PackageManagerService.java revision 36ecd08dc1627a7ed9c0ef498b41c40a66d646b0
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_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.admin.DevicePolicyManagerInternal;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128import android.content.pm.FeatureInfo;
129import android.content.pm.IOnPermissionsChangeListener;
130import android.content.pm.IPackageDataObserver;
131import android.content.pm.IPackageDeleteObserver;
132import android.content.pm.IPackageDeleteObserver2;
133import android.content.pm.IPackageInstallObserver2;
134import android.content.pm.IPackageInstaller;
135import android.content.pm.IPackageManager;
136import android.content.pm.IPackageMoveObserver;
137import android.content.pm.IPackageStatsObserver;
138import android.content.pm.InstrumentationInfo;
139import android.content.pm.IntentFilterVerificationInfo;
140import android.content.pm.KeySet;
141import android.content.pm.PackageCleanItem;
142import android.content.pm.PackageInfo;
143import android.content.pm.PackageInfoLite;
144import android.content.pm.PackageInstaller;
145import android.content.pm.PackageManager;
146import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147import android.content.pm.PackageManagerInternal;
148import android.content.pm.PackageParser;
149import android.content.pm.PackageParser.ActivityIntentInfo;
150import android.content.pm.PackageParser.PackageLite;
151import android.content.pm.PackageParser.PackageParserException;
152import android.content.pm.PackageStats;
153import android.content.pm.PackageUserState;
154import android.content.pm.ParceledListSlice;
155import android.content.pm.PermissionGroupInfo;
156import android.content.pm.PermissionInfo;
157import android.content.pm.ProviderInfo;
158import android.content.pm.ResolveInfo;
159import android.content.pm.ServiceInfo;
160import android.content.pm.Signature;
161import android.content.pm.UserInfo;
162import android.content.pm.VerifierDeviceIdentity;
163import android.content.pm.VerifierInfo;
164import android.content.res.Resources;
165import android.graphics.Bitmap;
166import android.hardware.display.DisplayManager;
167import android.net.INetworkPolicyManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.security.KeyStore;
201import android.security.SystemKeyStore;
202import android.system.ErrnoException;
203import android.system.Os;
204import android.text.TextUtils;
205import android.text.format.DateUtils;
206import android.util.ArrayMap;
207import android.util.ArraySet;
208import android.util.AtomicFile;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.EventLogTags;
243import com.android.server.FgThread;
244import com.android.server.IntentResolver;
245import com.android.server.LocalServices;
246import com.android.server.ServiceThread;
247import com.android.server.SystemConfig;
248import com.android.server.Watchdog;
249import com.android.server.net.NetworkPolicyManagerInternal;
250import com.android.server.pm.PermissionsState.PermissionState;
251import com.android.server.pm.Settings.DatabaseVersion;
252import com.android.server.pm.Settings.VersionInfo;
253import com.android.server.storage.DeviceStorageMonitorInternal;
254
255import dalvik.system.CloseGuard;
256import dalvik.system.DexFile;
257import dalvik.system.VMRuntime;
258
259import libcore.io.IoUtils;
260import libcore.util.EmptyArray;
261
262import org.xmlpull.v1.XmlPullParser;
263import org.xmlpull.v1.XmlPullParserException;
264import org.xmlpull.v1.XmlSerializer;
265
266import java.io.BufferedInputStream;
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.InputStream;
280import java.io.PrintWriter;
281import java.nio.charset.StandardCharsets;
282import java.security.DigestInputStream;
283import java.security.MessageDigest;
284import java.security.NoSuchAlgorithmException;
285import java.security.PublicKey;
286import java.security.cert.Certificate;
287import java.security.cert.CertificateEncodingException;
288import java.security.cert.CertificateException;
289import java.text.SimpleDateFormat;
290import java.util.ArrayList;
291import java.util.Arrays;
292import java.util.Collection;
293import java.util.Collections;
294import java.util.Comparator;
295import java.util.Date;
296import java.util.HashSet;
297import java.util.Iterator;
298import java.util.List;
299import java.util.Map;
300import java.util.Objects;
301import java.util.Set;
302import java.util.concurrent.CountDownLatch;
303import java.util.concurrent.TimeUnit;
304import java.util.concurrent.atomic.AtomicBoolean;
305import java.util.concurrent.atomic.AtomicInteger;
306import java.util.concurrent.atomic.AtomicLong;
307
308/**
309 * Keep track of all those APKs everywhere.
310 * <p>
311 * Internally there are two important locks:
312 * <ul>
313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
314 * and other related state. It is a fine-grained lock that should only be held
315 * momentarily, as it's one of the most contended locks in the system.
316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
317 * operations typically involve heavy lifting of application data on disk. Since
318 * {@code installd} is single-threaded, and it's operations can often be slow,
319 * this lock should never be acquired while already holding {@link #mPackages}.
320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
321 * holding {@link #mInstallLock}.
322 * </ul>
323 * Many internal methods rely on the caller to hold the appropriate locks, and
324 * this contract is expressed through method name suffixes:
325 * <ul>
326 * <li>fooLI(): the caller must hold {@link #mInstallLock}
327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
328 * being modified must be frozen
329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
331 * </ul>
332 * <p>
333 * Because this class is very central to the platform's security; please run all
334 * CTS and unit tests whenever making modifications:
335 *
336 * <pre>
337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
339 * </pre>
340 */
341public class PackageManagerService extends IPackageManager.Stub {
342    static final String TAG = "PackageManager";
343    static final boolean DEBUG_SETTINGS = false;
344    static final boolean DEBUG_PREFERRED = false;
345    static final boolean DEBUG_UPGRADE = false;
346    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
347    private static final boolean DEBUG_BACKUP = false;
348    private static final boolean DEBUG_INSTALL = false;
349    private static final boolean DEBUG_REMOVE = false;
350    private static final boolean DEBUG_BROADCASTS = false;
351    private static final boolean DEBUG_SHOW_INFO = false;
352    private static final boolean DEBUG_PACKAGE_INFO = false;
353    private static final boolean DEBUG_INTENT_MATCHING = false;
354    private static final boolean DEBUG_PACKAGE_SCANNING = false;
355    private static final boolean DEBUG_VERIFY = false;
356    private static final boolean DEBUG_FILTERS = false;
357
358    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
359    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
360    // user, but by default initialize to this.
361    static final boolean DEBUG_DEXOPT = false;
362
363    private static final boolean DEBUG_ABI_SELECTION = false;
364    private static final boolean DEBUG_EPHEMERAL = false;
365    private static final boolean DEBUG_TRIAGED_MISSING = false;
366    private static final boolean DEBUG_APP_DATA = false;
367
368    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
369
370    private static final boolean DISABLE_EPHEMERAL_APPS = true;
371
372    private static final int RADIO_UID = Process.PHONE_UID;
373    private static final int LOG_UID = Process.LOG_UID;
374    private static final int NFC_UID = Process.NFC_UID;
375    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
376    private static final int SHELL_UID = Process.SHELL_UID;
377
378    // Cap the size of permission trees that 3rd party apps can define
379    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
380
381    // Suffix used during package installation when copying/moving
382    // package apks to install directory.
383    private static final String INSTALL_PACKAGE_SUFFIX = "-";
384
385    static final int SCAN_NO_DEX = 1<<1;
386    static final int SCAN_FORCE_DEX = 1<<2;
387    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
388    static final int SCAN_NEW_INSTALL = 1<<4;
389    static final int SCAN_NO_PATHS = 1<<5;
390    static final int SCAN_UPDATE_TIME = 1<<6;
391    static final int SCAN_DEFER_DEX = 1<<7;
392    static final int SCAN_BOOTING = 1<<8;
393    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
394    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
395    static final int SCAN_REPLACING = 1<<11;
396    static final int SCAN_REQUIRE_KNOWN = 1<<12;
397    static final int SCAN_MOVE = 1<<13;
398    static final int SCAN_INITIAL = 1<<14;
399    static final int SCAN_CHECK_ONLY = 1<<15;
400    static final int SCAN_DONT_KILL_APP = 1<<17;
401    static final int SCAN_IGNORE_FROZEN = 1<<18;
402
403    static final int REMOVE_CHATTY = 1<<16;
404
405    private static final int[] EMPTY_INT_ARRAY = new int[0];
406
407    /**
408     * Timeout (in milliseconds) after which the watchdog should declare that
409     * our handler thread is wedged.  The usual default for such things is one
410     * minute but we sometimes do very lengthy I/O operations on this thread,
411     * such as installing multi-gigabyte applications, so ours needs to be longer.
412     */
413    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
414
415    /**
416     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
417     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
418     * settings entry if available, otherwise we use the hardcoded default.  If it's been
419     * more than this long since the last fstrim, we force one during the boot sequence.
420     *
421     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
422     * one gets run at the next available charging+idle time.  This final mandatory
423     * no-fstrim check kicks in only of the other scheduling criteria is never met.
424     */
425    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
426
427    /**
428     * Whether verification is enabled by default.
429     */
430    private static final boolean DEFAULT_VERIFY_ENABLE = true;
431
432    /**
433     * The default maximum time to wait for the verification agent to return in
434     * milliseconds.
435     */
436    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
437
438    /**
439     * The default response for package verification timeout.
440     *
441     * This can be either PackageManager.VERIFICATION_ALLOW or
442     * PackageManager.VERIFICATION_REJECT.
443     */
444    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
445
446    static final String PLATFORM_PACKAGE_NAME = "android";
447
448    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
449
450    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
451            DEFAULT_CONTAINER_PACKAGE,
452            "com.android.defcontainer.DefaultContainerService");
453
454    private static final String KILL_APP_REASON_GIDS_CHANGED =
455            "permission grant or revoke changed gids";
456
457    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
458            "permissions revoked";
459
460    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
461
462    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
463
464    /** Permission grant: not grant the permission. */
465    private static final int GRANT_DENIED = 1;
466
467    /** Permission grant: grant the permission as an install permission. */
468    private static final int GRANT_INSTALL = 2;
469
470    /** Permission grant: grant the permission as a runtime one. */
471    private static final int GRANT_RUNTIME = 3;
472
473    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
474    private static final int GRANT_UPGRADE = 4;
475
476    /** Canonical intent used to identify what counts as a "web browser" app */
477    private static final Intent sBrowserIntent;
478    static {
479        sBrowserIntent = new Intent();
480        sBrowserIntent.setAction(Intent.ACTION_VIEW);
481        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
482        sBrowserIntent.setData(Uri.parse("http:"));
483    }
484
485    /**
486     * The set of all protected actions [i.e. those actions for which a high priority
487     * intent filter is disallowed].
488     */
489    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
490    static {
491        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
492        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
494        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
495    }
496
497    // Compilation reasons.
498    public static final int REASON_FIRST_BOOT = 0;
499    public static final int REASON_BOOT = 1;
500    public static final int REASON_INSTALL = 2;
501    public static final int REASON_BACKGROUND_DEXOPT = 3;
502    public static final int REASON_AB_OTA = 4;
503    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
504    public static final int REASON_SHARED_APK = 6;
505    public static final int REASON_FORCED_DEXOPT = 7;
506
507    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
508
509    /** Special library name that skips shared libraries check during compilation. */
510    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
511
512    final ServiceThread mHandlerThread;
513
514    final PackageHandler mHandler;
515
516    private final ProcessLoggingHandler mProcessLoggingHandler;
517
518    /**
519     * Messages for {@link #mHandler} that need to wait for system ready before
520     * being dispatched.
521     */
522    private ArrayList<Message> mPostSystemReadyMessages;
523
524    final int mSdkVersion = Build.VERSION.SDK_INT;
525
526    final Context mContext;
527    final boolean mFactoryTest;
528    final boolean mOnlyCore;
529    final DisplayMetrics mMetrics;
530    final int mDefParseFlags;
531    final String[] mSeparateProcesses;
532    final boolean mIsUpgrade;
533    final boolean mIsPreNUpgrade;
534
535    /** The location for ASEC container files on internal storage. */
536    final String mAsecInternalPath;
537
538    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
539    // LOCK HELD.  Can be called with mInstallLock held.
540    @GuardedBy("mInstallLock")
541    final Installer mInstaller;
542
543    /** Directory where installed third-party apps stored */
544    final File mAppInstallDir;
545    final File mEphemeralInstallDir;
546
547    /**
548     * Directory to which applications installed internally have their
549     * 32 bit native libraries copied.
550     */
551    private File mAppLib32InstallDir;
552
553    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
554    // apps.
555    final File mDrmAppPrivateInstallDir;
556
557    // ----------------------------------------------------------------
558
559    // Lock for state used when installing and doing other long running
560    // operations.  Methods that must be called with this lock held have
561    // the suffix "LI".
562    final Object mInstallLock = new Object();
563
564    // ----------------------------------------------------------------
565
566    // Keys are String (package name), values are Package.  This also serves
567    // as the lock for the global state.  Methods that must be called with
568    // this lock held have the prefix "LP".
569    @GuardedBy("mPackages")
570    final ArrayMap<String, PackageParser.Package> mPackages =
571            new ArrayMap<String, PackageParser.Package>();
572
573    final ArrayMap<String, Set<String>> mKnownCodebase =
574            new ArrayMap<String, Set<String>>();
575
576    // Tracks available target package names -> overlay package paths.
577    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
578        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
579
580    /**
581     * Tracks new system packages [received in an OTA] that we expect to
582     * find updated user-installed versions. Keys are package name, values
583     * are package location.
584     */
585    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
586    /**
587     * Tracks high priority intent filters for protected actions. During boot, certain
588     * filter actions are protected and should never be allowed to have a high priority
589     * intent filter for them. However, there is one, and only one exception -- the
590     * setup wizard. It must be able to define a high priority intent filter for these
591     * actions to ensure there are no escapes from the wizard. We need to delay processing
592     * of these during boot as we need to look at all of the system packages in order
593     * to know which component is the setup wizard.
594     */
595    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
596    /**
597     * Whether or not processing protected filters should be deferred.
598     */
599    private boolean mDeferProtectedFilters = true;
600
601    /**
602     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
603     */
604    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
605    /**
606     * Whether or not system app permissions should be promoted from install to runtime.
607     */
608    boolean mPromoteSystemApps;
609
610    @GuardedBy("mPackages")
611    final Settings mSettings;
612
613    /**
614     * Set of package names that are currently "frozen", which means active
615     * surgery is being done on the code/data for that package. The platform
616     * will refuse to launch frozen packages to avoid race conditions.
617     *
618     * @see PackageFreezer
619     */
620    @GuardedBy("mPackages")
621    final ArraySet<String> mFrozenPackages = new ArraySet<>();
622
623    boolean mRestoredSettings;
624
625    // System configuration read by SystemConfig.
626    final int[] mGlobalGids;
627    final SparseArray<ArraySet<String>> mSystemPermissions;
628    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
629
630    // If mac_permissions.xml was found for seinfo labeling.
631    boolean mFoundPolicyFile;
632
633    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
634
635    public static final class SharedLibraryEntry {
636        public final String path;
637        public final String apk;
638
639        SharedLibraryEntry(String _path, String _apk) {
640            path = _path;
641            apk = _apk;
642        }
643    }
644
645    // Currently known shared libraries.
646    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
647            new ArrayMap<String, SharedLibraryEntry>();
648
649    // All available activities, for your resolving pleasure.
650    final ActivityIntentResolver mActivities =
651            new ActivityIntentResolver();
652
653    // All available receivers, for your resolving pleasure.
654    final ActivityIntentResolver mReceivers =
655            new ActivityIntentResolver();
656
657    // All available services, for your resolving pleasure.
658    final ServiceIntentResolver mServices = new ServiceIntentResolver();
659
660    // All available providers, for your resolving pleasure.
661    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
662
663    // Mapping from provider base names (first directory in content URI codePath)
664    // to the provider information.
665    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
666            new ArrayMap<String, PackageParser.Provider>();
667
668    // Mapping from instrumentation class names to info about them.
669    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
670            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
671
672    // Mapping from permission names to info about them.
673    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
674            new ArrayMap<String, PackageParser.PermissionGroup>();
675
676    // Packages whose data we have transfered into another package, thus
677    // should no longer exist.
678    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
679
680    // Broadcast actions that are only available to the system.
681    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
682
683    /** List of packages waiting for verification. */
684    final SparseArray<PackageVerificationState> mPendingVerification
685            = new SparseArray<PackageVerificationState>();
686
687    /** Set of packages associated with each app op permission. */
688    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
689
690    final PackageInstallerService mInstallerService;
691
692    private final PackageDexOptimizer mPackageDexOptimizer;
693
694    private AtomicInteger mNextMoveId = new AtomicInteger();
695    private final MoveCallbacks mMoveCallbacks;
696
697    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
698
699    // Cache of users who need badging.
700    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
701
702    /** Token for keys in mPendingVerification. */
703    private int mPendingVerificationToken = 0;
704
705    volatile boolean mSystemReady;
706    volatile boolean mSafeMode;
707    volatile boolean mHasSystemUidErrors;
708
709    ApplicationInfo mAndroidApplication;
710    final ActivityInfo mResolveActivity = new ActivityInfo();
711    final ResolveInfo mResolveInfo = new ResolveInfo();
712    ComponentName mResolveComponentName;
713    PackageParser.Package mPlatformPackage;
714    ComponentName mCustomResolverComponentName;
715
716    boolean mResolverReplaced = false;
717
718    private final @Nullable ComponentName mIntentFilterVerifierComponent;
719    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
720
721    private int mIntentFilterVerificationToken = 0;
722
723    /** Component that knows whether or not an ephemeral application exists */
724    final ComponentName mEphemeralResolverComponent;
725    /** The service connection to the ephemeral resolver */
726    final EphemeralResolverConnection mEphemeralResolverConnection;
727
728    /** Component used to install ephemeral applications */
729    final ComponentName mEphemeralInstallerComponent;
730    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
731    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
732
733    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
734            = new SparseArray<IntentFilterVerificationState>();
735
736    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
737            new DefaultPermissionGrantPolicy(this);
738
739    // List of packages names to keep cached, even if they are uninstalled for all users
740    private List<String> mKeepUninstalledPackages;
741
742    private UserManagerInternal mUserManagerInternal;
743
744    private static class IFVerificationParams {
745        PackageParser.Package pkg;
746        boolean replacing;
747        int userId;
748        int verifierUid;
749
750        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
751                int _userId, int _verifierUid) {
752            pkg = _pkg;
753            replacing = _replacing;
754            userId = _userId;
755            replacing = _replacing;
756            verifierUid = _verifierUid;
757        }
758    }
759
760    private interface IntentFilterVerifier<T extends IntentFilter> {
761        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
762                                               T filter, String packageName);
763        void startVerifications(int userId);
764        void receiveVerificationResponse(int verificationId);
765    }
766
767    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
768        private Context mContext;
769        private ComponentName mIntentFilterVerifierComponent;
770        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
771
772        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
773            mContext = context;
774            mIntentFilterVerifierComponent = verifierComponent;
775        }
776
777        private String getDefaultScheme() {
778            return IntentFilter.SCHEME_HTTPS;
779        }
780
781        @Override
782        public void startVerifications(int userId) {
783            // Launch verifications requests
784            int count = mCurrentIntentFilterVerifications.size();
785            for (int n=0; n<count; n++) {
786                int verificationId = mCurrentIntentFilterVerifications.get(n);
787                final IntentFilterVerificationState ivs =
788                        mIntentFilterVerificationStates.get(verificationId);
789
790                String packageName = ivs.getPackageName();
791
792                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
793                final int filterCount = filters.size();
794                ArraySet<String> domainsSet = new ArraySet<>();
795                for (int m=0; m<filterCount; m++) {
796                    PackageParser.ActivityIntentInfo filter = filters.get(m);
797                    domainsSet.addAll(filter.getHostsList());
798                }
799                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
800                synchronized (mPackages) {
801                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
802                            packageName, domainsList) != null) {
803                        scheduleWriteSettingsLocked();
804                    }
805                }
806                sendVerificationRequest(userId, verificationId, ivs);
807            }
808            mCurrentIntentFilterVerifications.clear();
809        }
810
811        private void sendVerificationRequest(int userId, int verificationId,
812                IntentFilterVerificationState ivs) {
813
814            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
815            verificationIntent.putExtra(
816                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
817                    verificationId);
818            verificationIntent.putExtra(
819                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
820                    getDefaultScheme());
821            verificationIntent.putExtra(
822                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
823                    ivs.getHostsString());
824            verificationIntent.putExtra(
825                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
826                    ivs.getPackageName());
827            verificationIntent.setComponent(mIntentFilterVerifierComponent);
828            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
829
830            UserHandle user = new UserHandle(userId);
831            mContext.sendBroadcastAsUser(verificationIntent, user);
832            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
833                    "Sending IntentFilter verification broadcast");
834        }
835
836        public void receiveVerificationResponse(int verificationId) {
837            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
838
839            final boolean verified = ivs.isVerified();
840
841            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
842            final int count = filters.size();
843            if (DEBUG_DOMAIN_VERIFICATION) {
844                Slog.i(TAG, "Received verification response " + verificationId
845                        + " for " + count + " filters, verified=" + verified);
846            }
847            for (int n=0; n<count; n++) {
848                PackageParser.ActivityIntentInfo filter = filters.get(n);
849                filter.setVerified(verified);
850
851                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
852                        + " verified with result:" + verified + " and hosts:"
853                        + ivs.getHostsString());
854            }
855
856            mIntentFilterVerificationStates.remove(verificationId);
857
858            final String packageName = ivs.getPackageName();
859            IntentFilterVerificationInfo ivi = null;
860
861            synchronized (mPackages) {
862                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
863            }
864            if (ivi == null) {
865                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
866                        + verificationId + " packageName:" + packageName);
867                return;
868            }
869            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
870                    "Updating IntentFilterVerificationInfo for package " + packageName
871                            +" verificationId:" + verificationId);
872
873            synchronized (mPackages) {
874                if (verified) {
875                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
876                } else {
877                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
878                }
879                scheduleWriteSettingsLocked();
880
881                final int userId = ivs.getUserId();
882                if (userId != UserHandle.USER_ALL) {
883                    final int userStatus =
884                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
885
886                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
887                    boolean needUpdate = false;
888
889                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
890                    // already been set by the User thru the Disambiguation dialog
891                    switch (userStatus) {
892                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
893                            if (verified) {
894                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
895                            } else {
896                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
897                            }
898                            needUpdate = true;
899                            break;
900
901                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
902                            if (verified) {
903                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
904                                needUpdate = true;
905                            }
906                            break;
907
908                        default:
909                            // Nothing to do
910                    }
911
912                    if (needUpdate) {
913                        mSettings.updateIntentFilterVerificationStatusLPw(
914                                packageName, updatedStatus, userId);
915                        scheduleWritePackageRestrictionsLocked(userId);
916                    }
917                }
918            }
919        }
920
921        @Override
922        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
923                    ActivityIntentInfo filter, String packageName) {
924            if (!hasValidDomains(filter)) {
925                return false;
926            }
927            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
928            if (ivs == null) {
929                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
930                        packageName);
931            }
932            if (DEBUG_DOMAIN_VERIFICATION) {
933                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
934            }
935            ivs.addFilter(filter);
936            return true;
937        }
938
939        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
940                int userId, int verificationId, String packageName) {
941            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
942                    verifierUid, userId, packageName);
943            ivs.setPendingState();
944            synchronized (mPackages) {
945                mIntentFilterVerificationStates.append(verificationId, ivs);
946                mCurrentIntentFilterVerifications.add(verificationId);
947            }
948            return ivs;
949        }
950    }
951
952    private static boolean hasValidDomains(ActivityIntentInfo filter) {
953        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
954                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
955                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
956    }
957
958    // Set of pending broadcasts for aggregating enable/disable of components.
959    static class PendingPackageBroadcasts {
960        // for each user id, a map of <package name -> components within that package>
961        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
962
963        public PendingPackageBroadcasts() {
964            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
965        }
966
967        public ArrayList<String> get(int userId, String packageName) {
968            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
969            return packages.get(packageName);
970        }
971
972        public void put(int userId, String packageName, ArrayList<String> components) {
973            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
974            packages.put(packageName, components);
975        }
976
977        public void remove(int userId, String packageName) {
978            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
979            if (packages != null) {
980                packages.remove(packageName);
981            }
982        }
983
984        public void remove(int userId) {
985            mUidMap.remove(userId);
986        }
987
988        public int userIdCount() {
989            return mUidMap.size();
990        }
991
992        public int userIdAt(int n) {
993            return mUidMap.keyAt(n);
994        }
995
996        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
997            return mUidMap.get(userId);
998        }
999
1000        public int size() {
1001            // total number of pending broadcast entries across all userIds
1002            int num = 0;
1003            for (int i = 0; i< mUidMap.size(); i++) {
1004                num += mUidMap.valueAt(i).size();
1005            }
1006            return num;
1007        }
1008
1009        public void clear() {
1010            mUidMap.clear();
1011        }
1012
1013        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1014            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1015            if (map == null) {
1016                map = new ArrayMap<String, ArrayList<String>>();
1017                mUidMap.put(userId, map);
1018            }
1019            return map;
1020        }
1021    }
1022    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1023
1024    // Service Connection to remote media container service to copy
1025    // package uri's from external media onto secure containers
1026    // or internal storage.
1027    private IMediaContainerService mContainerService = null;
1028
1029    static final int SEND_PENDING_BROADCAST = 1;
1030    static final int MCS_BOUND = 3;
1031    static final int END_COPY = 4;
1032    static final int INIT_COPY = 5;
1033    static final int MCS_UNBIND = 6;
1034    static final int START_CLEANING_PACKAGE = 7;
1035    static final int FIND_INSTALL_LOC = 8;
1036    static final int POST_INSTALL = 9;
1037    static final int MCS_RECONNECT = 10;
1038    static final int MCS_GIVE_UP = 11;
1039    static final int UPDATED_MEDIA_STATUS = 12;
1040    static final int WRITE_SETTINGS = 13;
1041    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1042    static final int PACKAGE_VERIFIED = 15;
1043    static final int CHECK_PENDING_VERIFICATION = 16;
1044    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1045    static final int INTENT_FILTER_VERIFIED = 18;
1046
1047    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1048
1049    // Delay time in millisecs
1050    static final int BROADCAST_DELAY = 10 * 1000;
1051
1052    static UserManagerService sUserManager;
1053
1054    // Stores a list of users whose package restrictions file needs to be updated
1055    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1056
1057    final private DefaultContainerConnection mDefContainerConn =
1058            new DefaultContainerConnection();
1059    class DefaultContainerConnection implements ServiceConnection {
1060        public void onServiceConnected(ComponentName name, IBinder service) {
1061            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1062            IMediaContainerService imcs =
1063                IMediaContainerService.Stub.asInterface(service);
1064            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1065        }
1066
1067        public void onServiceDisconnected(ComponentName name) {
1068            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1069        }
1070    }
1071
1072    // Recordkeeping of restore-after-install operations that are currently in flight
1073    // between the Package Manager and the Backup Manager
1074    static class PostInstallData {
1075        public InstallArgs args;
1076        public PackageInstalledInfo res;
1077
1078        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1079            args = _a;
1080            res = _r;
1081        }
1082    }
1083
1084    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1085    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1086
1087    // XML tags for backup/restore of various bits of state
1088    private static final String TAG_PREFERRED_BACKUP = "pa";
1089    private static final String TAG_DEFAULT_APPS = "da";
1090    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1091
1092    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1093    private static final String TAG_ALL_GRANTS = "rt-grants";
1094    private static final String TAG_GRANT = "grant";
1095    private static final String ATTR_PACKAGE_NAME = "pkg";
1096
1097    private static final String TAG_PERMISSION = "perm";
1098    private static final String ATTR_PERMISSION_NAME = "name";
1099    private static final String ATTR_IS_GRANTED = "g";
1100    private static final String ATTR_USER_SET = "set";
1101    private static final String ATTR_USER_FIXED = "fixed";
1102    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1103
1104    // System/policy permission grants are not backed up
1105    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1106            FLAG_PERMISSION_POLICY_FIXED
1107            | FLAG_PERMISSION_SYSTEM_FIXED
1108            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1109
1110    // And we back up these user-adjusted states
1111    private static final int USER_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_USER_SET
1113            | FLAG_PERMISSION_USER_FIXED
1114            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1115
1116    final @Nullable String mRequiredVerifierPackage;
1117    final @NonNull String mRequiredInstallerPackage;
1118    final @Nullable String mSetupWizardPackage;
1119    final @NonNull String mServicesSystemSharedLibraryPackageName;
1120    final @NonNull String mSharedSystemSharedLibraryPackageName;
1121
1122    private final PackageUsage mPackageUsage = new PackageUsage();
1123
1124    private class PackageUsage {
1125        private static final int WRITE_INTERVAL
1126            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1127
1128        private final Object mFileLock = new Object();
1129        private final AtomicLong mLastWritten = new AtomicLong(0);
1130        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1131
1132        private boolean mIsHistoricalPackageUsageAvailable = true;
1133
1134        boolean isHistoricalPackageUsageAvailable() {
1135            return mIsHistoricalPackageUsageAvailable;
1136        }
1137
1138        void write(boolean force) {
1139            if (force) {
1140                writeInternal();
1141                return;
1142            }
1143            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1144                && !DEBUG_DEXOPT) {
1145                return;
1146            }
1147            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1148                new Thread("PackageUsage_DiskWriter") {
1149                    @Override
1150                    public void run() {
1151                        try {
1152                            writeInternal();
1153                        } finally {
1154                            mBackgroundWriteRunning.set(false);
1155                        }
1156                    }
1157                }.start();
1158            }
1159        }
1160
1161        private void writeInternal() {
1162            synchronized (mPackages) {
1163                synchronized (mFileLock) {
1164                    AtomicFile file = getFile();
1165                    FileOutputStream f = null;
1166                    try {
1167                        f = file.startWrite();
1168                        BufferedOutputStream out = new BufferedOutputStream(f);
1169                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1170                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1171                        StringBuilder sb = new StringBuilder();
1172
1173                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1174                        sb.append('\n');
1175                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1176
1177                        for (PackageParser.Package pkg : mPackages.values()) {
1178                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1179                                continue;
1180                            }
1181                            sb.setLength(0);
1182                            sb.append(pkg.packageName);
1183                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1184                                sb.append(' ');
1185                                sb.append(usageTimeInMillis);
1186                            }
1187                            sb.append('\n');
1188                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1189                        }
1190                        out.flush();
1191                        file.finishWrite(f);
1192                    } catch (IOException e) {
1193                        if (f != null) {
1194                            file.failWrite(f);
1195                        }
1196                        Log.e(TAG, "Failed to write package usage times", e);
1197                    }
1198                }
1199            }
1200            mLastWritten.set(SystemClock.elapsedRealtime());
1201        }
1202
1203        void readLP() {
1204            synchronized (mFileLock) {
1205                AtomicFile file = getFile();
1206                BufferedInputStream in = null;
1207                try {
1208                    in = new BufferedInputStream(file.openRead());
1209                    StringBuffer sb = new StringBuffer();
1210
1211                    String firstLine = readLine(in, sb);
1212                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1213                        readVersion1LP(in, sb);
1214                    } else {
1215                        readVersion0LP(in, sb, firstLine);
1216                    }
1217                } catch (FileNotFoundException expected) {
1218                    mIsHistoricalPackageUsageAvailable = false;
1219                } catch (IOException e) {
1220                    Log.w(TAG, "Failed to read package usage times", e);
1221                } finally {
1222                    IoUtils.closeQuietly(in);
1223                }
1224            }
1225            mLastWritten.set(SystemClock.elapsedRealtime());
1226        }
1227
1228        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1229                throws IOException {
1230            // Initial version of the file had no version number and stored one
1231            // package-timestamp pair per line.
1232            // Note that the first line has already been read from the InputStream.
1233            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1234                String[] tokens = line.split(" ");
1235                if (tokens.length != 2) {
1236                    throw new IOException("Failed to parse " + line +
1237                            " as package-timestamp pair.");
1238                }
1239
1240                String packageName = tokens[0];
1241                PackageParser.Package pkg = mPackages.get(packageName);
1242                if (pkg == null) {
1243                    continue;
1244                }
1245
1246                long timestamp = parseAsLong(tokens[1]);
1247                for (int reason = 0;
1248                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1249                        reason++) {
1250                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1251                }
1252            }
1253        }
1254
1255        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1256            // Version 1 of the file started with the corresponding version
1257            // number and then stored a package name and eight timestamps per line.
1258            String line;
1259            while ((line = readLine(in, sb)) != null) {
1260                String[] tokens = line.split(" ");
1261                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1262                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1263                }
1264
1265                String packageName = tokens[0];
1266                PackageParser.Package pkg = mPackages.get(packageName);
1267                if (pkg == null) {
1268                    continue;
1269                }
1270
1271                for (int reason = 0;
1272                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1273                        reason++) {
1274                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1275                }
1276            }
1277        }
1278
1279        private long parseAsLong(String token) throws IOException {
1280            try {
1281                return Long.parseLong(token);
1282            } catch (NumberFormatException e) {
1283                throw new IOException("Failed to parse " + token + " as a long.", e);
1284            }
1285        }
1286
1287        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1288            return readToken(in, sb, '\n');
1289        }
1290
1291        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1292                throws IOException {
1293            sb.setLength(0);
1294            while (true) {
1295                int ch = in.read();
1296                if (ch == -1) {
1297                    if (sb.length() == 0) {
1298                        return null;
1299                    }
1300                    throw new IOException("Unexpected EOF");
1301                }
1302                if (ch == endOfToken) {
1303                    return sb.toString();
1304                }
1305                sb.append((char)ch);
1306            }
1307        }
1308
1309        private AtomicFile getFile() {
1310            File dataDir = Environment.getDataDirectory();
1311            File systemDir = new File(dataDir, "system");
1312            File fname = new File(systemDir, "package-usage.list");
1313            return new AtomicFile(fname);
1314        }
1315
1316        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1317        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1318    }
1319
1320    class PackageHandler extends Handler {
1321        private boolean mBound = false;
1322        final ArrayList<HandlerParams> mPendingInstalls =
1323            new ArrayList<HandlerParams>();
1324
1325        private boolean connectToService() {
1326            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1327                    " DefaultContainerService");
1328            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1329            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1331                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1332                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1333                mBound = true;
1334                return true;
1335            }
1336            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1337            return false;
1338        }
1339
1340        private void disconnectService() {
1341            mContainerService = null;
1342            mBound = false;
1343            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1344            mContext.unbindService(mDefContainerConn);
1345            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1346        }
1347
1348        PackageHandler(Looper looper) {
1349            super(looper);
1350        }
1351
1352        public void handleMessage(Message msg) {
1353            try {
1354                doHandleMessage(msg);
1355            } finally {
1356                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357            }
1358        }
1359
1360        void doHandleMessage(Message msg) {
1361            switch (msg.what) {
1362                case INIT_COPY: {
1363                    HandlerParams params = (HandlerParams) msg.obj;
1364                    int idx = mPendingInstalls.size();
1365                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1366                    // If a bind was already initiated we dont really
1367                    // need to do anything. The pending install
1368                    // will be processed later on.
1369                    if (!mBound) {
1370                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1371                                System.identityHashCode(mHandler));
1372                        // If this is the only one pending we might
1373                        // have to bind to the service again.
1374                        if (!connectToService()) {
1375                            Slog.e(TAG, "Failed to bind to media container service");
1376                            params.serviceError();
1377                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1378                                    System.identityHashCode(mHandler));
1379                            if (params.traceMethod != null) {
1380                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1381                                        params.traceCookie);
1382                            }
1383                            return;
1384                        } else {
1385                            // Once we bind to the service, the first
1386                            // pending request will be processed.
1387                            mPendingInstalls.add(idx, params);
1388                        }
1389                    } else {
1390                        mPendingInstalls.add(idx, params);
1391                        // Already bound to the service. Just make
1392                        // sure we trigger off processing the first request.
1393                        if (idx == 0) {
1394                            mHandler.sendEmptyMessage(MCS_BOUND);
1395                        }
1396                    }
1397                    break;
1398                }
1399                case MCS_BOUND: {
1400                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1401                    if (msg.obj != null) {
1402                        mContainerService = (IMediaContainerService) msg.obj;
1403                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1404                                System.identityHashCode(mHandler));
1405                    }
1406                    if (mContainerService == null) {
1407                        if (!mBound) {
1408                            // Something seriously wrong since we are not bound and we are not
1409                            // waiting for connection. Bail out.
1410                            Slog.e(TAG, "Cannot bind to media container service");
1411                            for (HandlerParams params : mPendingInstalls) {
1412                                // Indicate service bind error
1413                                params.serviceError();
1414                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1415                                        System.identityHashCode(params));
1416                                if (params.traceMethod != null) {
1417                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1418                                            params.traceMethod, params.traceCookie);
1419                                }
1420                                return;
1421                            }
1422                            mPendingInstalls.clear();
1423                        } else {
1424                            Slog.w(TAG, "Waiting to connect to media container service");
1425                        }
1426                    } else if (mPendingInstalls.size() > 0) {
1427                        HandlerParams params = mPendingInstalls.get(0);
1428                        if (params != null) {
1429                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1430                                    System.identityHashCode(params));
1431                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1432                            if (params.startCopy()) {
1433                                // We are done...  look for more work or to
1434                                // go idle.
1435                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1436                                        "Checking for more work or unbind...");
1437                                // Delete pending install
1438                                if (mPendingInstalls.size() > 0) {
1439                                    mPendingInstalls.remove(0);
1440                                }
1441                                if (mPendingInstalls.size() == 0) {
1442                                    if (mBound) {
1443                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1444                                                "Posting delayed MCS_UNBIND");
1445                                        removeMessages(MCS_UNBIND);
1446                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1447                                        // Unbind after a little delay, to avoid
1448                                        // continual thrashing.
1449                                        sendMessageDelayed(ubmsg, 10000);
1450                                    }
1451                                } else {
1452                                    // There are more pending requests in queue.
1453                                    // Just post MCS_BOUND message to trigger processing
1454                                    // of next pending install.
1455                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1456                                            "Posting MCS_BOUND for next work");
1457                                    mHandler.sendEmptyMessage(MCS_BOUND);
1458                                }
1459                            }
1460                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1461                        }
1462                    } else {
1463                        // Should never happen ideally.
1464                        Slog.w(TAG, "Empty queue");
1465                    }
1466                    break;
1467                }
1468                case MCS_RECONNECT: {
1469                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1470                    if (mPendingInstalls.size() > 0) {
1471                        if (mBound) {
1472                            disconnectService();
1473                        }
1474                        if (!connectToService()) {
1475                            Slog.e(TAG, "Failed to bind to media container service");
1476                            for (HandlerParams params : mPendingInstalls) {
1477                                // Indicate service bind error
1478                                params.serviceError();
1479                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1480                                        System.identityHashCode(params));
1481                            }
1482                            mPendingInstalls.clear();
1483                        }
1484                    }
1485                    break;
1486                }
1487                case MCS_UNBIND: {
1488                    // If there is no actual work left, then time to unbind.
1489                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1490
1491                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1492                        if (mBound) {
1493                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1494
1495                            disconnectService();
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        // There are more pending requests in queue.
1499                        // Just post MCS_BOUND message to trigger processing
1500                        // of next pending install.
1501                        mHandler.sendEmptyMessage(MCS_BOUND);
1502                    }
1503
1504                    break;
1505                }
1506                case MCS_GIVE_UP: {
1507                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1508                    HandlerParams params = mPendingInstalls.remove(0);
1509                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1510                            System.identityHashCode(params));
1511                    break;
1512                }
1513                case SEND_PENDING_BROADCAST: {
1514                    String packages[];
1515                    ArrayList<String> components[];
1516                    int size = 0;
1517                    int uids[];
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1519                    synchronized (mPackages) {
1520                        if (mPendingBroadcasts == null) {
1521                            return;
1522                        }
1523                        size = mPendingBroadcasts.size();
1524                        if (size <= 0) {
1525                            // Nothing to be done. Just return
1526                            return;
1527                        }
1528                        packages = new String[size];
1529                        components = new ArrayList[size];
1530                        uids = new int[size];
1531                        int i = 0;  // filling out the above arrays
1532
1533                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1534                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1535                            Iterator<Map.Entry<String, ArrayList<String>>> it
1536                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1537                                            .entrySet().iterator();
1538                            while (it.hasNext() && i < size) {
1539                                Map.Entry<String, ArrayList<String>> ent = it.next();
1540                                packages[i] = ent.getKey();
1541                                components[i] = ent.getValue();
1542                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1543                                uids[i] = (ps != null)
1544                                        ? UserHandle.getUid(packageUserId, ps.appId)
1545                                        : -1;
1546                                i++;
1547                            }
1548                        }
1549                        size = i;
1550                        mPendingBroadcasts.clear();
1551                    }
1552                    // Send broadcasts
1553                    for (int i = 0; i < size; i++) {
1554                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1555                    }
1556                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1557                    break;
1558                }
1559                case START_CLEANING_PACKAGE: {
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1561                    final String packageName = (String)msg.obj;
1562                    final int userId = msg.arg1;
1563                    final boolean andCode = msg.arg2 != 0;
1564                    synchronized (mPackages) {
1565                        if (userId == UserHandle.USER_ALL) {
1566                            int[] users = sUserManager.getUserIds();
1567                            for (int user : users) {
1568                                mSettings.addPackageToCleanLPw(
1569                                        new PackageCleanItem(user, packageName, andCode));
1570                            }
1571                        } else {
1572                            mSettings.addPackageToCleanLPw(
1573                                    new PackageCleanItem(userId, packageName, andCode));
1574                        }
1575                    }
1576                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1577                    startCleaningPackages();
1578                } break;
1579                case POST_INSTALL: {
1580                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1581
1582                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1583                    final boolean didRestore = (msg.arg2 != 0);
1584                    mRunningInstalls.delete(msg.arg1);
1585
1586                    if (data != null) {
1587                        InstallArgs args = data.args;
1588                        PackageInstalledInfo parentRes = data.res;
1589
1590                        final boolean grantPermissions = (args.installFlags
1591                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1592                        final boolean killApp = (args.installFlags
1593                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1594                        final String[] grantedPermissions = args.installGrantPermissions;
1595
1596                        // Handle the parent package
1597                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1598                                grantedPermissions, didRestore, args.installerPackageName,
1599                                args.observer);
1600
1601                        // Handle the child packages
1602                        final int childCount = (parentRes.addedChildPackages != null)
1603                                ? parentRes.addedChildPackages.size() : 0;
1604                        for (int i = 0; i < childCount; i++) {
1605                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1606                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1607                                    grantedPermissions, false, args.installerPackageName,
1608                                    args.observer);
1609                        }
1610
1611                        // Log tracing if needed
1612                        if (args.traceMethod != null) {
1613                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1614                                    args.traceCookie);
1615                        }
1616                    } else {
1617                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1618                    }
1619
1620                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1621                } break;
1622                case UPDATED_MEDIA_STATUS: {
1623                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1624                    boolean reportStatus = msg.arg1 == 1;
1625                    boolean doGc = msg.arg2 == 1;
1626                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1627                    if (doGc) {
1628                        // Force a gc to clear up stale containers.
1629                        Runtime.getRuntime().gc();
1630                    }
1631                    if (msg.obj != null) {
1632                        @SuppressWarnings("unchecked")
1633                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1634                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1635                        // Unload containers
1636                        unloadAllContainers(args);
1637                    }
1638                    if (reportStatus) {
1639                        try {
1640                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1641                            PackageHelper.getMountService().finishMediaUpdate();
1642                        } catch (RemoteException e) {
1643                            Log.e(TAG, "MountService not running?");
1644                        }
1645                    }
1646                } break;
1647                case WRITE_SETTINGS: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    synchronized (mPackages) {
1650                        removeMessages(WRITE_SETTINGS);
1651                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1652                        mSettings.writeLPr();
1653                        mDirtyUsers.clear();
1654                    }
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1656                } break;
1657                case WRITE_PACKAGE_RESTRICTIONS: {
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1659                    synchronized (mPackages) {
1660                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1661                        for (int userId : mDirtyUsers) {
1662                            mSettings.writePackageRestrictionsLPr(userId);
1663                        }
1664                        mDirtyUsers.clear();
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                } break;
1668                case CHECK_PENDING_VERIFICATION: {
1669                    final int verificationId = msg.arg1;
1670                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1671
1672                    if ((state != null) && !state.timeoutExtended()) {
1673                        final InstallArgs args = state.getInstallArgs();
1674                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1675
1676                        Slog.i(TAG, "Verification timed out for " + originUri);
1677                        mPendingVerification.remove(verificationId);
1678
1679                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1680
1681                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1682                            Slog.i(TAG, "Continuing with installation of " + originUri);
1683                            state.setVerifierResponse(Binder.getCallingUid(),
1684                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1685                            broadcastPackageVerified(verificationId, originUri,
1686                                    PackageManager.VERIFICATION_ALLOW,
1687                                    state.getInstallArgs().getUser());
1688                            try {
1689                                ret = args.copyApk(mContainerService, true);
1690                            } catch (RemoteException e) {
1691                                Slog.e(TAG, "Could not contact the ContainerService");
1692                            }
1693                        } else {
1694                            broadcastPackageVerified(verificationId, originUri,
1695                                    PackageManager.VERIFICATION_REJECT,
1696                                    state.getInstallArgs().getUser());
1697                        }
1698
1699                        Trace.asyncTraceEnd(
1700                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1701
1702                        processPendingInstall(args, ret);
1703                        mHandler.sendEmptyMessage(MCS_UNBIND);
1704                    }
1705                    break;
1706                }
1707                case PACKAGE_VERIFIED: {
1708                    final int verificationId = msg.arg1;
1709
1710                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1711                    if (state == null) {
1712                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1713                        break;
1714                    }
1715
1716                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1717
1718                    state.setVerifierResponse(response.callerUid, response.code);
1719
1720                    if (state.isVerificationComplete()) {
1721                        mPendingVerification.remove(verificationId);
1722
1723                        final InstallArgs args = state.getInstallArgs();
1724                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1725
1726                        int ret;
1727                        if (state.isInstallAllowed()) {
1728                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1729                            broadcastPackageVerified(verificationId, originUri,
1730                                    response.code, state.getInstallArgs().getUser());
1731                            try {
1732                                ret = args.copyApk(mContainerService, true);
1733                            } catch (RemoteException e) {
1734                                Slog.e(TAG, "Could not contact the ContainerService");
1735                            }
1736                        } else {
1737                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1738                        }
1739
1740                        Trace.asyncTraceEnd(
1741                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1742
1743                        processPendingInstall(args, ret);
1744                        mHandler.sendEmptyMessage(MCS_UNBIND);
1745                    }
1746
1747                    break;
1748                }
1749                case START_INTENT_FILTER_VERIFICATIONS: {
1750                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1751                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1752                            params.replacing, params.pkg);
1753                    break;
1754                }
1755                case INTENT_FILTER_VERIFIED: {
1756                    final int verificationId = msg.arg1;
1757
1758                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1759                            verificationId);
1760                    if (state == null) {
1761                        Slog.w(TAG, "Invalid IntentFilter verification token "
1762                                + verificationId + " received");
1763                        break;
1764                    }
1765
1766                    final int userId = state.getUserId();
1767
1768                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1769                            "Processing IntentFilter verification with token:"
1770                            + verificationId + " and userId:" + userId);
1771
1772                    final IntentFilterVerificationResponse response =
1773                            (IntentFilterVerificationResponse) msg.obj;
1774
1775                    state.setVerifierResponse(response.callerUid, response.code);
1776
1777                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1778                            "IntentFilter verification with token:" + verificationId
1779                            + " and userId:" + userId
1780                            + " is settings verifier response with response code:"
1781                            + response.code);
1782
1783                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1784                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1785                                + response.getFailedDomainsString());
1786                    }
1787
1788                    if (state.isVerificationComplete()) {
1789                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1790                    } else {
1791                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1792                                "IntentFilter verification with token:" + verificationId
1793                                + " was not said to be complete");
1794                    }
1795
1796                    break;
1797                }
1798            }
1799        }
1800    }
1801
1802    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1803            boolean killApp, String[] grantedPermissions,
1804            boolean launchedForRestore, String installerPackage,
1805            IPackageInstallObserver2 installObserver) {
1806        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1807            // Send the removed broadcasts
1808            if (res.removedInfo != null) {
1809                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1810            }
1811
1812            // Now that we successfully installed the package, grant runtime
1813            // permissions if requested before broadcasting the install.
1814            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1815                    >= Build.VERSION_CODES.M) {
1816                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1817            }
1818
1819            final boolean update = res.removedInfo != null
1820                    && res.removedInfo.removedPackage != null;
1821
1822            // If this is the first time we have child packages for a disabled privileged
1823            // app that had no children, we grant requested runtime permissions to the new
1824            // children if the parent on the system image had them already granted.
1825            if (res.pkg.parentPackage != null) {
1826                synchronized (mPackages) {
1827                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1828                }
1829            }
1830
1831            synchronized (mPackages) {
1832                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1833            }
1834
1835            final String packageName = res.pkg.applicationInfo.packageName;
1836            Bundle extras = new Bundle(1);
1837            extras.putInt(Intent.EXTRA_UID, res.uid);
1838
1839            // Determine the set of users who are adding this package for
1840            // the first time vs. those who are seeing an update.
1841            int[] firstUsers = EMPTY_INT_ARRAY;
1842            int[] updateUsers = EMPTY_INT_ARRAY;
1843            if (res.origUsers == null || res.origUsers.length == 0) {
1844                firstUsers = res.newUsers;
1845            } else {
1846                for (int newUser : res.newUsers) {
1847                    boolean isNew = true;
1848                    for (int origUser : res.origUsers) {
1849                        if (origUser == newUser) {
1850                            isNew = false;
1851                            break;
1852                        }
1853                    }
1854                    if (isNew) {
1855                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1856                    } else {
1857                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1858                    }
1859                }
1860            }
1861
1862            // Send installed broadcasts if the install/update is not ephemeral
1863            if (!isEphemeral(res.pkg)) {
1864                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1865
1866                // Send added for users that see the package for the first time
1867                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1868                        extras, 0 /*flags*/, null /*targetPackage*/,
1869                        null /*finishedReceiver*/, firstUsers);
1870
1871                // Send added for users that don't see the package for the first time
1872                if (update) {
1873                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1874                }
1875                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1876                        extras, 0 /*flags*/, null /*targetPackage*/,
1877                        null /*finishedReceiver*/, updateUsers);
1878
1879                // Send replaced for users that don't see the package for the first time
1880                if (update) {
1881                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1882                            packageName, extras, 0 /*flags*/,
1883                            null /*targetPackage*/, null /*finishedReceiver*/,
1884                            updateUsers);
1885                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1886                            null /*package*/, null /*extras*/, 0 /*flags*/,
1887                            packageName /*targetPackage*/,
1888                            null /*finishedReceiver*/, updateUsers);
1889                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1890                    // First-install and we did a restore, so we're responsible for the
1891                    // first-launch broadcast.
1892                    if (DEBUG_BACKUP) {
1893                        Slog.i(TAG, "Post-restore of " + packageName
1894                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1895                    }
1896                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1897                }
1898
1899                // Send broadcast package appeared if forward locked/external for all users
1900                // treat asec-hosted packages like removable media on upgrade
1901                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1902                    if (DEBUG_INSTALL) {
1903                        Slog.i(TAG, "upgrading pkg " + res.pkg
1904                                + " is ASEC-hosted -> AVAILABLE");
1905                    }
1906                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1907                    ArrayList<String> pkgList = new ArrayList<>(1);
1908                    pkgList.add(packageName);
1909                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1910                }
1911            }
1912
1913            // Work that needs to happen on first install within each user
1914            if (firstUsers != null && firstUsers.length > 0) {
1915                synchronized (mPackages) {
1916                    for (int userId : firstUsers) {
1917                        // If this app is a browser and it's newly-installed for some
1918                        // users, clear any default-browser state in those users. The
1919                        // app's nature doesn't depend on the user, so we can just check
1920                        // its browser nature in any user and generalize.
1921                        if (packageIsBrowser(packageName, userId)) {
1922                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1923                        }
1924
1925                        // We may also need to apply pending (restored) runtime
1926                        // permission grants within these users.
1927                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1928                    }
1929                }
1930            }
1931
1932            // Log current value of "unknown sources" setting
1933            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1934                    getUnknownSourcesSettings());
1935
1936            // Force a gc to clear up things
1937            Runtime.getRuntime().gc();
1938
1939            // Remove the replaced package's older resources safely now
1940            // We delete after a gc for applications  on sdcard.
1941            if (res.removedInfo != null && res.removedInfo.args != null) {
1942                synchronized (mInstallLock) {
1943                    res.removedInfo.args.doPostDeleteLI(true);
1944                }
1945            }
1946        }
1947
1948        // If someone is watching installs - notify them
1949        if (installObserver != null) {
1950            try {
1951                Bundle extras = extrasForInstallResult(res);
1952                installObserver.onPackageInstalled(res.name, res.returnCode,
1953                        res.returnMsg, extras);
1954            } catch (RemoteException e) {
1955                Slog.i(TAG, "Observer no longer exists.");
1956            }
1957        }
1958    }
1959
1960    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1961            PackageParser.Package pkg) {
1962        if (pkg.parentPackage == null) {
1963            return;
1964        }
1965        if (pkg.requestedPermissions == null) {
1966            return;
1967        }
1968        final PackageSetting disabledSysParentPs = mSettings
1969                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1970        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1971                || !disabledSysParentPs.isPrivileged()
1972                || (disabledSysParentPs.childPackageNames != null
1973                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1974            return;
1975        }
1976        final int[] allUserIds = sUserManager.getUserIds();
1977        final int permCount = pkg.requestedPermissions.size();
1978        for (int i = 0; i < permCount; i++) {
1979            String permission = pkg.requestedPermissions.get(i);
1980            BasePermission bp = mSettings.mPermissions.get(permission);
1981            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1982                continue;
1983            }
1984            for (int userId : allUserIds) {
1985                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1986                        permission, userId)) {
1987                    grantRuntimePermission(pkg.packageName, permission, userId);
1988                }
1989            }
1990        }
1991    }
1992
1993    private StorageEventListener mStorageListener = new StorageEventListener() {
1994        @Override
1995        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1996            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1997                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1998                    final String volumeUuid = vol.getFsUuid();
1999
2000                    // Clean up any users or apps that were removed or recreated
2001                    // while this volume was missing
2002                    reconcileUsers(volumeUuid);
2003                    reconcileApps(volumeUuid);
2004
2005                    // Clean up any install sessions that expired or were
2006                    // cancelled while this volume was missing
2007                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2008
2009                    loadPrivatePackages(vol);
2010
2011                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2012                    unloadPrivatePackages(vol);
2013                }
2014            }
2015
2016            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2017                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2018                    updateExternalMediaStatus(true, false);
2019                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2020                    updateExternalMediaStatus(false, false);
2021                }
2022            }
2023        }
2024
2025        @Override
2026        public void onVolumeForgotten(String fsUuid) {
2027            if (TextUtils.isEmpty(fsUuid)) {
2028                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2029                return;
2030            }
2031
2032            // Remove any apps installed on the forgotten volume
2033            synchronized (mPackages) {
2034                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2035                for (PackageSetting ps : packages) {
2036                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2037                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2038                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2039                }
2040
2041                mSettings.onVolumeForgotten(fsUuid);
2042                mSettings.writeLPr();
2043            }
2044        }
2045    };
2046
2047    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2048            String[] grantedPermissions) {
2049        for (int userId : userIds) {
2050            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2051        }
2052
2053        // We could have touched GID membership, so flush out packages.list
2054        synchronized (mPackages) {
2055            mSettings.writePackageListLPr();
2056        }
2057    }
2058
2059    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2060            String[] grantedPermissions) {
2061        SettingBase sb = (SettingBase) pkg.mExtras;
2062        if (sb == null) {
2063            return;
2064        }
2065
2066        PermissionsState permissionsState = sb.getPermissionsState();
2067
2068        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2069                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2070
2071        for (String permission : pkg.requestedPermissions) {
2072            final BasePermission bp;
2073            synchronized (mPackages) {
2074                bp = mSettings.mPermissions.get(permission);
2075            }
2076            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2077                    && (grantedPermissions == null
2078                           || ArrayUtils.contains(grantedPermissions, permission))) {
2079                final int flags = permissionsState.getPermissionFlags(permission, userId);
2080                // Installer cannot change immutable permissions.
2081                if ((flags & immutableFlags) == 0) {
2082                    grantRuntimePermission(pkg.packageName, permission, userId);
2083                }
2084            }
2085        }
2086    }
2087
2088    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2089        Bundle extras = null;
2090        switch (res.returnCode) {
2091            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2092                extras = new Bundle();
2093                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2094                        res.origPermission);
2095                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2096                        res.origPackage);
2097                break;
2098            }
2099            case PackageManager.INSTALL_SUCCEEDED: {
2100                extras = new Bundle();
2101                extras.putBoolean(Intent.EXTRA_REPLACING,
2102                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2103                break;
2104            }
2105        }
2106        return extras;
2107    }
2108
2109    void scheduleWriteSettingsLocked() {
2110        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2111            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2112        }
2113    }
2114
2115    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2116        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2117        scheduleWritePackageRestrictionsLocked(userId);
2118    }
2119
2120    void scheduleWritePackageRestrictionsLocked(int userId) {
2121        final int[] userIds = (userId == UserHandle.USER_ALL)
2122                ? sUserManager.getUserIds() : new int[]{userId};
2123        for (int nextUserId : userIds) {
2124            if (!sUserManager.exists(nextUserId)) return;
2125            mDirtyUsers.add(nextUserId);
2126            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2127                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2128            }
2129        }
2130    }
2131
2132    public static PackageManagerService main(Context context, Installer installer,
2133            boolean factoryTest, boolean onlyCore) {
2134        // Self-check for initial settings.
2135        PackageManagerServiceCompilerMapping.checkProperties();
2136
2137        PackageManagerService m = new PackageManagerService(context, installer,
2138                factoryTest, onlyCore);
2139        m.enableSystemUserPackages();
2140        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2141        // disabled after already being started.
2142        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2143                UserHandle.USER_SYSTEM);
2144        ServiceManager.addService("package", m);
2145        return m;
2146    }
2147
2148    private void enableSystemUserPackages() {
2149        if (!UserManager.isSplitSystemUser()) {
2150            return;
2151        }
2152        // For system user, enable apps based on the following conditions:
2153        // - app is whitelisted or belong to one of these groups:
2154        //   -- system app which has no launcher icons
2155        //   -- system app which has INTERACT_ACROSS_USERS permission
2156        //   -- system IME app
2157        // - app is not in the blacklist
2158        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2159        Set<String> enableApps = new ArraySet<>();
2160        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2161                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2162                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2163        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2164        enableApps.addAll(wlApps);
2165        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2166                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2167        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2168        enableApps.removeAll(blApps);
2169        Log.i(TAG, "Applications installed for system user: " + enableApps);
2170        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2171                UserHandle.SYSTEM);
2172        final int allAppsSize = allAps.size();
2173        synchronized (mPackages) {
2174            for (int i = 0; i < allAppsSize; i++) {
2175                String pName = allAps.get(i);
2176                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2177                // Should not happen, but we shouldn't be failing if it does
2178                if (pkgSetting == null) {
2179                    continue;
2180                }
2181                boolean install = enableApps.contains(pName);
2182                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2183                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2184                            + " for system user");
2185                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2186                }
2187            }
2188        }
2189    }
2190
2191    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2192        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2193                Context.DISPLAY_SERVICE);
2194        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2195    }
2196
2197    public PackageManagerService(Context context, Installer installer,
2198            boolean factoryTest, boolean onlyCore) {
2199        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2200                SystemClock.uptimeMillis());
2201
2202        if (mSdkVersion <= 0) {
2203            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2204        }
2205
2206        mContext = context;
2207        mFactoryTest = factoryTest;
2208        mOnlyCore = onlyCore;
2209        mMetrics = new DisplayMetrics();
2210        mSettings = new Settings(mPackages);
2211        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2212                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2213        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2214                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2215        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2216                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2217        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2218                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2219        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2220                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2221        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2222                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2223
2224        String separateProcesses = SystemProperties.get("debug.separate_processes");
2225        if (separateProcesses != null && separateProcesses.length() > 0) {
2226            if ("*".equals(separateProcesses)) {
2227                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2228                mSeparateProcesses = null;
2229                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2230            } else {
2231                mDefParseFlags = 0;
2232                mSeparateProcesses = separateProcesses.split(",");
2233                Slog.w(TAG, "Running with debug.separate_processes: "
2234                        + separateProcesses);
2235            }
2236        } else {
2237            mDefParseFlags = 0;
2238            mSeparateProcesses = null;
2239        }
2240
2241        mInstaller = installer;
2242        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2243                "*dexopt*");
2244        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2245
2246        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2247                FgThread.get().getLooper());
2248
2249        getDefaultDisplayMetrics(context, mMetrics);
2250
2251        SystemConfig systemConfig = SystemConfig.getInstance();
2252        mGlobalGids = systemConfig.getGlobalGids();
2253        mSystemPermissions = systemConfig.getSystemPermissions();
2254        mAvailableFeatures = systemConfig.getAvailableFeatures();
2255
2256        synchronized (mInstallLock) {
2257        // writer
2258        synchronized (mPackages) {
2259            mHandlerThread = new ServiceThread(TAG,
2260                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2261            mHandlerThread.start();
2262            mHandler = new PackageHandler(mHandlerThread.getLooper());
2263            mProcessLoggingHandler = new ProcessLoggingHandler();
2264            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2265
2266            File dataDir = Environment.getDataDirectory();
2267            mAppInstallDir = new File(dataDir, "app");
2268            mAppLib32InstallDir = new File(dataDir, "app-lib");
2269            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2270            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2271            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2272
2273            sUserManager = new UserManagerService(context, this, mPackages);
2274
2275            // Propagate permission configuration in to package manager.
2276            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2277                    = systemConfig.getPermissions();
2278            for (int i=0; i<permConfig.size(); i++) {
2279                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2280                BasePermission bp = mSettings.mPermissions.get(perm.name);
2281                if (bp == null) {
2282                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2283                    mSettings.mPermissions.put(perm.name, bp);
2284                }
2285                if (perm.gids != null) {
2286                    bp.setGids(perm.gids, perm.perUser);
2287                }
2288            }
2289
2290            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2291            for (int i=0; i<libConfig.size(); i++) {
2292                mSharedLibraries.put(libConfig.keyAt(i),
2293                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2294            }
2295
2296            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2297
2298            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2299
2300            String customResolverActivity = Resources.getSystem().getString(
2301                    R.string.config_customResolverActivity);
2302            if (TextUtils.isEmpty(customResolverActivity)) {
2303                customResolverActivity = null;
2304            } else {
2305                mCustomResolverComponentName = ComponentName.unflattenFromString(
2306                        customResolverActivity);
2307            }
2308
2309            long startTime = SystemClock.uptimeMillis();
2310
2311            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2312                    startTime);
2313
2314            // Set flag to monitor and not change apk file paths when
2315            // scanning install directories.
2316            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2317
2318            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2319            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2320
2321            if (bootClassPath == null) {
2322                Slog.w(TAG, "No BOOTCLASSPATH found!");
2323            }
2324
2325            if (systemServerClassPath == null) {
2326                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2327            }
2328
2329            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2330            final String[] dexCodeInstructionSets =
2331                    getDexCodeInstructionSets(
2332                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2333
2334            /**
2335             * Ensure all external libraries have had dexopt run on them.
2336             */
2337            if (mSharedLibraries.size() > 0) {
2338                // NOTE: For now, we're compiling these system "shared libraries"
2339                // (and framework jars) into all available architectures. It's possible
2340                // to compile them only when we come across an app that uses them (there's
2341                // already logic for that in scanPackageLI) but that adds some complexity.
2342                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2343                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2344                        final String lib = libEntry.path;
2345                        if (lib == null) {
2346                            continue;
2347                        }
2348
2349                        try {
2350                            // Shared libraries do not have profiles so we perform a full
2351                            // AOT compilation (if needed).
2352                            int dexoptNeeded = DexFile.getDexOptNeeded(
2353                                    lib, dexCodeInstructionSet,
2354                                    getCompilerFilterForReason(REASON_SHARED_APK),
2355                                    false /* newProfile */);
2356                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2357                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2358                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2359                                        getCompilerFilterForReason(REASON_SHARED_APK),
2360                                        StorageManager.UUID_PRIVATE_INTERNAL,
2361                                        SKIP_SHARED_LIBRARY_CHECK);
2362                            }
2363                        } catch (FileNotFoundException e) {
2364                            Slog.w(TAG, "Library not found: " + lib);
2365                        } catch (IOException | InstallerException e) {
2366                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2367                                    + e.getMessage());
2368                        }
2369                    }
2370                }
2371            }
2372
2373            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2374
2375            final VersionInfo ver = mSettings.getInternalVersion();
2376            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2377
2378            // when upgrading from pre-M, promote system app permissions from install to runtime
2379            mPromoteSystemApps =
2380                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2381
2382            // When upgrading from pre-N, we need to handle package extraction like first boot,
2383            // as there is no profiling data available.
2384            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2385
2386            // save off the names of pre-existing system packages prior to scanning; we don't
2387            // want to automatically grant runtime permissions for new system apps
2388            if (mPromoteSystemApps) {
2389                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2390                while (pkgSettingIter.hasNext()) {
2391                    PackageSetting ps = pkgSettingIter.next();
2392                    if (isSystemApp(ps)) {
2393                        mExistingSystemPackages.add(ps.name);
2394                    }
2395                }
2396            }
2397
2398            // Collect vendor overlay packages.
2399            // (Do this before scanning any apps.)
2400            // For security and version matching reason, only consider
2401            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2402            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2403            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2404                    | PackageParser.PARSE_IS_SYSTEM
2405                    | PackageParser.PARSE_IS_SYSTEM_DIR
2406                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2407
2408            // Find base frameworks (resource packages without code).
2409            scanDirTracedLI(frameworkDir, mDefParseFlags
2410                    | PackageParser.PARSE_IS_SYSTEM
2411                    | PackageParser.PARSE_IS_SYSTEM_DIR
2412                    | PackageParser.PARSE_IS_PRIVILEGED,
2413                    scanFlags | SCAN_NO_DEX, 0);
2414
2415            // Collected privileged system packages.
2416            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2417            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2418                    | PackageParser.PARSE_IS_SYSTEM
2419                    | PackageParser.PARSE_IS_SYSTEM_DIR
2420                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2421
2422            // Collect ordinary system packages.
2423            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2424            scanDirTracedLI(systemAppDir, mDefParseFlags
2425                    | PackageParser.PARSE_IS_SYSTEM
2426                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2427
2428            // Collect all vendor packages.
2429            File vendorAppDir = new File("/vendor/app");
2430            try {
2431                vendorAppDir = vendorAppDir.getCanonicalFile();
2432            } catch (IOException e) {
2433                // failed to look up canonical path, continue with original one
2434            }
2435            scanDirTracedLI(vendorAppDir, mDefParseFlags
2436                    | PackageParser.PARSE_IS_SYSTEM
2437                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2438
2439            // Collect all OEM packages.
2440            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2441            scanDirTracedLI(oemAppDir, mDefParseFlags
2442                    | PackageParser.PARSE_IS_SYSTEM
2443                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2444
2445            // Prune any system packages that no longer exist.
2446            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2447            if (!mOnlyCore) {
2448                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2449                while (psit.hasNext()) {
2450                    PackageSetting ps = psit.next();
2451
2452                    /*
2453                     * If this is not a system app, it can't be a
2454                     * disable system app.
2455                     */
2456                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2457                        continue;
2458                    }
2459
2460                    /*
2461                     * If the package is scanned, it's not erased.
2462                     */
2463                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2464                    if (scannedPkg != null) {
2465                        /*
2466                         * If the system app is both scanned and in the
2467                         * disabled packages list, then it must have been
2468                         * added via OTA. Remove it from the currently
2469                         * scanned package so the previously user-installed
2470                         * application can be scanned.
2471                         */
2472                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2473                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2474                                    + ps.name + "; removing system app.  Last known codePath="
2475                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2476                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2477                                    + scannedPkg.mVersionCode);
2478                            removePackageLI(scannedPkg, true);
2479                            mExpectingBetter.put(ps.name, ps.codePath);
2480                        }
2481
2482                        continue;
2483                    }
2484
2485                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2486                        psit.remove();
2487                        logCriticalInfo(Log.WARN, "System package " + ps.name
2488                                + " no longer exists; it's data will be wiped");
2489                        // Actual deletion of code and data will be handled by later
2490                        // reconciliation step
2491                    } else {
2492                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2493                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2494                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2495                        }
2496                    }
2497                }
2498            }
2499
2500            //look for any incomplete package installations
2501            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2502            for (int i = 0; i < deletePkgsList.size(); i++) {
2503                // Actual deletion of code and data will be handled by later
2504                // reconciliation step
2505                final String packageName = deletePkgsList.get(i).name;
2506                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2507                synchronized (mPackages) {
2508                    mSettings.removePackageLPw(packageName);
2509                }
2510            }
2511
2512            //delete tmp files
2513            deleteTempPackageFiles();
2514
2515            // Remove any shared userIDs that have no associated packages
2516            mSettings.pruneSharedUsersLPw();
2517
2518            if (!mOnlyCore) {
2519                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2520                        SystemClock.uptimeMillis());
2521                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2522
2523                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2524                        | PackageParser.PARSE_FORWARD_LOCK,
2525                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2526
2527                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2528                        | PackageParser.PARSE_IS_EPHEMERAL,
2529                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2530
2531                /**
2532                 * Remove disable package settings for any updated system
2533                 * apps that were removed via an OTA. If they're not a
2534                 * previously-updated app, remove them completely.
2535                 * Otherwise, just revoke their system-level permissions.
2536                 */
2537                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2538                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2539                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2540
2541                    String msg;
2542                    if (deletedPkg == null) {
2543                        msg = "Updated system package " + deletedAppName
2544                                + " no longer exists; it's data will be wiped";
2545                        // Actual deletion of code and data will be handled by later
2546                        // reconciliation step
2547                    } else {
2548                        msg = "Updated system app + " + deletedAppName
2549                                + " no longer present; removing system privileges for "
2550                                + deletedAppName;
2551
2552                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2553
2554                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2555                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2556                    }
2557                    logCriticalInfo(Log.WARN, msg);
2558                }
2559
2560                /**
2561                 * Make sure all system apps that we expected to appear on
2562                 * the userdata partition actually showed up. If they never
2563                 * appeared, crawl back and revive the system version.
2564                 */
2565                for (int i = 0; i < mExpectingBetter.size(); i++) {
2566                    final String packageName = mExpectingBetter.keyAt(i);
2567                    if (!mPackages.containsKey(packageName)) {
2568                        final File scanFile = mExpectingBetter.valueAt(i);
2569
2570                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2571                                + " but never showed up; reverting to system");
2572
2573                        int reparseFlags = mDefParseFlags;
2574                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2575                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2576                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2577                                    | PackageParser.PARSE_IS_PRIVILEGED;
2578                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2579                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2580                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2581                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2582                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2583                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2584                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2585                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2586                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2587                        } else {
2588                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2589                            continue;
2590                        }
2591
2592                        mSettings.enableSystemPackageLPw(packageName);
2593
2594                        try {
2595                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2596                        } catch (PackageManagerException e) {
2597                            Slog.e(TAG, "Failed to parse original system package: "
2598                                    + e.getMessage());
2599                        }
2600                    }
2601                }
2602            }
2603            mExpectingBetter.clear();
2604
2605            // Resolve protected action filters. Only the setup wizard is allowed to
2606            // have a high priority filter for these actions.
2607            mSetupWizardPackage = getSetupWizardPackageName();
2608            if (mProtectedFilters.size() > 0) {
2609                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2610                    Slog.i(TAG, "No setup wizard;"
2611                        + " All protected intents capped to priority 0");
2612                }
2613                for (ActivityIntentInfo filter : mProtectedFilters) {
2614                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2615                        if (DEBUG_FILTERS) {
2616                            Slog.i(TAG, "Found setup wizard;"
2617                                + " allow priority " + filter.getPriority() + ";"
2618                                + " package: " + filter.activity.info.packageName
2619                                + " activity: " + filter.activity.className
2620                                + " priority: " + filter.getPriority());
2621                        }
2622                        // skip setup wizard; allow it to keep the high priority filter
2623                        continue;
2624                    }
2625                    Slog.w(TAG, "Protected action; cap priority to 0;"
2626                            + " package: " + filter.activity.info.packageName
2627                            + " activity: " + filter.activity.className
2628                            + " origPrio: " + filter.getPriority());
2629                    filter.setPriority(0);
2630                }
2631            }
2632            mDeferProtectedFilters = false;
2633            mProtectedFilters.clear();
2634
2635            // Now that we know all of the shared libraries, update all clients to have
2636            // the correct library paths.
2637            updateAllSharedLibrariesLPw();
2638
2639            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2640                // NOTE: We ignore potential failures here during a system scan (like
2641                // the rest of the commands above) because there's precious little we
2642                // can do about it. A settings error is reported, though.
2643                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2644                        false /* boot complete */);
2645            }
2646
2647            // Now that we know all the packages we are keeping,
2648            // read and update their last usage times.
2649            mPackageUsage.readLP();
2650
2651            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2652                    SystemClock.uptimeMillis());
2653            Slog.i(TAG, "Time to scan packages: "
2654                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2655                    + " seconds");
2656
2657            // If the platform SDK has changed since the last time we booted,
2658            // we need to re-grant app permission to catch any new ones that
2659            // appear.  This is really a hack, and means that apps can in some
2660            // cases get permissions that the user didn't initially explicitly
2661            // allow...  it would be nice to have some better way to handle
2662            // this situation.
2663            int updateFlags = UPDATE_PERMISSIONS_ALL;
2664            if (ver.sdkVersion != mSdkVersion) {
2665                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2666                        + mSdkVersion + "; regranting permissions for internal storage");
2667                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2668            }
2669            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2670            ver.sdkVersion = mSdkVersion;
2671
2672            // If this is the first boot or an update from pre-M, and it is a normal
2673            // boot, then we need to initialize the default preferred apps across
2674            // all defined users.
2675            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2676                for (UserInfo user : sUserManager.getUsers(true)) {
2677                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2678                    applyFactoryDefaultBrowserLPw(user.id);
2679                    primeDomainVerificationsLPw(user.id);
2680                }
2681            }
2682
2683            // Prepare storage for system user really early during boot,
2684            // since core system apps like SettingsProvider and SystemUI
2685            // can't wait for user to start
2686            final int storageFlags;
2687            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2688                storageFlags = StorageManager.FLAG_STORAGE_DE;
2689            } else {
2690                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2691            }
2692            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2693                    storageFlags);
2694
2695            // If this is first boot after an OTA, and a normal boot, then
2696            // we need to clear code cache directories.
2697            if (mIsUpgrade && !onlyCore) {
2698                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2699                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2700                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2701                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2702                        // No apps are running this early, so no need to freeze
2703                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2704                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2705                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2706                    }
2707                    clearAppProfilesLIF(ps.pkg);
2708                }
2709                ver.fingerprint = Build.FINGERPRINT;
2710            }
2711
2712            checkDefaultBrowser();
2713
2714            // clear only after permissions and other defaults have been updated
2715            mExistingSystemPackages.clear();
2716            mPromoteSystemApps = false;
2717
2718            // All the changes are done during package scanning.
2719            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2720
2721            // can downgrade to reader
2722            mSettings.writeLPr();
2723
2724            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2725                    SystemClock.uptimeMillis());
2726
2727            if (!mOnlyCore) {
2728                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2729                mRequiredInstallerPackage = getRequiredInstallerLPr();
2730                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2731                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2732                        mIntentFilterVerifierComponent);
2733                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2734                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2735                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2736                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2737            } else {
2738                mRequiredVerifierPackage = null;
2739                mRequiredInstallerPackage = null;
2740                mIntentFilterVerifierComponent = null;
2741                mIntentFilterVerifier = null;
2742                mServicesSystemSharedLibraryPackageName = null;
2743                mSharedSystemSharedLibraryPackageName = null;
2744            }
2745
2746            mInstallerService = new PackageInstallerService(context, this);
2747
2748            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2749            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2750            // both the installer and resolver must be present to enable ephemeral
2751            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2752                if (DEBUG_EPHEMERAL) {
2753                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2754                            + " installer:" + ephemeralInstallerComponent);
2755                }
2756                mEphemeralResolverComponent = ephemeralResolverComponent;
2757                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2758                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2759                mEphemeralResolverConnection =
2760                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2761            } else {
2762                if (DEBUG_EPHEMERAL) {
2763                    final String missingComponent =
2764                            (ephemeralResolverComponent == null)
2765                            ? (ephemeralInstallerComponent == null)
2766                                    ? "resolver and installer"
2767                                    : "resolver"
2768                            : "installer";
2769                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2770                }
2771                mEphemeralResolverComponent = null;
2772                mEphemeralInstallerComponent = null;
2773                mEphemeralResolverConnection = null;
2774            }
2775
2776            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2777        } // synchronized (mPackages)
2778        } // synchronized (mInstallLock)
2779
2780        // Now after opening every single application zip, make sure they
2781        // are all flushed.  Not really needed, but keeps things nice and
2782        // tidy.
2783        Runtime.getRuntime().gc();
2784
2785        // The initial scanning above does many calls into installd while
2786        // holding the mPackages lock, but we're mostly interested in yelling
2787        // once we have a booted system.
2788        mInstaller.setWarnIfHeld(mPackages);
2789
2790        // Expose private service for system components to use.
2791        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2792    }
2793
2794    @Override
2795    public boolean isFirstBoot() {
2796        return !mRestoredSettings;
2797    }
2798
2799    @Override
2800    public boolean isOnlyCoreApps() {
2801        return mOnlyCore;
2802    }
2803
2804    @Override
2805    public boolean isUpgrade() {
2806        return mIsUpgrade;
2807    }
2808
2809    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2810        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2811
2812        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2813                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2814                UserHandle.USER_SYSTEM);
2815        if (matches.size() == 1) {
2816            return matches.get(0).getComponentInfo().packageName;
2817        } else {
2818            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2819            return null;
2820        }
2821    }
2822
2823    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2824        synchronized (mPackages) {
2825            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2826            if (libraryEntry == null) {
2827                throw new IllegalStateException("Missing required shared library:" + libraryName);
2828            }
2829            return libraryEntry.apk;
2830        }
2831    }
2832
2833    private @NonNull String getRequiredInstallerLPr() {
2834        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2835        intent.addCategory(Intent.CATEGORY_DEFAULT);
2836        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2837
2838        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2839                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2840                UserHandle.USER_SYSTEM);
2841        if (matches.size() == 1) {
2842            ResolveInfo resolveInfo = matches.get(0);
2843            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2844                throw new RuntimeException("The installer must be a privileged app");
2845            }
2846            return matches.get(0).getComponentInfo().packageName;
2847        } else {
2848            throw new RuntimeException("There must be exactly one installer; found " + matches);
2849        }
2850    }
2851
2852    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2853        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2854
2855        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2856                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2857                UserHandle.USER_SYSTEM);
2858        ResolveInfo best = null;
2859        final int N = matches.size();
2860        for (int i = 0; i < N; i++) {
2861            final ResolveInfo cur = matches.get(i);
2862            final String packageName = cur.getComponentInfo().packageName;
2863            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2864                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2865                continue;
2866            }
2867
2868            if (best == null || cur.priority > best.priority) {
2869                best = cur;
2870            }
2871        }
2872
2873        if (best != null) {
2874            return best.getComponentInfo().getComponentName();
2875        } else {
2876            throw new RuntimeException("There must be at least one intent filter verifier");
2877        }
2878    }
2879
2880    private @Nullable ComponentName getEphemeralResolverLPr() {
2881        final String[] packageArray =
2882                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2883        if (packageArray.length == 0) {
2884            if (DEBUG_EPHEMERAL) {
2885                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2886            }
2887            return null;
2888        }
2889
2890        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2891        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2892                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2893                UserHandle.USER_SYSTEM);
2894
2895        final int N = resolvers.size();
2896        if (N == 0) {
2897            if (DEBUG_EPHEMERAL) {
2898                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2899            }
2900            return null;
2901        }
2902
2903        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2904        for (int i = 0; i < N; i++) {
2905            final ResolveInfo info = resolvers.get(i);
2906
2907            if (info.serviceInfo == null) {
2908                continue;
2909            }
2910
2911            final String packageName = info.serviceInfo.packageName;
2912            if (!possiblePackages.contains(packageName)) {
2913                if (DEBUG_EPHEMERAL) {
2914                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2915                            + " pkg: " + packageName + ", info:" + info);
2916                }
2917                continue;
2918            }
2919
2920            if (DEBUG_EPHEMERAL) {
2921                Slog.v(TAG, "Ephemeral resolver found;"
2922                        + " pkg: " + packageName + ", info:" + info);
2923            }
2924            return new ComponentName(packageName, info.serviceInfo.name);
2925        }
2926        if (DEBUG_EPHEMERAL) {
2927            Slog.v(TAG, "Ephemeral resolver NOT found");
2928        }
2929        return null;
2930    }
2931
2932    private @Nullable ComponentName getEphemeralInstallerLPr() {
2933        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2934        intent.addCategory(Intent.CATEGORY_DEFAULT);
2935        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2936
2937        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2938                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2939                UserHandle.USER_SYSTEM);
2940        if (matches.size() == 0) {
2941            return null;
2942        } else if (matches.size() == 1) {
2943            return matches.get(0).getComponentInfo().getComponentName();
2944        } else {
2945            throw new RuntimeException(
2946                    "There must be at most one ephemeral installer; found " + matches);
2947        }
2948    }
2949
2950    private void primeDomainVerificationsLPw(int userId) {
2951        if (DEBUG_DOMAIN_VERIFICATION) {
2952            Slog.d(TAG, "Priming domain verifications in user " + userId);
2953        }
2954
2955        SystemConfig systemConfig = SystemConfig.getInstance();
2956        ArraySet<String> packages = systemConfig.getLinkedApps();
2957        ArraySet<String> domains = new ArraySet<String>();
2958
2959        for (String packageName : packages) {
2960            PackageParser.Package pkg = mPackages.get(packageName);
2961            if (pkg != null) {
2962                if (!pkg.isSystemApp()) {
2963                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2964                    continue;
2965                }
2966
2967                domains.clear();
2968                for (PackageParser.Activity a : pkg.activities) {
2969                    for (ActivityIntentInfo filter : a.intents) {
2970                        if (hasValidDomains(filter)) {
2971                            domains.addAll(filter.getHostsList());
2972                        }
2973                    }
2974                }
2975
2976                if (domains.size() > 0) {
2977                    if (DEBUG_DOMAIN_VERIFICATION) {
2978                        Slog.v(TAG, "      + " + packageName);
2979                    }
2980                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2981                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2982                    // and then 'always' in the per-user state actually used for intent resolution.
2983                    final IntentFilterVerificationInfo ivi;
2984                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2985                            new ArrayList<String>(domains));
2986                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2987                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2988                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2989                } else {
2990                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2991                            + "' does not handle web links");
2992                }
2993            } else {
2994                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2995            }
2996        }
2997
2998        scheduleWritePackageRestrictionsLocked(userId);
2999        scheduleWriteSettingsLocked();
3000    }
3001
3002    private void applyFactoryDefaultBrowserLPw(int userId) {
3003        // The default browser app's package name is stored in a string resource,
3004        // with a product-specific overlay used for vendor customization.
3005        String browserPkg = mContext.getResources().getString(
3006                com.android.internal.R.string.default_browser);
3007        if (!TextUtils.isEmpty(browserPkg)) {
3008            // non-empty string => required to be a known package
3009            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3010            if (ps == null) {
3011                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3012                browserPkg = null;
3013            } else {
3014                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3015            }
3016        }
3017
3018        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3019        // default.  If there's more than one, just leave everything alone.
3020        if (browserPkg == null) {
3021            calculateDefaultBrowserLPw(userId);
3022        }
3023    }
3024
3025    private void calculateDefaultBrowserLPw(int userId) {
3026        List<String> allBrowsers = resolveAllBrowserApps(userId);
3027        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3028        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3029    }
3030
3031    private List<String> resolveAllBrowserApps(int userId) {
3032        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3033        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3034                PackageManager.MATCH_ALL, userId);
3035
3036        final int count = list.size();
3037        List<String> result = new ArrayList<String>(count);
3038        for (int i=0; i<count; i++) {
3039            ResolveInfo info = list.get(i);
3040            if (info.activityInfo == null
3041                    || !info.handleAllWebDataURI
3042                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3043                    || result.contains(info.activityInfo.packageName)) {
3044                continue;
3045            }
3046            result.add(info.activityInfo.packageName);
3047        }
3048
3049        return result;
3050    }
3051
3052    private boolean packageIsBrowser(String packageName, int userId) {
3053        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3054                PackageManager.MATCH_ALL, userId);
3055        final int N = list.size();
3056        for (int i = 0; i < N; i++) {
3057            ResolveInfo info = list.get(i);
3058            if (packageName.equals(info.activityInfo.packageName)) {
3059                return true;
3060            }
3061        }
3062        return false;
3063    }
3064
3065    private void checkDefaultBrowser() {
3066        final int myUserId = UserHandle.myUserId();
3067        final String packageName = getDefaultBrowserPackageName(myUserId);
3068        if (packageName != null) {
3069            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3070            if (info == null) {
3071                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3072                synchronized (mPackages) {
3073                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3074                }
3075            }
3076        }
3077    }
3078
3079    @Override
3080    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3081            throws RemoteException {
3082        try {
3083            return super.onTransact(code, data, reply, flags);
3084        } catch (RuntimeException e) {
3085            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3086                Slog.wtf(TAG, "Package Manager Crash", e);
3087            }
3088            throw e;
3089        }
3090    }
3091
3092    static int[] appendInts(int[] cur, int[] add) {
3093        if (add == null) return cur;
3094        if (cur == null) return add;
3095        final int N = add.length;
3096        for (int i=0; i<N; i++) {
3097            cur = appendInt(cur, add[i]);
3098        }
3099        return cur;
3100    }
3101
3102    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3103        if (!sUserManager.exists(userId)) return null;
3104        if (ps == null) {
3105            return null;
3106        }
3107        final PackageParser.Package p = ps.pkg;
3108        if (p == null) {
3109            return null;
3110        }
3111
3112        final PermissionsState permissionsState = ps.getPermissionsState();
3113
3114        final int[] gids = permissionsState.computeGids(userId);
3115        final Set<String> permissions = permissionsState.getPermissions(userId);
3116        final PackageUserState state = ps.readUserState(userId);
3117
3118        return PackageParser.generatePackageInfo(p, gids, flags,
3119                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3120    }
3121
3122    @Override
3123    public void checkPackageStartable(String packageName, int userId) {
3124        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3125
3126        synchronized (mPackages) {
3127            final PackageSetting ps = mSettings.mPackages.get(packageName);
3128            if (ps == null) {
3129                throw new SecurityException("Package " + packageName + " was not found!");
3130            }
3131
3132            if (!ps.getInstalled(userId)) {
3133                throw new SecurityException(
3134                        "Package " + packageName + " was not installed for user " + userId + "!");
3135            }
3136
3137            if (mSafeMode && !ps.isSystem()) {
3138                throw new SecurityException("Package " + packageName + " not a system app!");
3139            }
3140
3141            if (mFrozenPackages.contains(packageName)) {
3142                throw new SecurityException("Package " + packageName + " is currently frozen!");
3143            }
3144
3145            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3146                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3147                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3148            }
3149        }
3150    }
3151
3152    @Override
3153    public boolean isPackageAvailable(String packageName, int userId) {
3154        if (!sUserManager.exists(userId)) return false;
3155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3156                false /* requireFullPermission */, false /* checkShell */, "is package available");
3157        synchronized (mPackages) {
3158            PackageParser.Package p = mPackages.get(packageName);
3159            if (p != null) {
3160                final PackageSetting ps = (PackageSetting) p.mExtras;
3161                if (ps != null) {
3162                    final PackageUserState state = ps.readUserState(userId);
3163                    if (state != null) {
3164                        return PackageParser.isAvailable(state);
3165                    }
3166                }
3167            }
3168        }
3169        return false;
3170    }
3171
3172    @Override
3173    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3174        if (!sUserManager.exists(userId)) return null;
3175        flags = updateFlagsForPackage(flags, userId, packageName);
3176        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3177                false /* requireFullPermission */, false /* checkShell */, "get package info");
3178        // reader
3179        synchronized (mPackages) {
3180            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3181            PackageParser.Package p = null;
3182            if (matchFactoryOnly) {
3183                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3184                if (ps != null) {
3185                    return generatePackageInfo(ps, flags, userId);
3186                }
3187            }
3188            if (p == null) {
3189                p = mPackages.get(packageName);
3190                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3191                    return null;
3192                }
3193            }
3194            if (DEBUG_PACKAGE_INFO)
3195                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3196            if (p != null) {
3197                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3198            }
3199            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3200                final PackageSetting ps = mSettings.mPackages.get(packageName);
3201                return generatePackageInfo(ps, flags, userId);
3202            }
3203        }
3204        return null;
3205    }
3206
3207    @Override
3208    public String[] currentToCanonicalPackageNames(String[] names) {
3209        String[] out = new String[names.length];
3210        // reader
3211        synchronized (mPackages) {
3212            for (int i=names.length-1; i>=0; i--) {
3213                PackageSetting ps = mSettings.mPackages.get(names[i]);
3214                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3215            }
3216        }
3217        return out;
3218    }
3219
3220    @Override
3221    public String[] canonicalToCurrentPackageNames(String[] names) {
3222        String[] out = new String[names.length];
3223        // reader
3224        synchronized (mPackages) {
3225            for (int i=names.length-1; i>=0; i--) {
3226                String cur = mSettings.mRenamedPackages.get(names[i]);
3227                out[i] = cur != null ? cur : names[i];
3228            }
3229        }
3230        return out;
3231    }
3232
3233    @Override
3234    public int getPackageUid(String packageName, int flags, int userId) {
3235        if (!sUserManager.exists(userId)) return -1;
3236        flags = updateFlagsForPackage(flags, userId, packageName);
3237        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3238                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3239
3240        // reader
3241        synchronized (mPackages) {
3242            final PackageParser.Package p = mPackages.get(packageName);
3243            if (p != null && p.isMatch(flags)) {
3244                return UserHandle.getUid(userId, p.applicationInfo.uid);
3245            }
3246            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3247                final PackageSetting ps = mSettings.mPackages.get(packageName);
3248                if (ps != null && ps.isMatch(flags)) {
3249                    return UserHandle.getUid(userId, ps.appId);
3250                }
3251            }
3252        }
3253
3254        return -1;
3255    }
3256
3257    @Override
3258    public int[] getPackageGids(String packageName, int flags, int userId) {
3259        if (!sUserManager.exists(userId)) return null;
3260        flags = updateFlagsForPackage(flags, userId, packageName);
3261        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3262                false /* requireFullPermission */, false /* checkShell */,
3263                "getPackageGids");
3264
3265        // reader
3266        synchronized (mPackages) {
3267            final PackageParser.Package p = mPackages.get(packageName);
3268            if (p != null && p.isMatch(flags)) {
3269                PackageSetting ps = (PackageSetting) p.mExtras;
3270                return ps.getPermissionsState().computeGids(userId);
3271            }
3272            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3273                final PackageSetting ps = mSettings.mPackages.get(packageName);
3274                if (ps != null && ps.isMatch(flags)) {
3275                    return ps.getPermissionsState().computeGids(userId);
3276                }
3277            }
3278        }
3279
3280        return null;
3281    }
3282
3283    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3284        if (bp.perm != null) {
3285            return PackageParser.generatePermissionInfo(bp.perm, flags);
3286        }
3287        PermissionInfo pi = new PermissionInfo();
3288        pi.name = bp.name;
3289        pi.packageName = bp.sourcePackage;
3290        pi.nonLocalizedLabel = bp.name;
3291        pi.protectionLevel = bp.protectionLevel;
3292        return pi;
3293    }
3294
3295    @Override
3296    public PermissionInfo getPermissionInfo(String name, int flags) {
3297        // reader
3298        synchronized (mPackages) {
3299            final BasePermission p = mSettings.mPermissions.get(name);
3300            if (p != null) {
3301                return generatePermissionInfo(p, flags);
3302            }
3303            return null;
3304        }
3305    }
3306
3307    @Override
3308    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3309            int flags) {
3310        // reader
3311        synchronized (mPackages) {
3312            if (group != null && !mPermissionGroups.containsKey(group)) {
3313                // This is thrown as NameNotFoundException
3314                return null;
3315            }
3316
3317            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3318            for (BasePermission p : mSettings.mPermissions.values()) {
3319                if (group == null) {
3320                    if (p.perm == null || p.perm.info.group == null) {
3321                        out.add(generatePermissionInfo(p, flags));
3322                    }
3323                } else {
3324                    if (p.perm != null && group.equals(p.perm.info.group)) {
3325                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3326                    }
3327                }
3328            }
3329            return new ParceledListSlice<>(out);
3330        }
3331    }
3332
3333    @Override
3334    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3335        // reader
3336        synchronized (mPackages) {
3337            return PackageParser.generatePermissionGroupInfo(
3338                    mPermissionGroups.get(name), flags);
3339        }
3340    }
3341
3342    @Override
3343    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3344        // reader
3345        synchronized (mPackages) {
3346            final int N = mPermissionGroups.size();
3347            ArrayList<PermissionGroupInfo> out
3348                    = new ArrayList<PermissionGroupInfo>(N);
3349            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3350                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3351            }
3352            return new ParceledListSlice<>(out);
3353        }
3354    }
3355
3356    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3357            int userId) {
3358        if (!sUserManager.exists(userId)) return null;
3359        PackageSetting ps = mSettings.mPackages.get(packageName);
3360        if (ps != null) {
3361            if (ps.pkg == null) {
3362                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3363                if (pInfo != null) {
3364                    return pInfo.applicationInfo;
3365                }
3366                return null;
3367            }
3368            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3369                    ps.readUserState(userId), userId);
3370        }
3371        return null;
3372    }
3373
3374    @Override
3375    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3376        if (!sUserManager.exists(userId)) return null;
3377        flags = updateFlagsForApplication(flags, userId, packageName);
3378        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3379                false /* requireFullPermission */, false /* checkShell */, "get application info");
3380        // writer
3381        synchronized (mPackages) {
3382            PackageParser.Package p = mPackages.get(packageName);
3383            if (DEBUG_PACKAGE_INFO) Log.v(
3384                    TAG, "getApplicationInfo " + packageName
3385                    + ": " + p);
3386            if (p != null) {
3387                PackageSetting ps = mSettings.mPackages.get(packageName);
3388                if (ps == null) return null;
3389                // Note: isEnabledLP() does not apply here - always return info
3390                return PackageParser.generateApplicationInfo(
3391                        p, flags, ps.readUserState(userId), userId);
3392            }
3393            if ("android".equals(packageName)||"system".equals(packageName)) {
3394                return mAndroidApplication;
3395            }
3396            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3397                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3398            }
3399        }
3400        return null;
3401    }
3402
3403    @Override
3404    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3405            final IPackageDataObserver observer) {
3406        mContext.enforceCallingOrSelfPermission(
3407                android.Manifest.permission.CLEAR_APP_CACHE, null);
3408        // Queue up an async operation since clearing cache may take a little while.
3409        mHandler.post(new Runnable() {
3410            public void run() {
3411                mHandler.removeCallbacks(this);
3412                boolean success = true;
3413                synchronized (mInstallLock) {
3414                    try {
3415                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3416                    } catch (InstallerException e) {
3417                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3418                        success = false;
3419                    }
3420                }
3421                if (observer != null) {
3422                    try {
3423                        observer.onRemoveCompleted(null, success);
3424                    } catch (RemoteException e) {
3425                        Slog.w(TAG, "RemoveException when invoking call back");
3426                    }
3427                }
3428            }
3429        });
3430    }
3431
3432    @Override
3433    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3434            final IntentSender pi) {
3435        mContext.enforceCallingOrSelfPermission(
3436                android.Manifest.permission.CLEAR_APP_CACHE, null);
3437        // Queue up an async operation since clearing cache may take a little while.
3438        mHandler.post(new Runnable() {
3439            public void run() {
3440                mHandler.removeCallbacks(this);
3441                boolean success = true;
3442                synchronized (mInstallLock) {
3443                    try {
3444                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3445                    } catch (InstallerException e) {
3446                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3447                        success = false;
3448                    }
3449                }
3450                if(pi != null) {
3451                    try {
3452                        // Callback via pending intent
3453                        int code = success ? 1 : 0;
3454                        pi.sendIntent(null, code, null,
3455                                null, null);
3456                    } catch (SendIntentException e1) {
3457                        Slog.i(TAG, "Failed to send pending intent");
3458                    }
3459                }
3460            }
3461        });
3462    }
3463
3464    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3465        synchronized (mInstallLock) {
3466            try {
3467                mInstaller.freeCache(volumeUuid, freeStorageSize);
3468            } catch (InstallerException e) {
3469                throw new IOException("Failed to free enough space", e);
3470            }
3471        }
3472    }
3473
3474    /**
3475     * Update given flags based on encryption status of current user.
3476     */
3477    private int updateFlags(int flags, int userId) {
3478        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3479                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3480            // Caller expressed an explicit opinion about what encryption
3481            // aware/unaware components they want to see, so fall through and
3482            // give them what they want
3483        } else {
3484            // Caller expressed no opinion, so match based on user state
3485            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3486                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3487            } else {
3488                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3489            }
3490        }
3491        return flags;
3492    }
3493
3494    private UserManagerInternal getUserManagerInternal() {
3495        if (mUserManagerInternal == null) {
3496            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3497        }
3498        return mUserManagerInternal;
3499    }
3500
3501    /**
3502     * Update given flags when being used to request {@link PackageInfo}.
3503     */
3504    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3505        boolean triaged = true;
3506        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3507                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3508            // Caller is asking for component details, so they'd better be
3509            // asking for specific encryption matching behavior, or be triaged
3510            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3511                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3512                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3513                triaged = false;
3514            }
3515        }
3516        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3517                | PackageManager.MATCH_SYSTEM_ONLY
3518                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3519            triaged = false;
3520        }
3521        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3522            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3523                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3524        }
3525        return updateFlags(flags, userId);
3526    }
3527
3528    /**
3529     * Update given flags when being used to request {@link ApplicationInfo}.
3530     */
3531    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3532        return updateFlagsForPackage(flags, userId, cookie);
3533    }
3534
3535    /**
3536     * Update given flags when being used to request {@link ComponentInfo}.
3537     */
3538    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3539        if (cookie instanceof Intent) {
3540            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3541                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3542            }
3543        }
3544
3545        boolean triaged = true;
3546        // Caller is asking for component details, so they'd better be
3547        // asking for specific encryption matching behavior, or be triaged
3548        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3549                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3550                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3551            triaged = false;
3552        }
3553        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3554            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3555                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3556        }
3557
3558        return updateFlags(flags, userId);
3559    }
3560
3561    /**
3562     * Update given flags when being used to request {@link ResolveInfo}.
3563     */
3564    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3565        // Safe mode means we shouldn't match any third-party components
3566        if (mSafeMode) {
3567            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3568        }
3569
3570        return updateFlagsForComponent(flags, userId, cookie);
3571    }
3572
3573    @Override
3574    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3575        if (!sUserManager.exists(userId)) return null;
3576        flags = updateFlagsForComponent(flags, userId, component);
3577        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3578                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3579        synchronized (mPackages) {
3580            PackageParser.Activity a = mActivities.mActivities.get(component);
3581
3582            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3583            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3584                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3585                if (ps == null) return null;
3586                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3587                        userId);
3588            }
3589            if (mResolveComponentName.equals(component)) {
3590                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3591                        new PackageUserState(), userId);
3592            }
3593        }
3594        return null;
3595    }
3596
3597    @Override
3598    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3599            String resolvedType) {
3600        synchronized (mPackages) {
3601            if (component.equals(mResolveComponentName)) {
3602                // The resolver supports EVERYTHING!
3603                return true;
3604            }
3605            PackageParser.Activity a = mActivities.mActivities.get(component);
3606            if (a == null) {
3607                return false;
3608            }
3609            for (int i=0; i<a.intents.size(); i++) {
3610                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3611                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3612                    return true;
3613                }
3614            }
3615            return false;
3616        }
3617    }
3618
3619    @Override
3620    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3621        if (!sUserManager.exists(userId)) return null;
3622        flags = updateFlagsForComponent(flags, userId, component);
3623        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3624                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3625        synchronized (mPackages) {
3626            PackageParser.Activity a = mReceivers.mActivities.get(component);
3627            if (DEBUG_PACKAGE_INFO) Log.v(
3628                TAG, "getReceiverInfo " + component + ": " + a);
3629            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3630                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3631                if (ps == null) return null;
3632                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3633                        userId);
3634            }
3635        }
3636        return null;
3637    }
3638
3639    @Override
3640    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3641        if (!sUserManager.exists(userId)) return null;
3642        flags = updateFlagsForComponent(flags, userId, component);
3643        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3644                false /* requireFullPermission */, false /* checkShell */, "get service info");
3645        synchronized (mPackages) {
3646            PackageParser.Service s = mServices.mServices.get(component);
3647            if (DEBUG_PACKAGE_INFO) Log.v(
3648                TAG, "getServiceInfo " + component + ": " + s);
3649            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3650                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3651                if (ps == null) return null;
3652                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3653                        userId);
3654            }
3655        }
3656        return null;
3657    }
3658
3659    @Override
3660    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3661        if (!sUserManager.exists(userId)) return null;
3662        flags = updateFlagsForComponent(flags, userId, component);
3663        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3664                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3665        synchronized (mPackages) {
3666            PackageParser.Provider p = mProviders.mProviders.get(component);
3667            if (DEBUG_PACKAGE_INFO) Log.v(
3668                TAG, "getProviderInfo " + component + ": " + p);
3669            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3670                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3671                if (ps == null) return null;
3672                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3673                        userId);
3674            }
3675        }
3676        return null;
3677    }
3678
3679    @Override
3680    public String[] getSystemSharedLibraryNames() {
3681        Set<String> libSet;
3682        synchronized (mPackages) {
3683            libSet = mSharedLibraries.keySet();
3684            int size = libSet.size();
3685            if (size > 0) {
3686                String[] libs = new String[size];
3687                libSet.toArray(libs);
3688                return libs;
3689            }
3690        }
3691        return null;
3692    }
3693
3694    @Override
3695    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3696        synchronized (mPackages) {
3697            return mServicesSystemSharedLibraryPackageName;
3698        }
3699    }
3700
3701    @Override
3702    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3703        synchronized (mPackages) {
3704            return mSharedSystemSharedLibraryPackageName;
3705        }
3706    }
3707
3708    @Override
3709    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3710        synchronized (mPackages) {
3711            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3712
3713            final FeatureInfo fi = new FeatureInfo();
3714            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3715                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3716            res.add(fi);
3717
3718            return new ParceledListSlice<>(res);
3719        }
3720    }
3721
3722    @Override
3723    public boolean hasSystemFeature(String name, int version) {
3724        synchronized (mPackages) {
3725            final FeatureInfo feat = mAvailableFeatures.get(name);
3726            if (feat == null) {
3727                return false;
3728            } else {
3729                return feat.version >= version;
3730            }
3731        }
3732    }
3733
3734    @Override
3735    public int checkPermission(String permName, String pkgName, int userId) {
3736        if (!sUserManager.exists(userId)) {
3737            return PackageManager.PERMISSION_DENIED;
3738        }
3739
3740        synchronized (mPackages) {
3741            final PackageParser.Package p = mPackages.get(pkgName);
3742            if (p != null && p.mExtras != null) {
3743                final PackageSetting ps = (PackageSetting) p.mExtras;
3744                final PermissionsState permissionsState = ps.getPermissionsState();
3745                if (permissionsState.hasPermission(permName, userId)) {
3746                    return PackageManager.PERMISSION_GRANTED;
3747                }
3748                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3749                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3750                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3751                    return PackageManager.PERMISSION_GRANTED;
3752                }
3753            }
3754        }
3755
3756        return PackageManager.PERMISSION_DENIED;
3757    }
3758
3759    @Override
3760    public int checkUidPermission(String permName, int uid) {
3761        final int userId = UserHandle.getUserId(uid);
3762
3763        if (!sUserManager.exists(userId)) {
3764            return PackageManager.PERMISSION_DENIED;
3765        }
3766
3767        synchronized (mPackages) {
3768            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3769            if (obj != null) {
3770                final SettingBase ps = (SettingBase) obj;
3771                final PermissionsState permissionsState = ps.getPermissionsState();
3772                if (permissionsState.hasPermission(permName, userId)) {
3773                    return PackageManager.PERMISSION_GRANTED;
3774                }
3775                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3776                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3777                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3778                    return PackageManager.PERMISSION_GRANTED;
3779                }
3780            } else {
3781                ArraySet<String> perms = mSystemPermissions.get(uid);
3782                if (perms != null) {
3783                    if (perms.contains(permName)) {
3784                        return PackageManager.PERMISSION_GRANTED;
3785                    }
3786                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3787                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3788                        return PackageManager.PERMISSION_GRANTED;
3789                    }
3790                }
3791            }
3792        }
3793
3794        return PackageManager.PERMISSION_DENIED;
3795    }
3796
3797    @Override
3798    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3799        if (UserHandle.getCallingUserId() != userId) {
3800            mContext.enforceCallingPermission(
3801                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3802                    "isPermissionRevokedByPolicy for user " + userId);
3803        }
3804
3805        if (checkPermission(permission, packageName, userId)
3806                == PackageManager.PERMISSION_GRANTED) {
3807            return false;
3808        }
3809
3810        final long identity = Binder.clearCallingIdentity();
3811        try {
3812            final int flags = getPermissionFlags(permission, packageName, userId);
3813            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3814        } finally {
3815            Binder.restoreCallingIdentity(identity);
3816        }
3817    }
3818
3819    @Override
3820    public String getPermissionControllerPackageName() {
3821        synchronized (mPackages) {
3822            return mRequiredInstallerPackage;
3823        }
3824    }
3825
3826    /**
3827     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3828     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3829     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3830     * @param message the message to log on security exception
3831     */
3832    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3833            boolean checkShell, String message) {
3834        if (userId < 0) {
3835            throw new IllegalArgumentException("Invalid userId " + userId);
3836        }
3837        if (checkShell) {
3838            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3839        }
3840        if (userId == UserHandle.getUserId(callingUid)) return;
3841        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3842            if (requireFullPermission) {
3843                mContext.enforceCallingOrSelfPermission(
3844                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3845            } else {
3846                try {
3847                    mContext.enforceCallingOrSelfPermission(
3848                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3849                } catch (SecurityException se) {
3850                    mContext.enforceCallingOrSelfPermission(
3851                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3852                }
3853            }
3854        }
3855    }
3856
3857    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3858        if (callingUid == Process.SHELL_UID) {
3859            if (userHandle >= 0
3860                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3861                throw new SecurityException("Shell does not have permission to access user "
3862                        + userHandle);
3863            } else if (userHandle < 0) {
3864                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3865                        + Debug.getCallers(3));
3866            }
3867        }
3868    }
3869
3870    private BasePermission findPermissionTreeLP(String permName) {
3871        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3872            if (permName.startsWith(bp.name) &&
3873                    permName.length() > bp.name.length() &&
3874                    permName.charAt(bp.name.length()) == '.') {
3875                return bp;
3876            }
3877        }
3878        return null;
3879    }
3880
3881    private BasePermission checkPermissionTreeLP(String permName) {
3882        if (permName != null) {
3883            BasePermission bp = findPermissionTreeLP(permName);
3884            if (bp != null) {
3885                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3886                    return bp;
3887                }
3888                throw new SecurityException("Calling uid "
3889                        + Binder.getCallingUid()
3890                        + " is not allowed to add to permission tree "
3891                        + bp.name + " owned by uid " + bp.uid);
3892            }
3893        }
3894        throw new SecurityException("No permission tree found for " + permName);
3895    }
3896
3897    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3898        if (s1 == null) {
3899            return s2 == null;
3900        }
3901        if (s2 == null) {
3902            return false;
3903        }
3904        if (s1.getClass() != s2.getClass()) {
3905            return false;
3906        }
3907        return s1.equals(s2);
3908    }
3909
3910    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3911        if (pi1.icon != pi2.icon) return false;
3912        if (pi1.logo != pi2.logo) return false;
3913        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3914        if (!compareStrings(pi1.name, pi2.name)) return false;
3915        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3916        // We'll take care of setting this one.
3917        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3918        // These are not currently stored in settings.
3919        //if (!compareStrings(pi1.group, pi2.group)) return false;
3920        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3921        //if (pi1.labelRes != pi2.labelRes) return false;
3922        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3923        return true;
3924    }
3925
3926    int permissionInfoFootprint(PermissionInfo info) {
3927        int size = info.name.length();
3928        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3929        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3930        return size;
3931    }
3932
3933    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3934        int size = 0;
3935        for (BasePermission perm : mSettings.mPermissions.values()) {
3936            if (perm.uid == tree.uid) {
3937                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3938            }
3939        }
3940        return size;
3941    }
3942
3943    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3944        // We calculate the max size of permissions defined by this uid and throw
3945        // if that plus the size of 'info' would exceed our stated maximum.
3946        if (tree.uid != Process.SYSTEM_UID) {
3947            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3948            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3949                throw new SecurityException("Permission tree size cap exceeded");
3950            }
3951        }
3952    }
3953
3954    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3955        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3956            throw new SecurityException("Label must be specified in permission");
3957        }
3958        BasePermission tree = checkPermissionTreeLP(info.name);
3959        BasePermission bp = mSettings.mPermissions.get(info.name);
3960        boolean added = bp == null;
3961        boolean changed = true;
3962        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3963        if (added) {
3964            enforcePermissionCapLocked(info, tree);
3965            bp = new BasePermission(info.name, tree.sourcePackage,
3966                    BasePermission.TYPE_DYNAMIC);
3967        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3968            throw new SecurityException(
3969                    "Not allowed to modify non-dynamic permission "
3970                    + info.name);
3971        } else {
3972            if (bp.protectionLevel == fixedLevel
3973                    && bp.perm.owner.equals(tree.perm.owner)
3974                    && bp.uid == tree.uid
3975                    && comparePermissionInfos(bp.perm.info, info)) {
3976                changed = false;
3977            }
3978        }
3979        bp.protectionLevel = fixedLevel;
3980        info = new PermissionInfo(info);
3981        info.protectionLevel = fixedLevel;
3982        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3983        bp.perm.info.packageName = tree.perm.info.packageName;
3984        bp.uid = tree.uid;
3985        if (added) {
3986            mSettings.mPermissions.put(info.name, bp);
3987        }
3988        if (changed) {
3989            if (!async) {
3990                mSettings.writeLPr();
3991            } else {
3992                scheduleWriteSettingsLocked();
3993            }
3994        }
3995        return added;
3996    }
3997
3998    @Override
3999    public boolean addPermission(PermissionInfo info) {
4000        synchronized (mPackages) {
4001            return addPermissionLocked(info, false);
4002        }
4003    }
4004
4005    @Override
4006    public boolean addPermissionAsync(PermissionInfo info) {
4007        synchronized (mPackages) {
4008            return addPermissionLocked(info, true);
4009        }
4010    }
4011
4012    @Override
4013    public void removePermission(String name) {
4014        synchronized (mPackages) {
4015            checkPermissionTreeLP(name);
4016            BasePermission bp = mSettings.mPermissions.get(name);
4017            if (bp != null) {
4018                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4019                    throw new SecurityException(
4020                            "Not allowed to modify non-dynamic permission "
4021                            + name);
4022                }
4023                mSettings.mPermissions.remove(name);
4024                mSettings.writeLPr();
4025            }
4026        }
4027    }
4028
4029    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4030            BasePermission bp) {
4031        int index = pkg.requestedPermissions.indexOf(bp.name);
4032        if (index == -1) {
4033            throw new SecurityException("Package " + pkg.packageName
4034                    + " has not requested permission " + bp.name);
4035        }
4036        if (!bp.isRuntime() && !bp.isDevelopment()) {
4037            throw new SecurityException("Permission " + bp.name
4038                    + " is not a changeable permission type");
4039        }
4040    }
4041
4042    @Override
4043    public void grantRuntimePermission(String packageName, String name, final int userId) {
4044        if (!sUserManager.exists(userId)) {
4045            Log.e(TAG, "No such user:" + userId);
4046            return;
4047        }
4048
4049        mContext.enforceCallingOrSelfPermission(
4050                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4051                "grantRuntimePermission");
4052
4053        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4054                true /* requireFullPermission */, true /* checkShell */,
4055                "grantRuntimePermission");
4056
4057        final int uid;
4058        final SettingBase sb;
4059
4060        synchronized (mPackages) {
4061            final PackageParser.Package pkg = mPackages.get(packageName);
4062            if (pkg == null) {
4063                throw new IllegalArgumentException("Unknown package: " + packageName);
4064            }
4065
4066            final BasePermission bp = mSettings.mPermissions.get(name);
4067            if (bp == null) {
4068                throw new IllegalArgumentException("Unknown permission: " + name);
4069            }
4070
4071            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4072
4073            // If a permission review is required for legacy apps we represent
4074            // their permissions as always granted runtime ones since we need
4075            // to keep the review required permission flag per user while an
4076            // install permission's state is shared across all users.
4077            if (Build.PERMISSIONS_REVIEW_REQUIRED
4078                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4079                    && bp.isRuntime()) {
4080                return;
4081            }
4082
4083            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4084            sb = (SettingBase) pkg.mExtras;
4085            if (sb == null) {
4086                throw new IllegalArgumentException("Unknown package: " + packageName);
4087            }
4088
4089            final PermissionsState permissionsState = sb.getPermissionsState();
4090
4091            final int flags = permissionsState.getPermissionFlags(name, userId);
4092            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4093                throw new SecurityException("Cannot grant system fixed permission "
4094                        + name + " for package " + packageName);
4095            }
4096
4097            if (bp.isDevelopment()) {
4098                // Development permissions must be handled specially, since they are not
4099                // normal runtime permissions.  For now they apply to all users.
4100                if (permissionsState.grantInstallPermission(bp) !=
4101                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4102                    scheduleWriteSettingsLocked();
4103                }
4104                return;
4105            }
4106
4107            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4108                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4109                return;
4110            }
4111
4112            final int result = permissionsState.grantRuntimePermission(bp, userId);
4113            switch (result) {
4114                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4115                    return;
4116                }
4117
4118                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4119                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4120                    mHandler.post(new Runnable() {
4121                        @Override
4122                        public void run() {
4123                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4124                        }
4125                    });
4126                }
4127                break;
4128            }
4129
4130            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4131
4132            // Not critical if that is lost - app has to request again.
4133            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4134        }
4135
4136        // Only need to do this if user is initialized. Otherwise it's a new user
4137        // and there are no processes running as the user yet and there's no need
4138        // to make an expensive call to remount processes for the changed permissions.
4139        if (READ_EXTERNAL_STORAGE.equals(name)
4140                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4141            final long token = Binder.clearCallingIdentity();
4142            try {
4143                if (sUserManager.isInitialized(userId)) {
4144                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4145                            MountServiceInternal.class);
4146                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4147                }
4148            } finally {
4149                Binder.restoreCallingIdentity(token);
4150            }
4151        }
4152    }
4153
4154    @Override
4155    public void revokeRuntimePermission(String packageName, String name, int userId) {
4156        if (!sUserManager.exists(userId)) {
4157            Log.e(TAG, "No such user:" + userId);
4158            return;
4159        }
4160
4161        mContext.enforceCallingOrSelfPermission(
4162                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4163                "revokeRuntimePermission");
4164
4165        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4166                true /* requireFullPermission */, true /* checkShell */,
4167                "revokeRuntimePermission");
4168
4169        final int appId;
4170
4171        synchronized (mPackages) {
4172            final PackageParser.Package pkg = mPackages.get(packageName);
4173            if (pkg == null) {
4174                throw new IllegalArgumentException("Unknown package: " + packageName);
4175            }
4176
4177            final BasePermission bp = mSettings.mPermissions.get(name);
4178            if (bp == null) {
4179                throw new IllegalArgumentException("Unknown permission: " + name);
4180            }
4181
4182            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4183
4184            // If a permission review is required for legacy apps we represent
4185            // their permissions as always granted runtime ones since we need
4186            // to keep the review required permission flag per user while an
4187            // install permission's state is shared across all users.
4188            if (Build.PERMISSIONS_REVIEW_REQUIRED
4189                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4190                    && bp.isRuntime()) {
4191                return;
4192            }
4193
4194            SettingBase sb = (SettingBase) pkg.mExtras;
4195            if (sb == null) {
4196                throw new IllegalArgumentException("Unknown package: " + packageName);
4197            }
4198
4199            final PermissionsState permissionsState = sb.getPermissionsState();
4200
4201            final int flags = permissionsState.getPermissionFlags(name, userId);
4202            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4203                throw new SecurityException("Cannot revoke system fixed permission "
4204                        + name + " for package " + packageName);
4205            }
4206
4207            if (bp.isDevelopment()) {
4208                // Development permissions must be handled specially, since they are not
4209                // normal runtime permissions.  For now they apply to all users.
4210                if (permissionsState.revokeInstallPermission(bp) !=
4211                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4212                    scheduleWriteSettingsLocked();
4213                }
4214                return;
4215            }
4216
4217            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4218                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4219                return;
4220            }
4221
4222            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4223
4224            // Critical, after this call app should never have the permission.
4225            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4226
4227            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4228        }
4229
4230        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4231    }
4232
4233    @Override
4234    public void resetRuntimePermissions() {
4235        mContext.enforceCallingOrSelfPermission(
4236                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4237                "revokeRuntimePermission");
4238
4239        int callingUid = Binder.getCallingUid();
4240        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4241            mContext.enforceCallingOrSelfPermission(
4242                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4243                    "resetRuntimePermissions");
4244        }
4245
4246        synchronized (mPackages) {
4247            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4248            for (int userId : UserManagerService.getInstance().getUserIds()) {
4249                final int packageCount = mPackages.size();
4250                for (int i = 0; i < packageCount; i++) {
4251                    PackageParser.Package pkg = mPackages.valueAt(i);
4252                    if (!(pkg.mExtras instanceof PackageSetting)) {
4253                        continue;
4254                    }
4255                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4256                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4257                }
4258            }
4259        }
4260    }
4261
4262    @Override
4263    public int getPermissionFlags(String name, String packageName, int userId) {
4264        if (!sUserManager.exists(userId)) {
4265            return 0;
4266        }
4267
4268        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4269
4270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4271                true /* requireFullPermission */, false /* checkShell */,
4272                "getPermissionFlags");
4273
4274        synchronized (mPackages) {
4275            final PackageParser.Package pkg = mPackages.get(packageName);
4276            if (pkg == null) {
4277                return 0;
4278            }
4279
4280            final BasePermission bp = mSettings.mPermissions.get(name);
4281            if (bp == null) {
4282                return 0;
4283            }
4284
4285            SettingBase sb = (SettingBase) pkg.mExtras;
4286            if (sb == null) {
4287                return 0;
4288            }
4289
4290            PermissionsState permissionsState = sb.getPermissionsState();
4291            return permissionsState.getPermissionFlags(name, userId);
4292        }
4293    }
4294
4295    @Override
4296    public void updatePermissionFlags(String name, String packageName, int flagMask,
4297            int flagValues, int userId) {
4298        if (!sUserManager.exists(userId)) {
4299            return;
4300        }
4301
4302        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4303
4304        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4305                true /* requireFullPermission */, true /* checkShell */,
4306                "updatePermissionFlags");
4307
4308        // Only the system can change these flags and nothing else.
4309        if (getCallingUid() != Process.SYSTEM_UID) {
4310            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4311            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4312            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4313            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4314            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4315        }
4316
4317        synchronized (mPackages) {
4318            final PackageParser.Package pkg = mPackages.get(packageName);
4319            if (pkg == null) {
4320                throw new IllegalArgumentException("Unknown package: " + packageName);
4321            }
4322
4323            final BasePermission bp = mSettings.mPermissions.get(name);
4324            if (bp == null) {
4325                throw new IllegalArgumentException("Unknown permission: " + name);
4326            }
4327
4328            SettingBase sb = (SettingBase) pkg.mExtras;
4329            if (sb == null) {
4330                throw new IllegalArgumentException("Unknown package: " + packageName);
4331            }
4332
4333            PermissionsState permissionsState = sb.getPermissionsState();
4334
4335            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4336
4337            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4338                // Install and runtime permissions are stored in different places,
4339                // so figure out what permission changed and persist the change.
4340                if (permissionsState.getInstallPermissionState(name) != null) {
4341                    scheduleWriteSettingsLocked();
4342                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4343                        || hadState) {
4344                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4345                }
4346            }
4347        }
4348    }
4349
4350    /**
4351     * Update the permission flags for all packages and runtime permissions of a user in order
4352     * to allow device or profile owner to remove POLICY_FIXED.
4353     */
4354    @Override
4355    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4356        if (!sUserManager.exists(userId)) {
4357            return;
4358        }
4359
4360        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4361
4362        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4363                true /* requireFullPermission */, true /* checkShell */,
4364                "updatePermissionFlagsForAllApps");
4365
4366        // Only the system can change system fixed flags.
4367        if (getCallingUid() != Process.SYSTEM_UID) {
4368            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4369            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4370        }
4371
4372        synchronized (mPackages) {
4373            boolean changed = false;
4374            final int packageCount = mPackages.size();
4375            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4376                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4377                SettingBase sb = (SettingBase) pkg.mExtras;
4378                if (sb == null) {
4379                    continue;
4380                }
4381                PermissionsState permissionsState = sb.getPermissionsState();
4382                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4383                        userId, flagMask, flagValues);
4384            }
4385            if (changed) {
4386                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4387            }
4388        }
4389    }
4390
4391    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4392        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4393                != PackageManager.PERMISSION_GRANTED
4394            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4395                != PackageManager.PERMISSION_GRANTED) {
4396            throw new SecurityException(message + " requires "
4397                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4398                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4399        }
4400    }
4401
4402    @Override
4403    public boolean shouldShowRequestPermissionRationale(String permissionName,
4404            String packageName, int userId) {
4405        if (UserHandle.getCallingUserId() != userId) {
4406            mContext.enforceCallingPermission(
4407                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4408                    "canShowRequestPermissionRationale for user " + userId);
4409        }
4410
4411        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4412        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4413            return false;
4414        }
4415
4416        if (checkPermission(permissionName, packageName, userId)
4417                == PackageManager.PERMISSION_GRANTED) {
4418            return false;
4419        }
4420
4421        final int flags;
4422
4423        final long identity = Binder.clearCallingIdentity();
4424        try {
4425            flags = getPermissionFlags(permissionName,
4426                    packageName, userId);
4427        } finally {
4428            Binder.restoreCallingIdentity(identity);
4429        }
4430
4431        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4432                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4433                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4434
4435        if ((flags & fixedFlags) != 0) {
4436            return false;
4437        }
4438
4439        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4440    }
4441
4442    @Override
4443    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4444        mContext.enforceCallingOrSelfPermission(
4445                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4446                "addOnPermissionsChangeListener");
4447
4448        synchronized (mPackages) {
4449            mOnPermissionChangeListeners.addListenerLocked(listener);
4450        }
4451    }
4452
4453    @Override
4454    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4455        synchronized (mPackages) {
4456            mOnPermissionChangeListeners.removeListenerLocked(listener);
4457        }
4458    }
4459
4460    @Override
4461    public boolean isProtectedBroadcast(String actionName) {
4462        synchronized (mPackages) {
4463            if (mProtectedBroadcasts.contains(actionName)) {
4464                return true;
4465            } else if (actionName != null) {
4466                // TODO: remove these terrible hacks
4467                if (actionName.startsWith("android.net.netmon.lingerExpired")
4468                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4469                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4470                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4471                    return true;
4472                }
4473            }
4474        }
4475        return false;
4476    }
4477
4478    @Override
4479    public int checkSignatures(String pkg1, String pkg2) {
4480        synchronized (mPackages) {
4481            final PackageParser.Package p1 = mPackages.get(pkg1);
4482            final PackageParser.Package p2 = mPackages.get(pkg2);
4483            if (p1 == null || p1.mExtras == null
4484                    || p2 == null || p2.mExtras == null) {
4485                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4486            }
4487            return compareSignatures(p1.mSignatures, p2.mSignatures);
4488        }
4489    }
4490
4491    @Override
4492    public int checkUidSignatures(int uid1, int uid2) {
4493        // Map to base uids.
4494        uid1 = UserHandle.getAppId(uid1);
4495        uid2 = UserHandle.getAppId(uid2);
4496        // reader
4497        synchronized (mPackages) {
4498            Signature[] s1;
4499            Signature[] s2;
4500            Object obj = mSettings.getUserIdLPr(uid1);
4501            if (obj != null) {
4502                if (obj instanceof SharedUserSetting) {
4503                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4504                } else if (obj instanceof PackageSetting) {
4505                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4506                } else {
4507                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4508                }
4509            } else {
4510                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4511            }
4512            obj = mSettings.getUserIdLPr(uid2);
4513            if (obj != null) {
4514                if (obj instanceof SharedUserSetting) {
4515                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4516                } else if (obj instanceof PackageSetting) {
4517                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4518                } else {
4519                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4520                }
4521            } else {
4522                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4523            }
4524            return compareSignatures(s1, s2);
4525        }
4526    }
4527
4528    /**
4529     * This method should typically only be used when granting or revoking
4530     * permissions, since the app may immediately restart after this call.
4531     * <p>
4532     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4533     * guard your work against the app being relaunched.
4534     */
4535    private void killUid(int appId, int userId, String reason) {
4536        final long identity = Binder.clearCallingIdentity();
4537        try {
4538            IActivityManager am = ActivityManagerNative.getDefault();
4539            if (am != null) {
4540                try {
4541                    am.killUid(appId, userId, reason);
4542                } catch (RemoteException e) {
4543                    /* ignore - same process */
4544                }
4545            }
4546        } finally {
4547            Binder.restoreCallingIdentity(identity);
4548        }
4549    }
4550
4551    /**
4552     * Compares two sets of signatures. Returns:
4553     * <br />
4554     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4555     * <br />
4556     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4557     * <br />
4558     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4559     * <br />
4560     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4561     * <br />
4562     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4563     */
4564    static int compareSignatures(Signature[] s1, Signature[] s2) {
4565        if (s1 == null) {
4566            return s2 == null
4567                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4568                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4569        }
4570
4571        if (s2 == null) {
4572            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4573        }
4574
4575        if (s1.length != s2.length) {
4576            return PackageManager.SIGNATURE_NO_MATCH;
4577        }
4578
4579        // Since both signature sets are of size 1, we can compare without HashSets.
4580        if (s1.length == 1) {
4581            return s1[0].equals(s2[0]) ?
4582                    PackageManager.SIGNATURE_MATCH :
4583                    PackageManager.SIGNATURE_NO_MATCH;
4584        }
4585
4586        ArraySet<Signature> set1 = new ArraySet<Signature>();
4587        for (Signature sig : s1) {
4588            set1.add(sig);
4589        }
4590        ArraySet<Signature> set2 = new ArraySet<Signature>();
4591        for (Signature sig : s2) {
4592            set2.add(sig);
4593        }
4594        // Make sure s2 contains all signatures in s1.
4595        if (set1.equals(set2)) {
4596            return PackageManager.SIGNATURE_MATCH;
4597        }
4598        return PackageManager.SIGNATURE_NO_MATCH;
4599    }
4600
4601    /**
4602     * If the database version for this type of package (internal storage or
4603     * external storage) is less than the version where package signatures
4604     * were updated, return true.
4605     */
4606    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4607        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4608        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4609    }
4610
4611    /**
4612     * Used for backward compatibility to make sure any packages with
4613     * certificate chains get upgraded to the new style. {@code existingSigs}
4614     * will be in the old format (since they were stored on disk from before the
4615     * system upgrade) and {@code scannedSigs} will be in the newer format.
4616     */
4617    private int compareSignaturesCompat(PackageSignatures existingSigs,
4618            PackageParser.Package scannedPkg) {
4619        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4620            return PackageManager.SIGNATURE_NO_MATCH;
4621        }
4622
4623        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4624        for (Signature sig : existingSigs.mSignatures) {
4625            existingSet.add(sig);
4626        }
4627        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4628        for (Signature sig : scannedPkg.mSignatures) {
4629            try {
4630                Signature[] chainSignatures = sig.getChainSignatures();
4631                for (Signature chainSig : chainSignatures) {
4632                    scannedCompatSet.add(chainSig);
4633                }
4634            } catch (CertificateEncodingException e) {
4635                scannedCompatSet.add(sig);
4636            }
4637        }
4638        /*
4639         * Make sure the expanded scanned set contains all signatures in the
4640         * existing one.
4641         */
4642        if (scannedCompatSet.equals(existingSet)) {
4643            // Migrate the old signatures to the new scheme.
4644            existingSigs.assignSignatures(scannedPkg.mSignatures);
4645            // The new KeySets will be re-added later in the scanning process.
4646            synchronized (mPackages) {
4647                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4648            }
4649            return PackageManager.SIGNATURE_MATCH;
4650        }
4651        return PackageManager.SIGNATURE_NO_MATCH;
4652    }
4653
4654    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4655        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4656        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4657    }
4658
4659    private int compareSignaturesRecover(PackageSignatures existingSigs,
4660            PackageParser.Package scannedPkg) {
4661        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4662            return PackageManager.SIGNATURE_NO_MATCH;
4663        }
4664
4665        String msg = null;
4666        try {
4667            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4668                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4669                        + scannedPkg.packageName);
4670                return PackageManager.SIGNATURE_MATCH;
4671            }
4672        } catch (CertificateException e) {
4673            msg = e.getMessage();
4674        }
4675
4676        logCriticalInfo(Log.INFO,
4677                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4678        return PackageManager.SIGNATURE_NO_MATCH;
4679    }
4680
4681    @Override
4682    public List<String> getAllPackages() {
4683        synchronized (mPackages) {
4684            return new ArrayList<String>(mPackages.keySet());
4685        }
4686    }
4687
4688    @Override
4689    public String[] getPackagesForUid(int uid) {
4690        uid = UserHandle.getAppId(uid);
4691        // reader
4692        synchronized (mPackages) {
4693            Object obj = mSettings.getUserIdLPr(uid);
4694            if (obj instanceof SharedUserSetting) {
4695                final SharedUserSetting sus = (SharedUserSetting) obj;
4696                final int N = sus.packages.size();
4697                final String[] res = new String[N];
4698                final Iterator<PackageSetting> it = sus.packages.iterator();
4699                int i = 0;
4700                while (it.hasNext()) {
4701                    res[i++] = it.next().name;
4702                }
4703                return res;
4704            } else if (obj instanceof PackageSetting) {
4705                final PackageSetting ps = (PackageSetting) obj;
4706                return new String[] { ps.name };
4707            }
4708        }
4709        return null;
4710    }
4711
4712    @Override
4713    public String getNameForUid(int uid) {
4714        // reader
4715        synchronized (mPackages) {
4716            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4717            if (obj instanceof SharedUserSetting) {
4718                final SharedUserSetting sus = (SharedUserSetting) obj;
4719                return sus.name + ":" + sus.userId;
4720            } else if (obj instanceof PackageSetting) {
4721                final PackageSetting ps = (PackageSetting) obj;
4722                return ps.name;
4723            }
4724        }
4725        return null;
4726    }
4727
4728    @Override
4729    public int getUidForSharedUser(String sharedUserName) {
4730        if(sharedUserName == null) {
4731            return -1;
4732        }
4733        // reader
4734        synchronized (mPackages) {
4735            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4736            if (suid == null) {
4737                return -1;
4738            }
4739            return suid.userId;
4740        }
4741    }
4742
4743    @Override
4744    public int getFlagsForUid(int uid) {
4745        synchronized (mPackages) {
4746            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4747            if (obj instanceof SharedUserSetting) {
4748                final SharedUserSetting sus = (SharedUserSetting) obj;
4749                return sus.pkgFlags;
4750            } else if (obj instanceof PackageSetting) {
4751                final PackageSetting ps = (PackageSetting) obj;
4752                return ps.pkgFlags;
4753            }
4754        }
4755        return 0;
4756    }
4757
4758    @Override
4759    public int getPrivateFlagsForUid(int uid) {
4760        synchronized (mPackages) {
4761            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4762            if (obj instanceof SharedUserSetting) {
4763                final SharedUserSetting sus = (SharedUserSetting) obj;
4764                return sus.pkgPrivateFlags;
4765            } else if (obj instanceof PackageSetting) {
4766                final PackageSetting ps = (PackageSetting) obj;
4767                return ps.pkgPrivateFlags;
4768            }
4769        }
4770        return 0;
4771    }
4772
4773    @Override
4774    public boolean isUidPrivileged(int uid) {
4775        uid = UserHandle.getAppId(uid);
4776        // reader
4777        synchronized (mPackages) {
4778            Object obj = mSettings.getUserIdLPr(uid);
4779            if (obj instanceof SharedUserSetting) {
4780                final SharedUserSetting sus = (SharedUserSetting) obj;
4781                final Iterator<PackageSetting> it = sus.packages.iterator();
4782                while (it.hasNext()) {
4783                    if (it.next().isPrivileged()) {
4784                        return true;
4785                    }
4786                }
4787            } else if (obj instanceof PackageSetting) {
4788                final PackageSetting ps = (PackageSetting) obj;
4789                return ps.isPrivileged();
4790            }
4791        }
4792        return false;
4793    }
4794
4795    @Override
4796    public String[] getAppOpPermissionPackages(String permissionName) {
4797        synchronized (mPackages) {
4798            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4799            if (pkgs == null) {
4800                return null;
4801            }
4802            return pkgs.toArray(new String[pkgs.size()]);
4803        }
4804    }
4805
4806    @Override
4807    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4808            int flags, int userId) {
4809        try {
4810            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4811
4812            if (!sUserManager.exists(userId)) return null;
4813            flags = updateFlagsForResolve(flags, userId, intent);
4814            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4815                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4816
4817            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4818            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4819                    flags, userId);
4820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4821
4822            final ResolveInfo bestChoice =
4823                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4824
4825            if (isEphemeralAllowed(intent, query, userId)) {
4826                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4827                final EphemeralResolveInfo ai =
4828                        getEphemeralResolveInfo(intent, resolvedType, userId);
4829                if (ai != null) {
4830                    if (DEBUG_EPHEMERAL) {
4831                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4832                    }
4833                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4834                    bestChoice.ephemeralResolveInfo = ai;
4835                }
4836                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4837            }
4838            return bestChoice;
4839        } finally {
4840            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4841        }
4842    }
4843
4844    @Override
4845    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4846            IntentFilter filter, int match, ComponentName activity) {
4847        final int userId = UserHandle.getCallingUserId();
4848        if (DEBUG_PREFERRED) {
4849            Log.v(TAG, "setLastChosenActivity intent=" + intent
4850                + " resolvedType=" + resolvedType
4851                + " flags=" + flags
4852                + " filter=" + filter
4853                + " match=" + match
4854                + " activity=" + activity);
4855            filter.dump(new PrintStreamPrinter(System.out), "    ");
4856        }
4857        intent.setComponent(null);
4858        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4859                userId);
4860        // Find any earlier preferred or last chosen entries and nuke them
4861        findPreferredActivity(intent, resolvedType,
4862                flags, query, 0, false, true, false, userId);
4863        // Add the new activity as the last chosen for this filter
4864        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4865                "Setting last chosen");
4866    }
4867
4868    @Override
4869    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4870        final int userId = UserHandle.getCallingUserId();
4871        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4872        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4873                userId);
4874        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4875                false, false, false, userId);
4876    }
4877
4878
4879    private boolean isEphemeralAllowed(
4880            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4881        // Short circuit and return early if possible.
4882        if (DISABLE_EPHEMERAL_APPS) {
4883            return false;
4884        }
4885        final int callingUser = UserHandle.getCallingUserId();
4886        if (callingUser != UserHandle.USER_SYSTEM) {
4887            return false;
4888        }
4889        if (mEphemeralResolverConnection == null) {
4890            return false;
4891        }
4892        if (intent.getComponent() != null) {
4893            return false;
4894        }
4895        if (intent.getPackage() != null) {
4896            return false;
4897        }
4898        final boolean isWebUri = hasWebURI(intent);
4899        if (!isWebUri) {
4900            return false;
4901        }
4902        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4903        synchronized (mPackages) {
4904            final int count = resolvedActivites.size();
4905            for (int n = 0; n < count; n++) {
4906                ResolveInfo info = resolvedActivites.get(n);
4907                String packageName = info.activityInfo.packageName;
4908                PackageSetting ps = mSettings.mPackages.get(packageName);
4909                if (ps != null) {
4910                    // Try to get the status from User settings first
4911                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4912                    int status = (int) (packedStatus >> 32);
4913                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4914                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4915                        if (DEBUG_EPHEMERAL) {
4916                            Slog.v(TAG, "DENY ephemeral apps;"
4917                                + " pkg: " + packageName + ", status: " + status);
4918                        }
4919                        return false;
4920                    }
4921                }
4922            }
4923        }
4924        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4925        return true;
4926    }
4927
4928    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4929            int userId) {
4930        MessageDigest digest = null;
4931        try {
4932            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4933        } catch (NoSuchAlgorithmException e) {
4934            // If we can't create a digest, ignore ephemeral apps.
4935            return null;
4936        }
4937
4938        final byte[] hostBytes = intent.getData().getHost().getBytes();
4939        final byte[] digestBytes = digest.digest(hostBytes);
4940        int shaPrefix =
4941                digestBytes[0] << 24
4942                | digestBytes[1] << 16
4943                | digestBytes[2] << 8
4944                | digestBytes[3] << 0;
4945        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4946                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4947        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4948            // No hash prefix match; there are no ephemeral apps for this domain.
4949            return null;
4950        }
4951        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4952            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4953            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4954                continue;
4955            }
4956            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4957            // No filters; this should never happen.
4958            if (filters.isEmpty()) {
4959                continue;
4960            }
4961            // We have a domain match; resolve the filters to see if anything matches.
4962            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4963            for (int j = filters.size() - 1; j >= 0; --j) {
4964                final EphemeralResolveIntentInfo intentInfo =
4965                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4966                ephemeralResolver.addFilter(intentInfo);
4967            }
4968            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4969                    intent, resolvedType, false /*defaultOnly*/, userId);
4970            if (!matchedResolveInfoList.isEmpty()) {
4971                return matchedResolveInfoList.get(0);
4972            }
4973        }
4974        // Hash or filter mis-match; no ephemeral apps for this domain.
4975        return null;
4976    }
4977
4978    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4979            int flags, List<ResolveInfo> query, int userId) {
4980        if (query != null) {
4981            final int N = query.size();
4982            if (N == 1) {
4983                return query.get(0);
4984            } else if (N > 1) {
4985                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4986                // If there is more than one activity with the same priority,
4987                // then let the user decide between them.
4988                ResolveInfo r0 = query.get(0);
4989                ResolveInfo r1 = query.get(1);
4990                if (DEBUG_INTENT_MATCHING || debug) {
4991                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4992                            + r1.activityInfo.name + "=" + r1.priority);
4993                }
4994                // If the first activity has a higher priority, or a different
4995                // default, then it is always desirable to pick it.
4996                if (r0.priority != r1.priority
4997                        || r0.preferredOrder != r1.preferredOrder
4998                        || r0.isDefault != r1.isDefault) {
4999                    return query.get(0);
5000                }
5001                // If we have saved a preference for a preferred activity for
5002                // this Intent, use that.
5003                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5004                        flags, query, r0.priority, true, false, debug, userId);
5005                if (ri != null) {
5006                    return ri;
5007                }
5008                ri = new ResolveInfo(mResolveInfo);
5009                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5010                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5011                ri.activityInfo.applicationInfo = new ApplicationInfo(
5012                        ri.activityInfo.applicationInfo);
5013                if (userId != 0) {
5014                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5015                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5016                }
5017                // Make sure that the resolver is displayable in car mode
5018                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5019                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5020                return ri;
5021            }
5022        }
5023        return null;
5024    }
5025
5026    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5027            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5028        final int N = query.size();
5029        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5030                .get(userId);
5031        // Get the list of persistent preferred activities that handle the intent
5032        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5033        List<PersistentPreferredActivity> pprefs = ppir != null
5034                ? ppir.queryIntent(intent, resolvedType,
5035                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5036                : null;
5037        if (pprefs != null && pprefs.size() > 0) {
5038            final int M = pprefs.size();
5039            for (int i=0; i<M; i++) {
5040                final PersistentPreferredActivity ppa = pprefs.get(i);
5041                if (DEBUG_PREFERRED || debug) {
5042                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5043                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5044                            + "\n  component=" + ppa.mComponent);
5045                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5046                }
5047                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5048                        flags | MATCH_DISABLED_COMPONENTS, userId);
5049                if (DEBUG_PREFERRED || debug) {
5050                    Slog.v(TAG, "Found persistent preferred activity:");
5051                    if (ai != null) {
5052                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5053                    } else {
5054                        Slog.v(TAG, "  null");
5055                    }
5056                }
5057                if (ai == null) {
5058                    // This previously registered persistent preferred activity
5059                    // component is no longer known. Ignore it and do NOT remove it.
5060                    continue;
5061                }
5062                for (int j=0; j<N; j++) {
5063                    final ResolveInfo ri = query.get(j);
5064                    if (!ri.activityInfo.applicationInfo.packageName
5065                            .equals(ai.applicationInfo.packageName)) {
5066                        continue;
5067                    }
5068                    if (!ri.activityInfo.name.equals(ai.name)) {
5069                        continue;
5070                    }
5071                    //  Found a persistent preference that can handle the intent.
5072                    if (DEBUG_PREFERRED || debug) {
5073                        Slog.v(TAG, "Returning persistent preferred activity: " +
5074                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5075                    }
5076                    return ri;
5077                }
5078            }
5079        }
5080        return null;
5081    }
5082
5083    // TODO: handle preferred activities missing while user has amnesia
5084    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5085            List<ResolveInfo> query, int priority, boolean always,
5086            boolean removeMatches, boolean debug, int userId) {
5087        if (!sUserManager.exists(userId)) return null;
5088        flags = updateFlagsForResolve(flags, userId, intent);
5089        // writer
5090        synchronized (mPackages) {
5091            if (intent.getSelector() != null) {
5092                intent = intent.getSelector();
5093            }
5094            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5095
5096            // Try to find a matching persistent preferred activity.
5097            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5098                    debug, userId);
5099
5100            // If a persistent preferred activity matched, use it.
5101            if (pri != null) {
5102                return pri;
5103            }
5104
5105            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5106            // Get the list of preferred activities that handle the intent
5107            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5108            List<PreferredActivity> prefs = pir != null
5109                    ? pir.queryIntent(intent, resolvedType,
5110                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5111                    : null;
5112            if (prefs != null && prefs.size() > 0) {
5113                boolean changed = false;
5114                try {
5115                    // First figure out how good the original match set is.
5116                    // We will only allow preferred activities that came
5117                    // from the same match quality.
5118                    int match = 0;
5119
5120                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5121
5122                    final int N = query.size();
5123                    for (int j=0; j<N; j++) {
5124                        final ResolveInfo ri = query.get(j);
5125                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5126                                + ": 0x" + Integer.toHexString(match));
5127                        if (ri.match > match) {
5128                            match = ri.match;
5129                        }
5130                    }
5131
5132                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5133                            + Integer.toHexString(match));
5134
5135                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5136                    final int M = prefs.size();
5137                    for (int i=0; i<M; i++) {
5138                        final PreferredActivity pa = prefs.get(i);
5139                        if (DEBUG_PREFERRED || debug) {
5140                            Slog.v(TAG, "Checking PreferredActivity ds="
5141                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5142                                    + "\n  component=" + pa.mPref.mComponent);
5143                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5144                        }
5145                        if (pa.mPref.mMatch != match) {
5146                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5147                                    + Integer.toHexString(pa.mPref.mMatch));
5148                            continue;
5149                        }
5150                        // If it's not an "always" type preferred activity and that's what we're
5151                        // looking for, skip it.
5152                        if (always && !pa.mPref.mAlways) {
5153                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5154                            continue;
5155                        }
5156                        final ActivityInfo ai = getActivityInfo(
5157                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5158                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5159                                userId);
5160                        if (DEBUG_PREFERRED || debug) {
5161                            Slog.v(TAG, "Found preferred activity:");
5162                            if (ai != null) {
5163                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5164                            } else {
5165                                Slog.v(TAG, "  null");
5166                            }
5167                        }
5168                        if (ai == null) {
5169                            // This previously registered preferred activity
5170                            // component is no longer known.  Most likely an update
5171                            // to the app was installed and in the new version this
5172                            // component no longer exists.  Clean it up by removing
5173                            // it from the preferred activities list, and skip it.
5174                            Slog.w(TAG, "Removing dangling preferred activity: "
5175                                    + pa.mPref.mComponent);
5176                            pir.removeFilter(pa);
5177                            changed = true;
5178                            continue;
5179                        }
5180                        for (int j=0; j<N; j++) {
5181                            final ResolveInfo ri = query.get(j);
5182                            if (!ri.activityInfo.applicationInfo.packageName
5183                                    .equals(ai.applicationInfo.packageName)) {
5184                                continue;
5185                            }
5186                            if (!ri.activityInfo.name.equals(ai.name)) {
5187                                continue;
5188                            }
5189
5190                            if (removeMatches) {
5191                                pir.removeFilter(pa);
5192                                changed = true;
5193                                if (DEBUG_PREFERRED) {
5194                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5195                                }
5196                                break;
5197                            }
5198
5199                            // Okay we found a previously set preferred or last chosen app.
5200                            // If the result set is different from when this
5201                            // was created, we need to clear it and re-ask the
5202                            // user their preference, if we're looking for an "always" type entry.
5203                            if (always && !pa.mPref.sameSet(query)) {
5204                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5205                                        + intent + " type " + resolvedType);
5206                                if (DEBUG_PREFERRED) {
5207                                    Slog.v(TAG, "Removing preferred activity since set changed "
5208                                            + pa.mPref.mComponent);
5209                                }
5210                                pir.removeFilter(pa);
5211                                // Re-add the filter as a "last chosen" entry (!always)
5212                                PreferredActivity lastChosen = new PreferredActivity(
5213                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5214                                pir.addFilter(lastChosen);
5215                                changed = true;
5216                                return null;
5217                            }
5218
5219                            // Yay! Either the set matched or we're looking for the last chosen
5220                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5221                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5222                            return ri;
5223                        }
5224                    }
5225                } finally {
5226                    if (changed) {
5227                        if (DEBUG_PREFERRED) {
5228                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5229                        }
5230                        scheduleWritePackageRestrictionsLocked(userId);
5231                    }
5232                }
5233            }
5234        }
5235        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5236        return null;
5237    }
5238
5239    /*
5240     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5241     */
5242    @Override
5243    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5244            int targetUserId) {
5245        mContext.enforceCallingOrSelfPermission(
5246                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5247        List<CrossProfileIntentFilter> matches =
5248                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5249        if (matches != null) {
5250            int size = matches.size();
5251            for (int i = 0; i < size; i++) {
5252                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5253            }
5254        }
5255        if (hasWebURI(intent)) {
5256            // cross-profile app linking works only towards the parent.
5257            final UserInfo parent = getProfileParent(sourceUserId);
5258            synchronized(mPackages) {
5259                int flags = updateFlagsForResolve(0, parent.id, intent);
5260                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5261                        intent, resolvedType, flags, sourceUserId, parent.id);
5262                return xpDomainInfo != null;
5263            }
5264        }
5265        return false;
5266    }
5267
5268    private UserInfo getProfileParent(int userId) {
5269        final long identity = Binder.clearCallingIdentity();
5270        try {
5271            return sUserManager.getProfileParent(userId);
5272        } finally {
5273            Binder.restoreCallingIdentity(identity);
5274        }
5275    }
5276
5277    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5278            String resolvedType, int userId) {
5279        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5280        if (resolver != null) {
5281            return resolver.queryIntent(intent, resolvedType, false, userId);
5282        }
5283        return null;
5284    }
5285
5286    @Override
5287    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5288            String resolvedType, int flags, int userId) {
5289        try {
5290            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5291
5292            return new ParceledListSlice<>(
5293                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5294        } finally {
5295            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5296        }
5297    }
5298
5299    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5300            String resolvedType, int flags, int userId) {
5301        if (!sUserManager.exists(userId)) return Collections.emptyList();
5302        flags = updateFlagsForResolve(flags, userId, intent);
5303        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5304                false /* requireFullPermission */, false /* checkShell */,
5305                "query intent activities");
5306        ComponentName comp = intent.getComponent();
5307        if (comp == null) {
5308            if (intent.getSelector() != null) {
5309                intent = intent.getSelector();
5310                comp = intent.getComponent();
5311            }
5312        }
5313
5314        if (comp != null) {
5315            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5316            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5317            if (ai != null) {
5318                final ResolveInfo ri = new ResolveInfo();
5319                ri.activityInfo = ai;
5320                list.add(ri);
5321            }
5322            return list;
5323        }
5324
5325        // reader
5326        synchronized (mPackages) {
5327            final String pkgName = intent.getPackage();
5328            if (pkgName == null) {
5329                List<CrossProfileIntentFilter> matchingFilters =
5330                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5331                // Check for results that need to skip the current profile.
5332                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5333                        resolvedType, flags, userId);
5334                if (xpResolveInfo != null) {
5335                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5336                    result.add(xpResolveInfo);
5337                    return filterIfNotSystemUser(result, userId);
5338                }
5339
5340                // Check for results in the current profile.
5341                List<ResolveInfo> result = mActivities.queryIntent(
5342                        intent, resolvedType, flags, userId);
5343                result = filterIfNotSystemUser(result, userId);
5344
5345                // Check for cross profile results.
5346                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5347                xpResolveInfo = queryCrossProfileIntents(
5348                        matchingFilters, intent, resolvedType, flags, userId,
5349                        hasNonNegativePriorityResult);
5350                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5351                    boolean isVisibleToUser = filterIfNotSystemUser(
5352                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5353                    if (isVisibleToUser) {
5354                        result.add(xpResolveInfo);
5355                        Collections.sort(result, mResolvePrioritySorter);
5356                    }
5357                }
5358                if (hasWebURI(intent)) {
5359                    CrossProfileDomainInfo xpDomainInfo = null;
5360                    final UserInfo parent = getProfileParent(userId);
5361                    if (parent != null) {
5362                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5363                                flags, userId, parent.id);
5364                    }
5365                    if (xpDomainInfo != null) {
5366                        if (xpResolveInfo != null) {
5367                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5368                            // in the result.
5369                            result.remove(xpResolveInfo);
5370                        }
5371                        if (result.size() == 0) {
5372                            result.add(xpDomainInfo.resolveInfo);
5373                            return result;
5374                        }
5375                    } else if (result.size() <= 1) {
5376                        return result;
5377                    }
5378                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5379                            xpDomainInfo, userId);
5380                    Collections.sort(result, mResolvePrioritySorter);
5381                }
5382                return result;
5383            }
5384            final PackageParser.Package pkg = mPackages.get(pkgName);
5385            if (pkg != null) {
5386                return filterIfNotSystemUser(
5387                        mActivities.queryIntentForPackage(
5388                                intent, resolvedType, flags, pkg.activities, userId),
5389                        userId);
5390            }
5391            return new ArrayList<ResolveInfo>();
5392        }
5393    }
5394
5395    private static class CrossProfileDomainInfo {
5396        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5397        ResolveInfo resolveInfo;
5398        /* Best domain verification status of the activities found in the other profile */
5399        int bestDomainVerificationStatus;
5400    }
5401
5402    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5403            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5404        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5405                sourceUserId)) {
5406            return null;
5407        }
5408        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5409                resolvedType, flags, parentUserId);
5410
5411        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5412            return null;
5413        }
5414        CrossProfileDomainInfo result = null;
5415        int size = resultTargetUser.size();
5416        for (int i = 0; i < size; i++) {
5417            ResolveInfo riTargetUser = resultTargetUser.get(i);
5418            // Intent filter verification is only for filters that specify a host. So don't return
5419            // those that handle all web uris.
5420            if (riTargetUser.handleAllWebDataURI) {
5421                continue;
5422            }
5423            String packageName = riTargetUser.activityInfo.packageName;
5424            PackageSetting ps = mSettings.mPackages.get(packageName);
5425            if (ps == null) {
5426                continue;
5427            }
5428            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5429            int status = (int)(verificationState >> 32);
5430            if (result == null) {
5431                result = new CrossProfileDomainInfo();
5432                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5433                        sourceUserId, parentUserId);
5434                result.bestDomainVerificationStatus = status;
5435            } else {
5436                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5437                        result.bestDomainVerificationStatus);
5438            }
5439        }
5440        // Don't consider matches with status NEVER across profiles.
5441        if (result != null && result.bestDomainVerificationStatus
5442                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5443            return null;
5444        }
5445        return result;
5446    }
5447
5448    /**
5449     * Verification statuses are ordered from the worse to the best, except for
5450     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5451     */
5452    private int bestDomainVerificationStatus(int status1, int status2) {
5453        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5454            return status2;
5455        }
5456        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5457            return status1;
5458        }
5459        return (int) MathUtils.max(status1, status2);
5460    }
5461
5462    private boolean isUserEnabled(int userId) {
5463        long callingId = Binder.clearCallingIdentity();
5464        try {
5465            UserInfo userInfo = sUserManager.getUserInfo(userId);
5466            return userInfo != null && userInfo.isEnabled();
5467        } finally {
5468            Binder.restoreCallingIdentity(callingId);
5469        }
5470    }
5471
5472    /**
5473     * Filter out activities with systemUserOnly flag set, when current user is not System.
5474     *
5475     * @return filtered list
5476     */
5477    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5478        if (userId == UserHandle.USER_SYSTEM) {
5479            return resolveInfos;
5480        }
5481        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5482            ResolveInfo info = resolveInfos.get(i);
5483            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5484                resolveInfos.remove(i);
5485            }
5486        }
5487        return resolveInfos;
5488    }
5489
5490    /**
5491     * @param resolveInfos list of resolve infos in descending priority order
5492     * @return if the list contains a resolve info with non-negative priority
5493     */
5494    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5495        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5496    }
5497
5498    private static boolean hasWebURI(Intent intent) {
5499        if (intent.getData() == null) {
5500            return false;
5501        }
5502        final String scheme = intent.getScheme();
5503        if (TextUtils.isEmpty(scheme)) {
5504            return false;
5505        }
5506        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5507    }
5508
5509    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5510            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5511            int userId) {
5512        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5513
5514        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5515            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5516                    candidates.size());
5517        }
5518
5519        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5520        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5521        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5522        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5523        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5524        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5525
5526        synchronized (mPackages) {
5527            final int count = candidates.size();
5528            // First, try to use linked apps. Partition the candidates into four lists:
5529            // one for the final results, one for the "do not use ever", one for "undefined status"
5530            // and finally one for "browser app type".
5531            for (int n=0; n<count; n++) {
5532                ResolveInfo info = candidates.get(n);
5533                String packageName = info.activityInfo.packageName;
5534                PackageSetting ps = mSettings.mPackages.get(packageName);
5535                if (ps != null) {
5536                    // Add to the special match all list (Browser use case)
5537                    if (info.handleAllWebDataURI) {
5538                        matchAllList.add(info);
5539                        continue;
5540                    }
5541                    // Try to get the status from User settings first
5542                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5543                    int status = (int)(packedStatus >> 32);
5544                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5545                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5546                        if (DEBUG_DOMAIN_VERIFICATION) {
5547                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5548                                    + " : linkgen=" + linkGeneration);
5549                        }
5550                        // Use link-enabled generation as preferredOrder, i.e.
5551                        // prefer newly-enabled over earlier-enabled.
5552                        info.preferredOrder = linkGeneration;
5553                        alwaysList.add(info);
5554                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5555                        if (DEBUG_DOMAIN_VERIFICATION) {
5556                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5557                        }
5558                        neverList.add(info);
5559                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5560                        if (DEBUG_DOMAIN_VERIFICATION) {
5561                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5562                        }
5563                        alwaysAskList.add(info);
5564                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5565                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5566                        if (DEBUG_DOMAIN_VERIFICATION) {
5567                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5568                        }
5569                        undefinedList.add(info);
5570                    }
5571                }
5572            }
5573
5574            // We'll want to include browser possibilities in a few cases
5575            boolean includeBrowser = false;
5576
5577            // First try to add the "always" resolution(s) for the current user, if any
5578            if (alwaysList.size() > 0) {
5579                result.addAll(alwaysList);
5580            } else {
5581                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5582                result.addAll(undefinedList);
5583                // Maybe add one for the other profile.
5584                if (xpDomainInfo != null && (
5585                        xpDomainInfo.bestDomainVerificationStatus
5586                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5587                    result.add(xpDomainInfo.resolveInfo);
5588                }
5589                includeBrowser = true;
5590            }
5591
5592            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5593            // If there were 'always' entries their preferred order has been set, so we also
5594            // back that off to make the alternatives equivalent
5595            if (alwaysAskList.size() > 0) {
5596                for (ResolveInfo i : result) {
5597                    i.preferredOrder = 0;
5598                }
5599                result.addAll(alwaysAskList);
5600                includeBrowser = true;
5601            }
5602
5603            if (includeBrowser) {
5604                // Also add browsers (all of them or only the default one)
5605                if (DEBUG_DOMAIN_VERIFICATION) {
5606                    Slog.v(TAG, "   ...including browsers in candidate set");
5607                }
5608                if ((matchFlags & MATCH_ALL) != 0) {
5609                    result.addAll(matchAllList);
5610                } else {
5611                    // Browser/generic handling case.  If there's a default browser, go straight
5612                    // to that (but only if there is no other higher-priority match).
5613                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5614                    int maxMatchPrio = 0;
5615                    ResolveInfo defaultBrowserMatch = null;
5616                    final int numCandidates = matchAllList.size();
5617                    for (int n = 0; n < numCandidates; n++) {
5618                        ResolveInfo info = matchAllList.get(n);
5619                        // track the highest overall match priority...
5620                        if (info.priority > maxMatchPrio) {
5621                            maxMatchPrio = info.priority;
5622                        }
5623                        // ...and the highest-priority default browser match
5624                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5625                            if (defaultBrowserMatch == null
5626                                    || (defaultBrowserMatch.priority < info.priority)) {
5627                                if (debug) {
5628                                    Slog.v(TAG, "Considering default browser match " + info);
5629                                }
5630                                defaultBrowserMatch = info;
5631                            }
5632                        }
5633                    }
5634                    if (defaultBrowserMatch != null
5635                            && defaultBrowserMatch.priority >= maxMatchPrio
5636                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5637                    {
5638                        if (debug) {
5639                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5640                        }
5641                        result.add(defaultBrowserMatch);
5642                    } else {
5643                        result.addAll(matchAllList);
5644                    }
5645                }
5646
5647                // If there is nothing selected, add all candidates and remove the ones that the user
5648                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5649                if (result.size() == 0) {
5650                    result.addAll(candidates);
5651                    result.removeAll(neverList);
5652                }
5653            }
5654        }
5655        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5656            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5657                    result.size());
5658            for (ResolveInfo info : result) {
5659                Slog.v(TAG, "  + " + info.activityInfo);
5660            }
5661        }
5662        return result;
5663    }
5664
5665    // Returns a packed value as a long:
5666    //
5667    // high 'int'-sized word: link status: undefined/ask/never/always.
5668    // low 'int'-sized word: relative priority among 'always' results.
5669    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5670        long result = ps.getDomainVerificationStatusForUser(userId);
5671        // if none available, get the master status
5672        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5673            if (ps.getIntentFilterVerificationInfo() != null) {
5674                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5675            }
5676        }
5677        return result;
5678    }
5679
5680    private ResolveInfo querySkipCurrentProfileIntents(
5681            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5682            int flags, int sourceUserId) {
5683        if (matchingFilters != null) {
5684            int size = matchingFilters.size();
5685            for (int i = 0; i < size; i ++) {
5686                CrossProfileIntentFilter filter = matchingFilters.get(i);
5687                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5688                    // Checking if there are activities in the target user that can handle the
5689                    // intent.
5690                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5691                            resolvedType, flags, sourceUserId);
5692                    if (resolveInfo != null) {
5693                        return resolveInfo;
5694                    }
5695                }
5696            }
5697        }
5698        return null;
5699    }
5700
5701    // Return matching ResolveInfo in target user if any.
5702    private ResolveInfo queryCrossProfileIntents(
5703            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5704            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5705        if (matchingFilters != null) {
5706            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5707            // match the same intent. For performance reasons, it is better not to
5708            // run queryIntent twice for the same userId
5709            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5710            int size = matchingFilters.size();
5711            for (int i = 0; i < size; i++) {
5712                CrossProfileIntentFilter filter = matchingFilters.get(i);
5713                int targetUserId = filter.getTargetUserId();
5714                boolean skipCurrentProfile =
5715                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5716                boolean skipCurrentProfileIfNoMatchFound =
5717                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5718                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5719                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5720                    // Checking if there are activities in the target user that can handle the
5721                    // intent.
5722                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5723                            resolvedType, flags, sourceUserId);
5724                    if (resolveInfo != null) return resolveInfo;
5725                    alreadyTriedUserIds.put(targetUserId, true);
5726                }
5727            }
5728        }
5729        return null;
5730    }
5731
5732    /**
5733     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5734     * will forward the intent to the filter's target user.
5735     * Otherwise, returns null.
5736     */
5737    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5738            String resolvedType, int flags, int sourceUserId) {
5739        int targetUserId = filter.getTargetUserId();
5740        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5741                resolvedType, flags, targetUserId);
5742        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5743            // If all the matches in the target profile are suspended, return null.
5744            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5745                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5746                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5747                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5748                            targetUserId);
5749                }
5750            }
5751        }
5752        return null;
5753    }
5754
5755    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5756            int sourceUserId, int targetUserId) {
5757        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5758        long ident = Binder.clearCallingIdentity();
5759        boolean targetIsProfile;
5760        try {
5761            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5762        } finally {
5763            Binder.restoreCallingIdentity(ident);
5764        }
5765        String className;
5766        if (targetIsProfile) {
5767            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5768        } else {
5769            className = FORWARD_INTENT_TO_PARENT;
5770        }
5771        ComponentName forwardingActivityComponentName = new ComponentName(
5772                mAndroidApplication.packageName, className);
5773        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5774                sourceUserId);
5775        if (!targetIsProfile) {
5776            forwardingActivityInfo.showUserIcon = targetUserId;
5777            forwardingResolveInfo.noResourceId = true;
5778        }
5779        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5780        forwardingResolveInfo.priority = 0;
5781        forwardingResolveInfo.preferredOrder = 0;
5782        forwardingResolveInfo.match = 0;
5783        forwardingResolveInfo.isDefault = true;
5784        forwardingResolveInfo.filter = filter;
5785        forwardingResolveInfo.targetUserId = targetUserId;
5786        return forwardingResolveInfo;
5787    }
5788
5789    @Override
5790    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5791            Intent[] specifics, String[] specificTypes, Intent intent,
5792            String resolvedType, int flags, int userId) {
5793        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5794                specificTypes, intent, resolvedType, flags, userId));
5795    }
5796
5797    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5798            Intent[] specifics, String[] specificTypes, Intent intent,
5799            String resolvedType, int flags, int userId) {
5800        if (!sUserManager.exists(userId)) return Collections.emptyList();
5801        flags = updateFlagsForResolve(flags, userId, intent);
5802        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5803                false /* requireFullPermission */, false /* checkShell */,
5804                "query intent activity options");
5805        final String resultsAction = intent.getAction();
5806
5807        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5808                | PackageManager.GET_RESOLVED_FILTER, userId);
5809
5810        if (DEBUG_INTENT_MATCHING) {
5811            Log.v(TAG, "Query " + intent + ": " + results);
5812        }
5813
5814        int specificsPos = 0;
5815        int N;
5816
5817        // todo: note that the algorithm used here is O(N^2).  This
5818        // isn't a problem in our current environment, but if we start running
5819        // into situations where we have more than 5 or 10 matches then this
5820        // should probably be changed to something smarter...
5821
5822        // First we go through and resolve each of the specific items
5823        // that were supplied, taking care of removing any corresponding
5824        // duplicate items in the generic resolve list.
5825        if (specifics != null) {
5826            for (int i=0; i<specifics.length; i++) {
5827                final Intent sintent = specifics[i];
5828                if (sintent == null) {
5829                    continue;
5830                }
5831
5832                if (DEBUG_INTENT_MATCHING) {
5833                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5834                }
5835
5836                String action = sintent.getAction();
5837                if (resultsAction != null && resultsAction.equals(action)) {
5838                    // If this action was explicitly requested, then don't
5839                    // remove things that have it.
5840                    action = null;
5841                }
5842
5843                ResolveInfo ri = null;
5844                ActivityInfo ai = null;
5845
5846                ComponentName comp = sintent.getComponent();
5847                if (comp == null) {
5848                    ri = resolveIntent(
5849                        sintent,
5850                        specificTypes != null ? specificTypes[i] : null,
5851                            flags, userId);
5852                    if (ri == null) {
5853                        continue;
5854                    }
5855                    if (ri == mResolveInfo) {
5856                        // ACK!  Must do something better with this.
5857                    }
5858                    ai = ri.activityInfo;
5859                    comp = new ComponentName(ai.applicationInfo.packageName,
5860                            ai.name);
5861                } else {
5862                    ai = getActivityInfo(comp, flags, userId);
5863                    if (ai == null) {
5864                        continue;
5865                    }
5866                }
5867
5868                // Look for any generic query activities that are duplicates
5869                // of this specific one, and remove them from the results.
5870                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5871                N = results.size();
5872                int j;
5873                for (j=specificsPos; j<N; j++) {
5874                    ResolveInfo sri = results.get(j);
5875                    if ((sri.activityInfo.name.equals(comp.getClassName())
5876                            && sri.activityInfo.applicationInfo.packageName.equals(
5877                                    comp.getPackageName()))
5878                        || (action != null && sri.filter.matchAction(action))) {
5879                        results.remove(j);
5880                        if (DEBUG_INTENT_MATCHING) Log.v(
5881                            TAG, "Removing duplicate item from " + j
5882                            + " due to specific " + specificsPos);
5883                        if (ri == null) {
5884                            ri = sri;
5885                        }
5886                        j--;
5887                        N--;
5888                    }
5889                }
5890
5891                // Add this specific item to its proper place.
5892                if (ri == null) {
5893                    ri = new ResolveInfo();
5894                    ri.activityInfo = ai;
5895                }
5896                results.add(specificsPos, ri);
5897                ri.specificIndex = i;
5898                specificsPos++;
5899            }
5900        }
5901
5902        // Now we go through the remaining generic results and remove any
5903        // duplicate actions that are found here.
5904        N = results.size();
5905        for (int i=specificsPos; i<N-1; i++) {
5906            final ResolveInfo rii = results.get(i);
5907            if (rii.filter == null) {
5908                continue;
5909            }
5910
5911            // Iterate over all of the actions of this result's intent
5912            // filter...  typically this should be just one.
5913            final Iterator<String> it = rii.filter.actionsIterator();
5914            if (it == null) {
5915                continue;
5916            }
5917            while (it.hasNext()) {
5918                final String action = it.next();
5919                if (resultsAction != null && resultsAction.equals(action)) {
5920                    // If this action was explicitly requested, then don't
5921                    // remove things that have it.
5922                    continue;
5923                }
5924                for (int j=i+1; j<N; j++) {
5925                    final ResolveInfo rij = results.get(j);
5926                    if (rij.filter != null && rij.filter.hasAction(action)) {
5927                        results.remove(j);
5928                        if (DEBUG_INTENT_MATCHING) Log.v(
5929                            TAG, "Removing duplicate item from " + j
5930                            + " due to action " + action + " at " + i);
5931                        j--;
5932                        N--;
5933                    }
5934                }
5935            }
5936
5937            // If the caller didn't request filter information, drop it now
5938            // so we don't have to marshall/unmarshall it.
5939            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5940                rii.filter = null;
5941            }
5942        }
5943
5944        // Filter out the caller activity if so requested.
5945        if (caller != null) {
5946            N = results.size();
5947            for (int i=0; i<N; i++) {
5948                ActivityInfo ainfo = results.get(i).activityInfo;
5949                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5950                        && caller.getClassName().equals(ainfo.name)) {
5951                    results.remove(i);
5952                    break;
5953                }
5954            }
5955        }
5956
5957        // If the caller didn't request filter information,
5958        // drop them now so we don't have to
5959        // marshall/unmarshall it.
5960        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5961            N = results.size();
5962            for (int i=0; i<N; i++) {
5963                results.get(i).filter = null;
5964            }
5965        }
5966
5967        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5968        return results;
5969    }
5970
5971    @Override
5972    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5973            String resolvedType, int flags, int userId) {
5974        return new ParceledListSlice<>(
5975                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5976    }
5977
5978    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5979            String resolvedType, int flags, int userId) {
5980        if (!sUserManager.exists(userId)) return Collections.emptyList();
5981        flags = updateFlagsForResolve(flags, userId, intent);
5982        ComponentName comp = intent.getComponent();
5983        if (comp == null) {
5984            if (intent.getSelector() != null) {
5985                intent = intent.getSelector();
5986                comp = intent.getComponent();
5987            }
5988        }
5989        if (comp != null) {
5990            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5991            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5992            if (ai != null) {
5993                ResolveInfo ri = new ResolveInfo();
5994                ri.activityInfo = ai;
5995                list.add(ri);
5996            }
5997            return list;
5998        }
5999
6000        // reader
6001        synchronized (mPackages) {
6002            String pkgName = intent.getPackage();
6003            if (pkgName == null) {
6004                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6005            }
6006            final PackageParser.Package pkg = mPackages.get(pkgName);
6007            if (pkg != null) {
6008                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6009                        userId);
6010            }
6011            return Collections.emptyList();
6012        }
6013    }
6014
6015    @Override
6016    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6017        if (!sUserManager.exists(userId)) return null;
6018        flags = updateFlagsForResolve(flags, userId, intent);
6019        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6020        if (query != null) {
6021            if (query.size() >= 1) {
6022                // If there is more than one service with the same priority,
6023                // just arbitrarily pick the first one.
6024                return query.get(0);
6025            }
6026        }
6027        return null;
6028    }
6029
6030    @Override
6031    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6032            String resolvedType, int flags, int userId) {
6033        return new ParceledListSlice<>(
6034                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6035    }
6036
6037    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6038            String resolvedType, int flags, int userId) {
6039        if (!sUserManager.exists(userId)) return Collections.emptyList();
6040        flags = updateFlagsForResolve(flags, userId, intent);
6041        ComponentName comp = intent.getComponent();
6042        if (comp == null) {
6043            if (intent.getSelector() != null) {
6044                intent = intent.getSelector();
6045                comp = intent.getComponent();
6046            }
6047        }
6048        if (comp != null) {
6049            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6050            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6051            if (si != null) {
6052                final ResolveInfo ri = new ResolveInfo();
6053                ri.serviceInfo = si;
6054                list.add(ri);
6055            }
6056            return list;
6057        }
6058
6059        // reader
6060        synchronized (mPackages) {
6061            String pkgName = intent.getPackage();
6062            if (pkgName == null) {
6063                return mServices.queryIntent(intent, resolvedType, flags, userId);
6064            }
6065            final PackageParser.Package pkg = mPackages.get(pkgName);
6066            if (pkg != null) {
6067                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6068                        userId);
6069            }
6070            return Collections.emptyList();
6071        }
6072    }
6073
6074    @Override
6075    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6076            String resolvedType, int flags, int userId) {
6077        return new ParceledListSlice<>(
6078                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6079    }
6080
6081    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6082            Intent intent, String resolvedType, int flags, int userId) {
6083        if (!sUserManager.exists(userId)) return Collections.emptyList();
6084        flags = updateFlagsForResolve(flags, userId, intent);
6085        ComponentName comp = intent.getComponent();
6086        if (comp == null) {
6087            if (intent.getSelector() != null) {
6088                intent = intent.getSelector();
6089                comp = intent.getComponent();
6090            }
6091        }
6092        if (comp != null) {
6093            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6094            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6095            if (pi != null) {
6096                final ResolveInfo ri = new ResolveInfo();
6097                ri.providerInfo = pi;
6098                list.add(ri);
6099            }
6100            return list;
6101        }
6102
6103        // reader
6104        synchronized (mPackages) {
6105            String pkgName = intent.getPackage();
6106            if (pkgName == null) {
6107                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6108            }
6109            final PackageParser.Package pkg = mPackages.get(pkgName);
6110            if (pkg != null) {
6111                return mProviders.queryIntentForPackage(
6112                        intent, resolvedType, flags, pkg.providers, userId);
6113            }
6114            return Collections.emptyList();
6115        }
6116    }
6117
6118    @Override
6119    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6120        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6121        flags = updateFlagsForPackage(flags, userId, null);
6122        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6124                true /* requireFullPermission */, false /* checkShell */,
6125                "get installed packages");
6126
6127        // writer
6128        synchronized (mPackages) {
6129            ArrayList<PackageInfo> list;
6130            if (listUninstalled) {
6131                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6132                for (PackageSetting ps : mSettings.mPackages.values()) {
6133                    final PackageInfo pi;
6134                    if (ps.pkg != null) {
6135                        pi = generatePackageInfo(ps, flags, userId);
6136                    } else {
6137                        pi = generatePackageInfo(ps, flags, userId);
6138                    }
6139                    if (pi != null) {
6140                        list.add(pi);
6141                    }
6142                }
6143            } else {
6144                list = new ArrayList<PackageInfo>(mPackages.size());
6145                for (PackageParser.Package p : mPackages.values()) {
6146                    final PackageInfo pi =
6147                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6148                    if (pi != null) {
6149                        list.add(pi);
6150                    }
6151                }
6152            }
6153
6154            return new ParceledListSlice<PackageInfo>(list);
6155        }
6156    }
6157
6158    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6159            String[] permissions, boolean[] tmp, int flags, int userId) {
6160        int numMatch = 0;
6161        final PermissionsState permissionsState = ps.getPermissionsState();
6162        for (int i=0; i<permissions.length; i++) {
6163            final String permission = permissions[i];
6164            if (permissionsState.hasPermission(permission, userId)) {
6165                tmp[i] = true;
6166                numMatch++;
6167            } else {
6168                tmp[i] = false;
6169            }
6170        }
6171        if (numMatch == 0) {
6172            return;
6173        }
6174        final PackageInfo pi;
6175        if (ps.pkg != null) {
6176            pi = generatePackageInfo(ps, flags, userId);
6177        } else {
6178            pi = generatePackageInfo(ps, flags, userId);
6179        }
6180        // The above might return null in cases of uninstalled apps or install-state
6181        // skew across users/profiles.
6182        if (pi != null) {
6183            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6184                if (numMatch == permissions.length) {
6185                    pi.requestedPermissions = permissions;
6186                } else {
6187                    pi.requestedPermissions = new String[numMatch];
6188                    numMatch = 0;
6189                    for (int i=0; i<permissions.length; i++) {
6190                        if (tmp[i]) {
6191                            pi.requestedPermissions[numMatch] = permissions[i];
6192                            numMatch++;
6193                        }
6194                    }
6195                }
6196            }
6197            list.add(pi);
6198        }
6199    }
6200
6201    @Override
6202    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6203            String[] permissions, int flags, int userId) {
6204        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6205        flags = updateFlagsForPackage(flags, userId, permissions);
6206        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6207
6208        // writer
6209        synchronized (mPackages) {
6210            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6211            boolean[] tmpBools = new boolean[permissions.length];
6212            if (listUninstalled) {
6213                for (PackageSetting ps : mSettings.mPackages.values()) {
6214                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6215                }
6216            } else {
6217                for (PackageParser.Package pkg : mPackages.values()) {
6218                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6219                    if (ps != null) {
6220                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6221                                userId);
6222                    }
6223                }
6224            }
6225
6226            return new ParceledListSlice<PackageInfo>(list);
6227        }
6228    }
6229
6230    @Override
6231    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6232        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6233        flags = updateFlagsForApplication(flags, userId, null);
6234        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6235
6236        // writer
6237        synchronized (mPackages) {
6238            ArrayList<ApplicationInfo> list;
6239            if (listUninstalled) {
6240                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6241                for (PackageSetting ps : mSettings.mPackages.values()) {
6242                    ApplicationInfo ai;
6243                    if (ps.pkg != null) {
6244                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6245                                ps.readUserState(userId), userId);
6246                    } else {
6247                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6248                    }
6249                    if (ai != null) {
6250                        list.add(ai);
6251                    }
6252                }
6253            } else {
6254                list = new ArrayList<ApplicationInfo>(mPackages.size());
6255                for (PackageParser.Package p : mPackages.values()) {
6256                    if (p.mExtras != null) {
6257                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6258                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6259                        if (ai != null) {
6260                            list.add(ai);
6261                        }
6262                    }
6263                }
6264            }
6265
6266            return new ParceledListSlice<ApplicationInfo>(list);
6267        }
6268    }
6269
6270    @Override
6271    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6272        if (DISABLE_EPHEMERAL_APPS) {
6273            return null;
6274        }
6275
6276        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6277                "getEphemeralApplications");
6278        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6279                true /* requireFullPermission */, false /* checkShell */,
6280                "getEphemeralApplications");
6281        synchronized (mPackages) {
6282            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6283                    .getEphemeralApplicationsLPw(userId);
6284            if (ephemeralApps != null) {
6285                return new ParceledListSlice<>(ephemeralApps);
6286            }
6287        }
6288        return null;
6289    }
6290
6291    @Override
6292    public boolean isEphemeralApplication(String packageName, int userId) {
6293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6294                true /* requireFullPermission */, false /* checkShell */,
6295                "isEphemeral");
6296        if (DISABLE_EPHEMERAL_APPS) {
6297            return false;
6298        }
6299
6300        if (!isCallerSameApp(packageName)) {
6301            return false;
6302        }
6303        synchronized (mPackages) {
6304            PackageParser.Package pkg = mPackages.get(packageName);
6305            if (pkg != null) {
6306                return pkg.applicationInfo.isEphemeralApp();
6307            }
6308        }
6309        return false;
6310    }
6311
6312    @Override
6313    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6314        if (DISABLE_EPHEMERAL_APPS) {
6315            return null;
6316        }
6317
6318        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6319                true /* requireFullPermission */, false /* checkShell */,
6320                "getCookie");
6321        if (!isCallerSameApp(packageName)) {
6322            return null;
6323        }
6324        synchronized (mPackages) {
6325            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6326                    packageName, userId);
6327        }
6328    }
6329
6330    @Override
6331    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6332        if (DISABLE_EPHEMERAL_APPS) {
6333            return true;
6334        }
6335
6336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6337                true /* requireFullPermission */, true /* checkShell */,
6338                "setCookie");
6339        if (!isCallerSameApp(packageName)) {
6340            return false;
6341        }
6342        synchronized (mPackages) {
6343            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6344                    packageName, cookie, userId);
6345        }
6346    }
6347
6348    @Override
6349    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6350        if (DISABLE_EPHEMERAL_APPS) {
6351            return null;
6352        }
6353
6354        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6355                "getEphemeralApplicationIcon");
6356        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6357                true /* requireFullPermission */, false /* checkShell */,
6358                "getEphemeralApplicationIcon");
6359        synchronized (mPackages) {
6360            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6361                    packageName, userId);
6362        }
6363    }
6364
6365    private boolean isCallerSameApp(String packageName) {
6366        PackageParser.Package pkg = mPackages.get(packageName);
6367        return pkg != null
6368                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6369    }
6370
6371    @Override
6372    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6373        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6374    }
6375
6376    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6377        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6378
6379        // reader
6380        synchronized (mPackages) {
6381            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6382            final int userId = UserHandle.getCallingUserId();
6383            while (i.hasNext()) {
6384                final PackageParser.Package p = i.next();
6385                if (p.applicationInfo == null) continue;
6386
6387                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6388                        && !p.applicationInfo.isDirectBootAware();
6389                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6390                        && p.applicationInfo.isDirectBootAware();
6391
6392                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6393                        && (!mSafeMode || isSystemApp(p))
6394                        && (matchesUnaware || matchesAware)) {
6395                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6396                    if (ps != null) {
6397                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6398                                ps.readUserState(userId), userId);
6399                        if (ai != null) {
6400                            finalList.add(ai);
6401                        }
6402                    }
6403                }
6404            }
6405        }
6406
6407        return finalList;
6408    }
6409
6410    @Override
6411    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6412        if (!sUserManager.exists(userId)) return null;
6413        flags = updateFlagsForComponent(flags, userId, name);
6414        // reader
6415        synchronized (mPackages) {
6416            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6417            PackageSetting ps = provider != null
6418                    ? mSettings.mPackages.get(provider.owner.packageName)
6419                    : null;
6420            return ps != null
6421                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6422                    ? PackageParser.generateProviderInfo(provider, flags,
6423                            ps.readUserState(userId), userId)
6424                    : null;
6425        }
6426    }
6427
6428    /**
6429     * @deprecated
6430     */
6431    @Deprecated
6432    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6433        // reader
6434        synchronized (mPackages) {
6435            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6436                    .entrySet().iterator();
6437            final int userId = UserHandle.getCallingUserId();
6438            while (i.hasNext()) {
6439                Map.Entry<String, PackageParser.Provider> entry = i.next();
6440                PackageParser.Provider p = entry.getValue();
6441                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6442
6443                if (ps != null && p.syncable
6444                        && (!mSafeMode || (p.info.applicationInfo.flags
6445                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6446                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6447                            ps.readUserState(userId), userId);
6448                    if (info != null) {
6449                        outNames.add(entry.getKey());
6450                        outInfo.add(info);
6451                    }
6452                }
6453            }
6454        }
6455    }
6456
6457    @Override
6458    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6459            int uid, int flags) {
6460        final int userId = processName != null ? UserHandle.getUserId(uid)
6461                : UserHandle.getCallingUserId();
6462        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6463        flags = updateFlagsForComponent(flags, userId, processName);
6464
6465        ArrayList<ProviderInfo> finalList = null;
6466        // reader
6467        synchronized (mPackages) {
6468            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6469            while (i.hasNext()) {
6470                final PackageParser.Provider p = i.next();
6471                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6472                if (ps != null && p.info.authority != null
6473                        && (processName == null
6474                                || (p.info.processName.equals(processName)
6475                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6476                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6477                    if (finalList == null) {
6478                        finalList = new ArrayList<ProviderInfo>(3);
6479                    }
6480                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6481                            ps.readUserState(userId), userId);
6482                    if (info != null) {
6483                        finalList.add(info);
6484                    }
6485                }
6486            }
6487        }
6488
6489        if (finalList != null) {
6490            Collections.sort(finalList, mProviderInitOrderSorter);
6491            return new ParceledListSlice<ProviderInfo>(finalList);
6492        }
6493
6494        return ParceledListSlice.emptyList();
6495    }
6496
6497    @Override
6498    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6499        // reader
6500        synchronized (mPackages) {
6501            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6502            return PackageParser.generateInstrumentationInfo(i, flags);
6503        }
6504    }
6505
6506    @Override
6507    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6508            String targetPackage, int flags) {
6509        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6510    }
6511
6512    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6513            int flags) {
6514        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6515
6516        // reader
6517        synchronized (mPackages) {
6518            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6519            while (i.hasNext()) {
6520                final PackageParser.Instrumentation p = i.next();
6521                if (targetPackage == null
6522                        || targetPackage.equals(p.info.targetPackage)) {
6523                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6524                            flags);
6525                    if (ii != null) {
6526                        finalList.add(ii);
6527                    }
6528                }
6529            }
6530        }
6531
6532        return finalList;
6533    }
6534
6535    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6536        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6537        if (overlays == null) {
6538            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6539            return;
6540        }
6541        for (PackageParser.Package opkg : overlays.values()) {
6542            // Not much to do if idmap fails: we already logged the error
6543            // and we certainly don't want to abort installation of pkg simply
6544            // because an overlay didn't fit properly. For these reasons,
6545            // ignore the return value of createIdmapForPackagePairLI.
6546            createIdmapForPackagePairLI(pkg, opkg);
6547        }
6548    }
6549
6550    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6551            PackageParser.Package opkg) {
6552        if (!opkg.mTrustedOverlay) {
6553            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6554                    opkg.baseCodePath + ": overlay not trusted");
6555            return false;
6556        }
6557        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6558        if (overlaySet == null) {
6559            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6560                    opkg.baseCodePath + " but target package has no known overlays");
6561            return false;
6562        }
6563        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6564        // TODO: generate idmap for split APKs
6565        try {
6566            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6567        } catch (InstallerException e) {
6568            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6569                    + opkg.baseCodePath);
6570            return false;
6571        }
6572        PackageParser.Package[] overlayArray =
6573            overlaySet.values().toArray(new PackageParser.Package[0]);
6574        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6575            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6576                return p1.mOverlayPriority - p2.mOverlayPriority;
6577            }
6578        };
6579        Arrays.sort(overlayArray, cmp);
6580
6581        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6582        int i = 0;
6583        for (PackageParser.Package p : overlayArray) {
6584            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6585        }
6586        return true;
6587    }
6588
6589    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6590        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6591        try {
6592            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6593        } finally {
6594            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6595        }
6596    }
6597
6598    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6599        final File[] files = dir.listFiles();
6600        if (ArrayUtils.isEmpty(files)) {
6601            Log.d(TAG, "No files in app dir " + dir);
6602            return;
6603        }
6604
6605        if (DEBUG_PACKAGE_SCANNING) {
6606            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6607                    + " flags=0x" + Integer.toHexString(parseFlags));
6608        }
6609
6610        for (File file : files) {
6611            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6612                    && !PackageInstallerService.isStageName(file.getName());
6613            if (!isPackage) {
6614                // Ignore entries which are not packages
6615                continue;
6616            }
6617            try {
6618                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6619                        scanFlags, currentTime, null);
6620            } catch (PackageManagerException e) {
6621                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6622
6623                // Delete invalid userdata apps
6624                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6625                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6626                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6627                    removeCodePathLI(file);
6628                }
6629            }
6630        }
6631    }
6632
6633    private static File getSettingsProblemFile() {
6634        File dataDir = Environment.getDataDirectory();
6635        File systemDir = new File(dataDir, "system");
6636        File fname = new File(systemDir, "uiderrors.txt");
6637        return fname;
6638    }
6639
6640    static void reportSettingsProblem(int priority, String msg) {
6641        logCriticalInfo(priority, msg);
6642    }
6643
6644    static void logCriticalInfo(int priority, String msg) {
6645        Slog.println(priority, TAG, msg);
6646        EventLogTags.writePmCriticalInfo(msg);
6647        try {
6648            File fname = getSettingsProblemFile();
6649            FileOutputStream out = new FileOutputStream(fname, true);
6650            PrintWriter pw = new FastPrintWriter(out);
6651            SimpleDateFormat formatter = new SimpleDateFormat();
6652            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6653            pw.println(dateString + ": " + msg);
6654            pw.close();
6655            FileUtils.setPermissions(
6656                    fname.toString(),
6657                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6658                    -1, -1);
6659        } catch (java.io.IOException e) {
6660        }
6661    }
6662
6663    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6664            final int policyFlags) throws PackageManagerException {
6665        if (ps != null
6666                && ps.codePath.equals(srcFile)
6667                && ps.timeStamp == srcFile.lastModified()
6668                && !isCompatSignatureUpdateNeeded(pkg)
6669                && !isRecoverSignatureUpdateNeeded(pkg)) {
6670            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6671            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6672            ArraySet<PublicKey> signingKs;
6673            synchronized (mPackages) {
6674                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6675            }
6676            if (ps.signatures.mSignatures != null
6677                    && ps.signatures.mSignatures.length != 0
6678                    && signingKs != null) {
6679                // Optimization: reuse the existing cached certificates
6680                // if the package appears to be unchanged.
6681                pkg.mSignatures = ps.signatures.mSignatures;
6682                pkg.mSigningKeys = signingKs;
6683                return;
6684            }
6685
6686            Slog.w(TAG, "PackageSetting for " + ps.name
6687                    + " is missing signatures.  Collecting certs again to recover them.");
6688        } else {
6689            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6690        }
6691
6692        try {
6693            PackageParser.collectCertificates(pkg, policyFlags);
6694        } catch (PackageParserException e) {
6695            throw PackageManagerException.from(e);
6696        }
6697    }
6698
6699    /**
6700     *  Traces a package scan.
6701     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6702     */
6703    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6704            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6705        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6706        try {
6707            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6708        } finally {
6709            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6710        }
6711    }
6712
6713    /**
6714     *  Scans a package and returns the newly parsed package.
6715     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6716     */
6717    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6718            long currentTime, UserHandle user) throws PackageManagerException {
6719        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6720        PackageParser pp = new PackageParser();
6721        pp.setSeparateProcesses(mSeparateProcesses);
6722        pp.setOnlyCoreApps(mOnlyCore);
6723        pp.setDisplayMetrics(mMetrics);
6724
6725        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6726            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6727        }
6728
6729        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6730        final PackageParser.Package pkg;
6731        try {
6732            pkg = pp.parsePackage(scanFile, parseFlags);
6733        } catch (PackageParserException e) {
6734            throw PackageManagerException.from(e);
6735        } finally {
6736            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6737        }
6738
6739        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6740    }
6741
6742    /**
6743     *  Scans a package and returns the newly parsed package.
6744     *  @throws PackageManagerException on a parse error.
6745     */
6746    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6747            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6748            throws PackageManagerException {
6749        // If the package has children and this is the first dive in the function
6750        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6751        // packages (parent and children) would be successfully scanned before the
6752        // actual scan since scanning mutates internal state and we want to atomically
6753        // install the package and its children.
6754        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6755            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6756                scanFlags |= SCAN_CHECK_ONLY;
6757            }
6758        } else {
6759            scanFlags &= ~SCAN_CHECK_ONLY;
6760        }
6761
6762        // Scan the parent
6763        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6764                scanFlags, currentTime, user);
6765
6766        // Scan the children
6767        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6768        for (int i = 0; i < childCount; i++) {
6769            PackageParser.Package childPackage = pkg.childPackages.get(i);
6770            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6771                    currentTime, user);
6772        }
6773
6774
6775        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6776            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6777        }
6778
6779        return scannedPkg;
6780    }
6781
6782    /**
6783     *  Scans a package and returns the newly parsed package.
6784     *  @throws PackageManagerException on a parse error.
6785     */
6786    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6787            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6788            throws PackageManagerException {
6789        PackageSetting ps = null;
6790        PackageSetting updatedPkg;
6791        // reader
6792        synchronized (mPackages) {
6793            // Look to see if we already know about this package.
6794            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6795            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6796                // This package has been renamed to its original name.  Let's
6797                // use that.
6798                ps = mSettings.peekPackageLPr(oldName);
6799            }
6800            // If there was no original package, see one for the real package name.
6801            if (ps == null) {
6802                ps = mSettings.peekPackageLPr(pkg.packageName);
6803            }
6804            // Check to see if this package could be hiding/updating a system
6805            // package.  Must look for it either under the original or real
6806            // package name depending on our state.
6807            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6808            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6809
6810            // If this is a package we don't know about on the system partition, we
6811            // may need to remove disabled child packages on the system partition
6812            // or may need to not add child packages if the parent apk is updated
6813            // on the data partition and no longer defines this child package.
6814            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6815                // If this is a parent package for an updated system app and this system
6816                // app got an OTA update which no longer defines some of the child packages
6817                // we have to prune them from the disabled system packages.
6818                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6819                if (disabledPs != null) {
6820                    final int scannedChildCount = (pkg.childPackages != null)
6821                            ? pkg.childPackages.size() : 0;
6822                    final int disabledChildCount = disabledPs.childPackageNames != null
6823                            ? disabledPs.childPackageNames.size() : 0;
6824                    for (int i = 0; i < disabledChildCount; i++) {
6825                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6826                        boolean disabledPackageAvailable = false;
6827                        for (int j = 0; j < scannedChildCount; j++) {
6828                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6829                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6830                                disabledPackageAvailable = true;
6831                                break;
6832                            }
6833                         }
6834                         if (!disabledPackageAvailable) {
6835                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6836                         }
6837                    }
6838                }
6839            }
6840        }
6841
6842        boolean updatedPkgBetter = false;
6843        // First check if this is a system package that may involve an update
6844        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6845            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6846            // it needs to drop FLAG_PRIVILEGED.
6847            if (locationIsPrivileged(scanFile)) {
6848                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6849            } else {
6850                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6851            }
6852
6853            if (ps != null && !ps.codePath.equals(scanFile)) {
6854                // The path has changed from what was last scanned...  check the
6855                // version of the new path against what we have stored to determine
6856                // what to do.
6857                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6858                if (pkg.mVersionCode <= ps.versionCode) {
6859                    // The system package has been updated and the code path does not match
6860                    // Ignore entry. Skip it.
6861                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6862                            + " ignored: updated version " + ps.versionCode
6863                            + " better than this " + pkg.mVersionCode);
6864                    if (!updatedPkg.codePath.equals(scanFile)) {
6865                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6866                                + ps.name + " changing from " + updatedPkg.codePathString
6867                                + " to " + scanFile);
6868                        updatedPkg.codePath = scanFile;
6869                        updatedPkg.codePathString = scanFile.toString();
6870                        updatedPkg.resourcePath = scanFile;
6871                        updatedPkg.resourcePathString = scanFile.toString();
6872                    }
6873                    updatedPkg.pkg = pkg;
6874                    updatedPkg.versionCode = pkg.mVersionCode;
6875
6876                    // Update the disabled system child packages to point to the package too.
6877                    final int childCount = updatedPkg.childPackageNames != null
6878                            ? updatedPkg.childPackageNames.size() : 0;
6879                    for (int i = 0; i < childCount; i++) {
6880                        String childPackageName = updatedPkg.childPackageNames.get(i);
6881                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6882                                childPackageName);
6883                        if (updatedChildPkg != null) {
6884                            updatedChildPkg.pkg = pkg;
6885                            updatedChildPkg.versionCode = pkg.mVersionCode;
6886                        }
6887                    }
6888
6889                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6890                            + scanFile + " ignored: updated version " + ps.versionCode
6891                            + " better than this " + pkg.mVersionCode);
6892                } else {
6893                    // The current app on the system partition is better than
6894                    // what we have updated to on the data partition; switch
6895                    // back to the system partition version.
6896                    // At this point, its safely assumed that package installation for
6897                    // apps in system partition will go through. If not there won't be a working
6898                    // version of the app
6899                    // writer
6900                    synchronized (mPackages) {
6901                        // Just remove the loaded entries from package lists.
6902                        mPackages.remove(ps.name);
6903                    }
6904
6905                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6906                            + " reverting from " + ps.codePathString
6907                            + ": new version " + pkg.mVersionCode
6908                            + " better than installed " + ps.versionCode);
6909
6910                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6911                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6912                    synchronized (mInstallLock) {
6913                        args.cleanUpResourcesLI();
6914                    }
6915                    synchronized (mPackages) {
6916                        mSettings.enableSystemPackageLPw(ps.name);
6917                    }
6918                    updatedPkgBetter = true;
6919                }
6920            }
6921        }
6922
6923        if (updatedPkg != null) {
6924            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6925            // initially
6926            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6927
6928            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6929            // flag set initially
6930            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6931                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6932            }
6933        }
6934
6935        // Verify certificates against what was last scanned
6936        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6937
6938        /*
6939         * A new system app appeared, but we already had a non-system one of the
6940         * same name installed earlier.
6941         */
6942        boolean shouldHideSystemApp = false;
6943        if (updatedPkg == null && ps != null
6944                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6945            /*
6946             * Check to make sure the signatures match first. If they don't,
6947             * wipe the installed application and its data.
6948             */
6949            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6950                    != PackageManager.SIGNATURE_MATCH) {
6951                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6952                        + " signatures don't match existing userdata copy; removing");
6953                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6954                        "scanPackageInternalLI")) {
6955                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6956                }
6957                ps = null;
6958            } else {
6959                /*
6960                 * If the newly-added system app is an older version than the
6961                 * already installed version, hide it. It will be scanned later
6962                 * and re-added like an update.
6963                 */
6964                if (pkg.mVersionCode <= ps.versionCode) {
6965                    shouldHideSystemApp = true;
6966                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6967                            + " but new version " + pkg.mVersionCode + " better than installed "
6968                            + ps.versionCode + "; hiding system");
6969                } else {
6970                    /*
6971                     * The newly found system app is a newer version that the
6972                     * one previously installed. Simply remove the
6973                     * already-installed application and replace it with our own
6974                     * while keeping the application data.
6975                     */
6976                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6977                            + " reverting from " + ps.codePathString + ": new version "
6978                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6979                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6980                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6981                    synchronized (mInstallLock) {
6982                        args.cleanUpResourcesLI();
6983                    }
6984                }
6985            }
6986        }
6987
6988        // The apk is forward locked (not public) if its code and resources
6989        // are kept in different files. (except for app in either system or
6990        // vendor path).
6991        // TODO grab this value from PackageSettings
6992        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6993            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6994                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6995            }
6996        }
6997
6998        // TODO: extend to support forward-locked splits
6999        String resourcePath = null;
7000        String baseResourcePath = null;
7001        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7002            if (ps != null && ps.resourcePathString != null) {
7003                resourcePath = ps.resourcePathString;
7004                baseResourcePath = ps.resourcePathString;
7005            } else {
7006                // Should not happen at all. Just log an error.
7007                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7008            }
7009        } else {
7010            resourcePath = pkg.codePath;
7011            baseResourcePath = pkg.baseCodePath;
7012        }
7013
7014        // Set application objects path explicitly.
7015        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7016        pkg.setApplicationInfoCodePath(pkg.codePath);
7017        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7018        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7019        pkg.setApplicationInfoResourcePath(resourcePath);
7020        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7021        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7022
7023        // Note that we invoke the following method only if we are about to unpack an application
7024        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7025                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7026
7027        /*
7028         * If the system app should be overridden by a previously installed
7029         * data, hide the system app now and let the /data/app scan pick it up
7030         * again.
7031         */
7032        if (shouldHideSystemApp) {
7033            synchronized (mPackages) {
7034                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7035            }
7036        }
7037
7038        return scannedPkg;
7039    }
7040
7041    private static String fixProcessName(String defProcessName,
7042            String processName, int uid) {
7043        if (processName == null) {
7044            return defProcessName;
7045        }
7046        return processName;
7047    }
7048
7049    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7050            throws PackageManagerException {
7051        if (pkgSetting.signatures.mSignatures != null) {
7052            // Already existing package. Make sure signatures match
7053            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7054                    == PackageManager.SIGNATURE_MATCH;
7055            if (!match) {
7056                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7057                        == PackageManager.SIGNATURE_MATCH;
7058            }
7059            if (!match) {
7060                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7061                        == PackageManager.SIGNATURE_MATCH;
7062            }
7063            if (!match) {
7064                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7065                        + pkg.packageName + " signatures do not match the "
7066                        + "previously installed version; ignoring!");
7067            }
7068        }
7069
7070        // Check for shared user signatures
7071        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7072            // Already existing package. Make sure signatures match
7073            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7074                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7075            if (!match) {
7076                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7077                        == PackageManager.SIGNATURE_MATCH;
7078            }
7079            if (!match) {
7080                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7081                        == PackageManager.SIGNATURE_MATCH;
7082            }
7083            if (!match) {
7084                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7085                        "Package " + pkg.packageName
7086                        + " has no signatures that match those in shared user "
7087                        + pkgSetting.sharedUser.name + "; ignoring!");
7088            }
7089        }
7090    }
7091
7092    /**
7093     * Enforces that only the system UID or root's UID can call a method exposed
7094     * via Binder.
7095     *
7096     * @param message used as message if SecurityException is thrown
7097     * @throws SecurityException if the caller is not system or root
7098     */
7099    private static final void enforceSystemOrRoot(String message) {
7100        final int uid = Binder.getCallingUid();
7101        if (uid != Process.SYSTEM_UID && uid != 0) {
7102            throw new SecurityException(message);
7103        }
7104    }
7105
7106    @Override
7107    public void performFstrimIfNeeded() {
7108        enforceSystemOrRoot("Only the system can request fstrim");
7109
7110        // Before everything else, see whether we need to fstrim.
7111        try {
7112            IMountService ms = PackageHelper.getMountService();
7113            if (ms != null) {
7114                final boolean isUpgrade = isUpgrade();
7115                boolean doTrim = isUpgrade;
7116                if (doTrim) {
7117                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7118                } else {
7119                    final long interval = android.provider.Settings.Global.getLong(
7120                            mContext.getContentResolver(),
7121                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7122                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7123                    if (interval > 0) {
7124                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7125                        if (timeSinceLast > interval) {
7126                            doTrim = true;
7127                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7128                                    + "; running immediately");
7129                        }
7130                    }
7131                }
7132                if (doTrim) {
7133                    if (!isFirstBoot()) {
7134                        try {
7135                            ActivityManagerNative.getDefault().showBootMessage(
7136                                    mContext.getResources().getString(
7137                                            R.string.android_upgrading_fstrim), true);
7138                        } catch (RemoteException e) {
7139                        }
7140                    }
7141                    ms.runMaintenance();
7142                }
7143            } else {
7144                Slog.e(TAG, "Mount service unavailable!");
7145            }
7146        } catch (RemoteException e) {
7147            // Can't happen; MountService is local
7148        }
7149    }
7150
7151    @Override
7152    public void updatePackagesIfNeeded() {
7153        enforceSystemOrRoot("Only the system can request package update");
7154
7155        // We need to re-extract after an OTA.
7156        boolean causeUpgrade = isUpgrade();
7157
7158        // First boot or factory reset.
7159        // Note: we also handle devices that are upgrading to N right now as if it is their
7160        //       first boot, as they do not have profile data.
7161        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7162
7163        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7164        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7165
7166        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7167            return;
7168        }
7169
7170        List<PackageParser.Package> pkgs;
7171        synchronized (mPackages) {
7172            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7173        }
7174
7175        int numberOfPackagesVisited = 0;
7176        int numberOfPackagesOptimized = 0;
7177        int numberOfPackagesSkipped = 0;
7178        int numberOfPackagesFailed = 0;
7179        final int numberOfPackagesToDexopt = pkgs.size();
7180        final long startTime = System.nanoTime();
7181
7182        for (PackageParser.Package pkg : pkgs) {
7183            numberOfPackagesVisited++;
7184
7185            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7186                if (DEBUG_DEXOPT) {
7187                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7188                }
7189                numberOfPackagesSkipped++;
7190                continue;
7191            }
7192
7193            if (DEBUG_DEXOPT) {
7194                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7195                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7196            }
7197
7198            if (mIsPreNUpgrade) {
7199                try {
7200                    ActivityManagerNative.getDefault().showBootMessage(
7201                            mContext.getResources().getString(R.string.android_upgrading_apk,
7202                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7203                } catch (RemoteException e) {
7204                }
7205            }
7206
7207            // checkProfiles is false to avoid merging profiles during boot which
7208            // might interfere with background compilation (b/28612421).
7209            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7210            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7211            // trade-off worth doing to save boot time work.
7212            int dexOptStatus = performDexOptTraced(pkg.packageName,
7213                    null /* instructionSet */,
7214                    false /* checkProfiles */,
7215                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
7216                    false /* force */);
7217            switch (dexOptStatus) {
7218                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7219                    numberOfPackagesOptimized++;
7220                    break;
7221                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7222                    numberOfPackagesSkipped++;
7223                    break;
7224                case PackageDexOptimizer.DEX_OPT_FAILED:
7225                    numberOfPackagesFailed++;
7226                    break;
7227                default:
7228                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7229                    break;
7230            }
7231        }
7232
7233        final int elapsedTimeSeconds =
7234                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7235        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized);
7236        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped);
7237        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed);
7238        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7239        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7240    }
7241
7242    @Override
7243    public void notifyPackageUse(String packageName, int reason) {
7244        synchronized (mPackages) {
7245            PackageParser.Package p = mPackages.get(packageName);
7246            if (p == null) {
7247                return;
7248            }
7249            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7250        }
7251    }
7252
7253    // TODO: this is not used nor needed. Delete it.
7254    @Override
7255    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7256        int dexOptStatus = performDexOptTraced(packageName, instructionSet,
7257                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7258        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7259    }
7260
7261    @Override
7262    public boolean performDexOpt(String packageName, String instructionSet,
7263            boolean checkProfiles, int compileReason, boolean force) {
7264        int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles,
7265                getCompilerFilterForReason(compileReason), force);
7266        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7267    }
7268
7269    @Override
7270    public boolean performDexOptMode(String packageName, String instructionSet,
7271            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7272        int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles,
7273                targetCompilerFilter, force);
7274        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7275    }
7276
7277    private int performDexOptTraced(String packageName, String instructionSet,
7278                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7279        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7280        try {
7281            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7282                    targetCompilerFilter, force);
7283        } finally {
7284            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7285        }
7286    }
7287
7288    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7289    // if the package can now be considered up to date for the given filter.
7290    private int performDexOptInternal(String packageName, String instructionSet,
7291                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7292        PackageParser.Package p;
7293        final String targetInstructionSet;
7294        synchronized (mPackages) {
7295            p = mPackages.get(packageName);
7296            if (p == null) {
7297                // Package could not be found. Report failure.
7298                return PackageDexOptimizer.DEX_OPT_FAILED;
7299            }
7300            mPackageUsage.write(false);
7301
7302            targetInstructionSet = instructionSet != null ? instructionSet :
7303                    getPrimaryInstructionSet(p.applicationInfo);
7304        }
7305        long callingId = Binder.clearCallingIdentity();
7306        try {
7307            synchronized (mInstallLock) {
7308                final String[] instructionSets = new String[] { targetInstructionSet };
7309                return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles,
7310                        targetCompilerFilter, force);
7311            }
7312        } finally {
7313            Binder.restoreCallingIdentity(callingId);
7314        }
7315    }
7316
7317    public ArraySet<String> getOptimizablePackages() {
7318        ArraySet<String> pkgs = new ArraySet<String>();
7319        synchronized (mPackages) {
7320            for (PackageParser.Package p : mPackages.values()) {
7321                if (PackageDexOptimizer.canOptimizePackage(p)) {
7322                    pkgs.add(p.packageName);
7323                }
7324            }
7325        }
7326        return pkgs;
7327    }
7328
7329    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7330            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7331            boolean force) {
7332        // Select the dex optimizer based on the force parameter.
7333        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7334        //       allocate an object here.
7335        PackageDexOptimizer pdo = force
7336                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7337                : mPackageDexOptimizer;
7338
7339        // Optimize all dependencies first. Note: we ignore the return value and march on
7340        // on errors.
7341        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7342        if (!deps.isEmpty()) {
7343            for (PackageParser.Package depPackage : deps) {
7344                // TODO: Analyze and investigate if we (should) profile libraries.
7345                // Currently this will do a full compilation of the library by default.
7346                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7347                        false /* checkProfiles */,
7348                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7349            }
7350        }
7351
7352        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7353                targetCompilerFilter);
7354    }
7355
7356    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7357        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7358            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7359            Set<String> collectedNames = new HashSet<>();
7360            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7361
7362            retValue.remove(p);
7363
7364            return retValue;
7365        } else {
7366            return Collections.emptyList();
7367        }
7368    }
7369
7370    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7371            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7372        if (!collectedNames.contains(p.packageName)) {
7373            collectedNames.add(p.packageName);
7374            collected.add(p);
7375
7376            if (p.usesLibraries != null) {
7377                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7378            }
7379            if (p.usesOptionalLibraries != null) {
7380                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7381                        collectedNames);
7382            }
7383        }
7384    }
7385
7386    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7387            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7388        for (String libName : libs) {
7389            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7390            if (libPkg != null) {
7391                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7392            }
7393        }
7394    }
7395
7396    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7397        synchronized (mPackages) {
7398            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7399            if (lib != null && lib.apk != null) {
7400                return mPackages.get(lib.apk);
7401            }
7402        }
7403        return null;
7404    }
7405
7406    public void shutdown() {
7407        mPackageUsage.write(true);
7408    }
7409
7410    @Override
7411    public void forceDexOpt(String packageName) {
7412        enforceSystemOrRoot("forceDexOpt");
7413
7414        PackageParser.Package pkg;
7415        synchronized (mPackages) {
7416            pkg = mPackages.get(packageName);
7417            if (pkg == null) {
7418                throw new IllegalArgumentException("Unknown package: " + packageName);
7419            }
7420        }
7421
7422        synchronized (mInstallLock) {
7423            final String[] instructionSets = new String[] {
7424                    getPrimaryInstructionSet(pkg.applicationInfo) };
7425
7426            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7427
7428            // Whoever is calling forceDexOpt wants a fully compiled package.
7429            // Don't use profiles since that may cause compilation to be skipped.
7430            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7431                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7432                    true /* force */);
7433
7434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7435            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7436                throw new IllegalStateException("Failed to dexopt: " + res);
7437            }
7438        }
7439    }
7440
7441    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7442        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7443            Slog.w(TAG, "Unable to update from " + oldPkg.name
7444                    + " to " + newPkg.packageName
7445                    + ": old package not in system partition");
7446            return false;
7447        } else if (mPackages.get(oldPkg.name) != null) {
7448            Slog.w(TAG, "Unable to update from " + oldPkg.name
7449                    + " to " + newPkg.packageName
7450                    + ": old package still exists");
7451            return false;
7452        }
7453        return true;
7454    }
7455
7456    void removeCodePathLI(File codePath) {
7457        if (codePath.isDirectory()) {
7458            try {
7459                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7460            } catch (InstallerException e) {
7461                Slog.w(TAG, "Failed to remove code path", e);
7462            }
7463        } else {
7464            codePath.delete();
7465        }
7466    }
7467
7468    private int[] resolveUserIds(int userId) {
7469        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7470    }
7471
7472    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7473        if (pkg == null) {
7474            Slog.wtf(TAG, "Package was null!", new Throwable());
7475            return;
7476        }
7477        clearAppDataLeafLIF(pkg, userId, flags);
7478        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7479        for (int i = 0; i < childCount; i++) {
7480            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7481        }
7482    }
7483
7484    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7485        final PackageSetting ps;
7486        synchronized (mPackages) {
7487            ps = mSettings.mPackages.get(pkg.packageName);
7488        }
7489        for (int realUserId : resolveUserIds(userId)) {
7490            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7491            try {
7492                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7493                        ceDataInode);
7494            } catch (InstallerException e) {
7495                Slog.w(TAG, String.valueOf(e));
7496            }
7497        }
7498    }
7499
7500    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7501        if (pkg == null) {
7502            Slog.wtf(TAG, "Package was null!", new Throwable());
7503            return;
7504        }
7505        destroyAppDataLeafLIF(pkg, userId, flags);
7506        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7507        for (int i = 0; i < childCount; i++) {
7508            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7509        }
7510    }
7511
7512    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7513        final PackageSetting ps;
7514        synchronized (mPackages) {
7515            ps = mSettings.mPackages.get(pkg.packageName);
7516        }
7517        for (int realUserId : resolveUserIds(userId)) {
7518            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7519            try {
7520                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7521                        ceDataInode);
7522            } catch (InstallerException e) {
7523                Slog.w(TAG, String.valueOf(e));
7524            }
7525        }
7526    }
7527
7528    private void destroyAppProfilesLIF(PackageParser.Package pkg) {
7529        if (pkg == null) {
7530            Slog.wtf(TAG, "Package was null!", new Throwable());
7531            return;
7532        }
7533        destroyAppProfilesLeafLIF(pkg);
7534        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7535        for (int i = 0; i < childCount; i++) {
7536            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7537        }
7538    }
7539
7540    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7541        try {
7542            mInstaller.destroyAppProfiles(pkg.packageName);
7543        } catch (InstallerException e) {
7544            Slog.w(TAG, String.valueOf(e));
7545        }
7546    }
7547
7548    private void clearAppProfilesLIF(PackageParser.Package pkg) {
7549        if (pkg == null) {
7550            Slog.wtf(TAG, "Package was null!", new Throwable());
7551            return;
7552        }
7553        clearAppProfilesLeafLIF(pkg);
7554        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7555        for (int i = 0; i < childCount; i++) {
7556            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7557        }
7558    }
7559
7560    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7561        try {
7562            mInstaller.clearAppProfiles(pkg.packageName);
7563        } catch (InstallerException e) {
7564            Slog.w(TAG, String.valueOf(e));
7565        }
7566    }
7567
7568    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7569            long lastUpdateTime) {
7570        // Set parent install/update time
7571        PackageSetting ps = (PackageSetting) pkg.mExtras;
7572        if (ps != null) {
7573            ps.firstInstallTime = firstInstallTime;
7574            ps.lastUpdateTime = lastUpdateTime;
7575        }
7576        // Set children install/update time
7577        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7578        for (int i = 0; i < childCount; i++) {
7579            PackageParser.Package childPkg = pkg.childPackages.get(i);
7580            ps = (PackageSetting) childPkg.mExtras;
7581            if (ps != null) {
7582                ps.firstInstallTime = firstInstallTime;
7583                ps.lastUpdateTime = lastUpdateTime;
7584            }
7585        }
7586    }
7587
7588    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7589            PackageParser.Package changingLib) {
7590        if (file.path != null) {
7591            usesLibraryFiles.add(file.path);
7592            return;
7593        }
7594        PackageParser.Package p = mPackages.get(file.apk);
7595        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7596            // If we are doing this while in the middle of updating a library apk,
7597            // then we need to make sure to use that new apk for determining the
7598            // dependencies here.  (We haven't yet finished committing the new apk
7599            // to the package manager state.)
7600            if (p == null || p.packageName.equals(changingLib.packageName)) {
7601                p = changingLib;
7602            }
7603        }
7604        if (p != null) {
7605            usesLibraryFiles.addAll(p.getAllCodePaths());
7606        }
7607    }
7608
7609    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7610            PackageParser.Package changingLib) throws PackageManagerException {
7611        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7612            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7613            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7614            for (int i=0; i<N; i++) {
7615                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7616                if (file == null) {
7617                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7618                            "Package " + pkg.packageName + " requires unavailable shared library "
7619                            + pkg.usesLibraries.get(i) + "; failing!");
7620                }
7621                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7622            }
7623            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7624            for (int i=0; i<N; i++) {
7625                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7626                if (file == null) {
7627                    Slog.w(TAG, "Package " + pkg.packageName
7628                            + " desires unavailable shared library "
7629                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7630                } else {
7631                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7632                }
7633            }
7634            N = usesLibraryFiles.size();
7635            if (N > 0) {
7636                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7637            } else {
7638                pkg.usesLibraryFiles = null;
7639            }
7640        }
7641    }
7642
7643    private static boolean hasString(List<String> list, List<String> which) {
7644        if (list == null) {
7645            return false;
7646        }
7647        for (int i=list.size()-1; i>=0; i--) {
7648            for (int j=which.size()-1; j>=0; j--) {
7649                if (which.get(j).equals(list.get(i))) {
7650                    return true;
7651                }
7652            }
7653        }
7654        return false;
7655    }
7656
7657    private void updateAllSharedLibrariesLPw() {
7658        for (PackageParser.Package pkg : mPackages.values()) {
7659            try {
7660                updateSharedLibrariesLPw(pkg, null);
7661            } catch (PackageManagerException e) {
7662                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7663            }
7664        }
7665    }
7666
7667    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7668            PackageParser.Package changingPkg) {
7669        ArrayList<PackageParser.Package> res = null;
7670        for (PackageParser.Package pkg : mPackages.values()) {
7671            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7672                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7673                if (res == null) {
7674                    res = new ArrayList<PackageParser.Package>();
7675                }
7676                res.add(pkg);
7677                try {
7678                    updateSharedLibrariesLPw(pkg, changingPkg);
7679                } catch (PackageManagerException e) {
7680                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7681                }
7682            }
7683        }
7684        return res;
7685    }
7686
7687    /**
7688     * Derive the value of the {@code cpuAbiOverride} based on the provided
7689     * value and an optional stored value from the package settings.
7690     */
7691    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7692        String cpuAbiOverride = null;
7693
7694        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7695            cpuAbiOverride = null;
7696        } else if (abiOverride != null) {
7697            cpuAbiOverride = abiOverride;
7698        } else if (settings != null) {
7699            cpuAbiOverride = settings.cpuAbiOverrideString;
7700        }
7701
7702        return cpuAbiOverride;
7703    }
7704
7705    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7706            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7707                    throws PackageManagerException {
7708        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7709        // If the package has children and this is the first dive in the function
7710        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7711        // whether all packages (parent and children) would be successfully scanned
7712        // before the actual scan since scanning mutates internal state and we want
7713        // to atomically install the package and its children.
7714        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7715            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7716                scanFlags |= SCAN_CHECK_ONLY;
7717            }
7718        } else {
7719            scanFlags &= ~SCAN_CHECK_ONLY;
7720        }
7721
7722        final PackageParser.Package scannedPkg;
7723        try {
7724            // Scan the parent
7725            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7726            // Scan the children
7727            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7728            for (int i = 0; i < childCount; i++) {
7729                PackageParser.Package childPkg = pkg.childPackages.get(i);
7730                scanPackageLI(childPkg, policyFlags,
7731                        scanFlags, currentTime, user);
7732            }
7733        } finally {
7734            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7735        }
7736
7737        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7738            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7739        }
7740
7741        return scannedPkg;
7742    }
7743
7744    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7745            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7746        boolean success = false;
7747        try {
7748            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7749                    currentTime, user);
7750            success = true;
7751            return res;
7752        } finally {
7753            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7754                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7755                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7756                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7757                destroyAppProfilesLIF(pkg);
7758            }
7759        }
7760    }
7761
7762    /**
7763     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7764     */
7765    private static boolean apkHasCode(String fileName) {
7766        StrictJarFile jarFile = null;
7767        try {
7768            jarFile = new StrictJarFile(fileName,
7769                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7770            return jarFile.findEntry("classes.dex") != null;
7771        } catch (IOException ignore) {
7772        } finally {
7773            try {
7774                jarFile.close();
7775            } catch (IOException ignore) {}
7776        }
7777        return false;
7778    }
7779
7780    /**
7781     * Enforces code policy for the package. This ensures that if an APK has
7782     * declared hasCode="true" in its manifest that the APK actually contains
7783     * code.
7784     *
7785     * @throws PackageManagerException If bytecode could not be found when it should exist
7786     */
7787    private static void enforceCodePolicy(PackageParser.Package pkg)
7788            throws PackageManagerException {
7789        final boolean shouldHaveCode =
7790                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7791        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7792            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7793                    "Package " + pkg.baseCodePath + " code is missing");
7794        }
7795
7796        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7797            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7798                final boolean splitShouldHaveCode =
7799                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7800                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7801                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7802                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7803                }
7804            }
7805        }
7806    }
7807
7808    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7809            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7810            throws PackageManagerException {
7811        final File scanFile = new File(pkg.codePath);
7812        if (pkg.applicationInfo.getCodePath() == null ||
7813                pkg.applicationInfo.getResourcePath() == null) {
7814            // Bail out. The resource and code paths haven't been set.
7815            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7816                    "Code and resource paths haven't been set correctly");
7817        }
7818
7819        // Apply policy
7820        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7821            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7822            if (pkg.applicationInfo.isDirectBootAware()) {
7823                // we're direct boot aware; set for all components
7824                for (PackageParser.Service s : pkg.services) {
7825                    s.info.encryptionAware = s.info.directBootAware = true;
7826                }
7827                for (PackageParser.Provider p : pkg.providers) {
7828                    p.info.encryptionAware = p.info.directBootAware = true;
7829                }
7830                for (PackageParser.Activity a : pkg.activities) {
7831                    a.info.encryptionAware = a.info.directBootAware = true;
7832                }
7833                for (PackageParser.Activity r : pkg.receivers) {
7834                    r.info.encryptionAware = r.info.directBootAware = true;
7835                }
7836            }
7837        } else {
7838            // Only allow system apps to be flagged as core apps.
7839            pkg.coreApp = false;
7840            // clear flags not applicable to regular apps
7841            pkg.applicationInfo.privateFlags &=
7842                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7843            pkg.applicationInfo.privateFlags &=
7844                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7845        }
7846        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7847
7848        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7849            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7850        }
7851
7852        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7853            enforceCodePolicy(pkg);
7854        }
7855
7856        if (mCustomResolverComponentName != null &&
7857                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7858            setUpCustomResolverActivity(pkg);
7859        }
7860
7861        if (pkg.packageName.equals("android")) {
7862            synchronized (mPackages) {
7863                if (mAndroidApplication != null) {
7864                    Slog.w(TAG, "*************************************************");
7865                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7866                    Slog.w(TAG, " file=" + scanFile);
7867                    Slog.w(TAG, "*************************************************");
7868                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7869                            "Core android package being redefined.  Skipping.");
7870                }
7871
7872                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7873                    // Set up information for our fall-back user intent resolution activity.
7874                    mPlatformPackage = pkg;
7875                    pkg.mVersionCode = mSdkVersion;
7876                    mAndroidApplication = pkg.applicationInfo;
7877
7878                    if (!mResolverReplaced) {
7879                        mResolveActivity.applicationInfo = mAndroidApplication;
7880                        mResolveActivity.name = ResolverActivity.class.getName();
7881                        mResolveActivity.packageName = mAndroidApplication.packageName;
7882                        mResolveActivity.processName = "system:ui";
7883                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7884                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7885                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7886                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7887                        mResolveActivity.exported = true;
7888                        mResolveActivity.enabled = true;
7889                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7890                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7891                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7892                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7893                                | ActivityInfo.CONFIG_ORIENTATION
7894                                | ActivityInfo.CONFIG_KEYBOARD
7895                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7896                        mResolveInfo.activityInfo = mResolveActivity;
7897                        mResolveInfo.priority = 0;
7898                        mResolveInfo.preferredOrder = 0;
7899                        mResolveInfo.match = 0;
7900                        mResolveComponentName = new ComponentName(
7901                                mAndroidApplication.packageName, mResolveActivity.name);
7902                    }
7903                }
7904            }
7905        }
7906
7907        if (DEBUG_PACKAGE_SCANNING) {
7908            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7909                Log.d(TAG, "Scanning package " + pkg.packageName);
7910        }
7911
7912        synchronized (mPackages) {
7913            if (mPackages.containsKey(pkg.packageName)
7914                    || mSharedLibraries.containsKey(pkg.packageName)) {
7915                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7916                        "Application package " + pkg.packageName
7917                                + " already installed.  Skipping duplicate.");
7918            }
7919
7920            // If we're only installing presumed-existing packages, require that the
7921            // scanned APK is both already known and at the path previously established
7922            // for it.  Previously unknown packages we pick up normally, but if we have an
7923            // a priori expectation about this package's install presence, enforce it.
7924            // With a singular exception for new system packages. When an OTA contains
7925            // a new system package, we allow the codepath to change from a system location
7926            // to the user-installed location. If we don't allow this change, any newer,
7927            // user-installed version of the application will be ignored.
7928            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7929                if (mExpectingBetter.containsKey(pkg.packageName)) {
7930                    logCriticalInfo(Log.WARN,
7931                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7932                } else {
7933                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7934                    if (known != null) {
7935                        if (DEBUG_PACKAGE_SCANNING) {
7936                            Log.d(TAG, "Examining " + pkg.codePath
7937                                    + " and requiring known paths " + known.codePathString
7938                                    + " & " + known.resourcePathString);
7939                        }
7940                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7941                                || !pkg.applicationInfo.getResourcePath().equals(
7942                                known.resourcePathString)) {
7943                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7944                                    "Application package " + pkg.packageName
7945                                            + " found at " + pkg.applicationInfo.getCodePath()
7946                                            + " but expected at " + known.codePathString
7947                                            + "; ignoring.");
7948                        }
7949                    }
7950                }
7951            }
7952        }
7953
7954        // Initialize package source and resource directories
7955        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7956        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7957
7958        SharedUserSetting suid = null;
7959        PackageSetting pkgSetting = null;
7960
7961        if (!isSystemApp(pkg)) {
7962            // Only system apps can use these features.
7963            pkg.mOriginalPackages = null;
7964            pkg.mRealPackage = null;
7965            pkg.mAdoptPermissions = null;
7966        }
7967
7968        // Getting the package setting may have a side-effect, so if we
7969        // are only checking if scan would succeed, stash a copy of the
7970        // old setting to restore at the end.
7971        PackageSetting nonMutatedPs = null;
7972
7973        // writer
7974        synchronized (mPackages) {
7975            if (pkg.mSharedUserId != null) {
7976                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7977                if (suid == null) {
7978                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7979                            "Creating application package " + pkg.packageName
7980                            + " for shared user failed");
7981                }
7982                if (DEBUG_PACKAGE_SCANNING) {
7983                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7984                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7985                                + "): packages=" + suid.packages);
7986                }
7987            }
7988
7989            // Check if we are renaming from an original package name.
7990            PackageSetting origPackage = null;
7991            String realName = null;
7992            if (pkg.mOriginalPackages != null) {
7993                // This package may need to be renamed to a previously
7994                // installed name.  Let's check on that...
7995                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7996                if (pkg.mOriginalPackages.contains(renamed)) {
7997                    // This package had originally been installed as the
7998                    // original name, and we have already taken care of
7999                    // transitioning to the new one.  Just update the new
8000                    // one to continue using the old name.
8001                    realName = pkg.mRealPackage;
8002                    if (!pkg.packageName.equals(renamed)) {
8003                        // Callers into this function may have already taken
8004                        // care of renaming the package; only do it here if
8005                        // it is not already done.
8006                        pkg.setPackageName(renamed);
8007                    }
8008
8009                } else {
8010                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8011                        if ((origPackage = mSettings.peekPackageLPr(
8012                                pkg.mOriginalPackages.get(i))) != null) {
8013                            // We do have the package already installed under its
8014                            // original name...  should we use it?
8015                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8016                                // New package is not compatible with original.
8017                                origPackage = null;
8018                                continue;
8019                            } else if (origPackage.sharedUser != null) {
8020                                // Make sure uid is compatible between packages.
8021                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8022                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8023                                            + " to " + pkg.packageName + ": old uid "
8024                                            + origPackage.sharedUser.name
8025                                            + " differs from " + pkg.mSharedUserId);
8026                                    origPackage = null;
8027                                    continue;
8028                                }
8029                                // TODO: Add case when shared user id is added [b/28144775]
8030                            } else {
8031                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8032                                        + pkg.packageName + " to old name " + origPackage.name);
8033                            }
8034                            break;
8035                        }
8036                    }
8037                }
8038            }
8039
8040            if (mTransferedPackages.contains(pkg.packageName)) {
8041                Slog.w(TAG, "Package " + pkg.packageName
8042                        + " was transferred to another, but its .apk remains");
8043            }
8044
8045            // See comments in nonMutatedPs declaration
8046            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8047                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8048                if (foundPs != null) {
8049                    nonMutatedPs = new PackageSetting(foundPs);
8050                }
8051            }
8052
8053            // Just create the setting, don't add it yet. For already existing packages
8054            // the PkgSetting exists already and doesn't have to be created.
8055            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8056                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8057                    pkg.applicationInfo.primaryCpuAbi,
8058                    pkg.applicationInfo.secondaryCpuAbi,
8059                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8060                    user, false);
8061            if (pkgSetting == null) {
8062                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8063                        "Creating application package " + pkg.packageName + " failed");
8064            }
8065
8066            if (pkgSetting.origPackage != null) {
8067                // If we are first transitioning from an original package,
8068                // fix up the new package's name now.  We need to do this after
8069                // looking up the package under its new name, so getPackageLP
8070                // can take care of fiddling things correctly.
8071                pkg.setPackageName(origPackage.name);
8072
8073                // File a report about this.
8074                String msg = "New package " + pkgSetting.realName
8075                        + " renamed to replace old package " + pkgSetting.name;
8076                reportSettingsProblem(Log.WARN, msg);
8077
8078                // Make a note of it.
8079                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8080                    mTransferedPackages.add(origPackage.name);
8081                }
8082
8083                // No longer need to retain this.
8084                pkgSetting.origPackage = null;
8085            }
8086
8087            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8088                // Make a note of it.
8089                mTransferedPackages.add(pkg.packageName);
8090            }
8091
8092            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8093                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8094            }
8095
8096            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8097                // Check all shared libraries and map to their actual file path.
8098                // We only do this here for apps not on a system dir, because those
8099                // are the only ones that can fail an install due to this.  We
8100                // will take care of the system apps by updating all of their
8101                // library paths after the scan is done.
8102                updateSharedLibrariesLPw(pkg, null);
8103            }
8104
8105            if (mFoundPolicyFile) {
8106                SELinuxMMAC.assignSeinfoValue(pkg);
8107            }
8108
8109            pkg.applicationInfo.uid = pkgSetting.appId;
8110            pkg.mExtras = pkgSetting;
8111            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8112                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8113                    // We just determined the app is signed correctly, so bring
8114                    // over the latest parsed certs.
8115                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8116                } else {
8117                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8118                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8119                                "Package " + pkg.packageName + " upgrade keys do not match the "
8120                                + "previously installed version");
8121                    } else {
8122                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8123                        String msg = "System package " + pkg.packageName
8124                            + " signature changed; retaining data.";
8125                        reportSettingsProblem(Log.WARN, msg);
8126                    }
8127                }
8128            } else {
8129                try {
8130                    verifySignaturesLP(pkgSetting, pkg);
8131                    // We just determined the app is signed correctly, so bring
8132                    // over the latest parsed certs.
8133                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8134                } catch (PackageManagerException e) {
8135                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8136                        throw e;
8137                    }
8138                    // The signature has changed, but this package is in the system
8139                    // image...  let's recover!
8140                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8141                    // However...  if this package is part of a shared user, but it
8142                    // doesn't match the signature of the shared user, let's fail.
8143                    // What this means is that you can't change the signatures
8144                    // associated with an overall shared user, which doesn't seem all
8145                    // that unreasonable.
8146                    if (pkgSetting.sharedUser != null) {
8147                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8148                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8149                            throw new PackageManagerException(
8150                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8151                                            "Signature mismatch for shared user: "
8152                                            + pkgSetting.sharedUser);
8153                        }
8154                    }
8155                    // File a report about this.
8156                    String msg = "System package " + pkg.packageName
8157                        + " signature changed; retaining data.";
8158                    reportSettingsProblem(Log.WARN, msg);
8159                }
8160            }
8161            // Verify that this new package doesn't have any content providers
8162            // that conflict with existing packages.  Only do this if the
8163            // package isn't already installed, since we don't want to break
8164            // things that are installed.
8165            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8166                final int N = pkg.providers.size();
8167                int i;
8168                for (i=0; i<N; i++) {
8169                    PackageParser.Provider p = pkg.providers.get(i);
8170                    if (p.info.authority != null) {
8171                        String names[] = p.info.authority.split(";");
8172                        for (int j = 0; j < names.length; j++) {
8173                            if (mProvidersByAuthority.containsKey(names[j])) {
8174                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8175                                final String otherPackageName =
8176                                        ((other != null && other.getComponentName() != null) ?
8177                                                other.getComponentName().getPackageName() : "?");
8178                                throw new PackageManagerException(
8179                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8180                                                "Can't install because provider name " + names[j]
8181                                                + " (in package " + pkg.applicationInfo.packageName
8182                                                + ") is already used by " + otherPackageName);
8183                            }
8184                        }
8185                    }
8186                }
8187            }
8188
8189            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8190                // This package wants to adopt ownership of permissions from
8191                // another package.
8192                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8193                    final String origName = pkg.mAdoptPermissions.get(i);
8194                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8195                    if (orig != null) {
8196                        if (verifyPackageUpdateLPr(orig, pkg)) {
8197                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8198                                    + pkg.packageName);
8199                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8200                        }
8201                    }
8202                }
8203            }
8204        }
8205
8206        final String pkgName = pkg.packageName;
8207
8208        final long scanFileTime = scanFile.lastModified();
8209        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8210        pkg.applicationInfo.processName = fixProcessName(
8211                pkg.applicationInfo.packageName,
8212                pkg.applicationInfo.processName,
8213                pkg.applicationInfo.uid);
8214
8215        if (pkg != mPlatformPackage) {
8216            // Get all of our default paths setup
8217            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8218        }
8219
8220        final String path = scanFile.getPath();
8221        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8222
8223        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8224            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8225
8226            // Some system apps still use directory structure for native libraries
8227            // in which case we might end up not detecting abi solely based on apk
8228            // structure. Try to detect abi based on directory structure.
8229            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8230                    pkg.applicationInfo.primaryCpuAbi == null) {
8231                setBundledAppAbisAndRoots(pkg, pkgSetting);
8232                setNativeLibraryPaths(pkg);
8233            }
8234
8235        } else {
8236            if ((scanFlags & SCAN_MOVE) != 0) {
8237                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8238                // but we already have this packages package info in the PackageSetting. We just
8239                // use that and derive the native library path based on the new codepath.
8240                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8241                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8242            }
8243
8244            // Set native library paths again. For moves, the path will be updated based on the
8245            // ABIs we've determined above. For non-moves, the path will be updated based on the
8246            // ABIs we determined during compilation, but the path will depend on the final
8247            // package path (after the rename away from the stage path).
8248            setNativeLibraryPaths(pkg);
8249        }
8250
8251        // This is a special case for the "system" package, where the ABI is
8252        // dictated by the zygote configuration (and init.rc). We should keep track
8253        // of this ABI so that we can deal with "normal" applications that run under
8254        // the same UID correctly.
8255        if (mPlatformPackage == pkg) {
8256            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8257                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8258        }
8259
8260        // If there's a mismatch between the abi-override in the package setting
8261        // and the abiOverride specified for the install. Warn about this because we
8262        // would've already compiled the app without taking the package setting into
8263        // account.
8264        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8265            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8266                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8267                        " for package " + pkg.packageName);
8268            }
8269        }
8270
8271        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8272        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8273        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8274
8275        // Copy the derived override back to the parsed package, so that we can
8276        // update the package settings accordingly.
8277        pkg.cpuAbiOverride = cpuAbiOverride;
8278
8279        if (DEBUG_ABI_SELECTION) {
8280            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8281                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8282                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8283        }
8284
8285        // Push the derived path down into PackageSettings so we know what to
8286        // clean up at uninstall time.
8287        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8288
8289        if (DEBUG_ABI_SELECTION) {
8290            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8291                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8292                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8293        }
8294
8295        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8296            // We don't do this here during boot because we can do it all
8297            // at once after scanning all existing packages.
8298            //
8299            // We also do this *before* we perform dexopt on this package, so that
8300            // we can avoid redundant dexopts, and also to make sure we've got the
8301            // code and package path correct.
8302            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8303                    pkg, true /* boot complete */);
8304        }
8305
8306        if (mFactoryTest && pkg.requestedPermissions.contains(
8307                android.Manifest.permission.FACTORY_TEST)) {
8308            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8309        }
8310
8311        ArrayList<PackageParser.Package> clientLibPkgs = null;
8312
8313        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8314            if (nonMutatedPs != null) {
8315                synchronized (mPackages) {
8316                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8317                }
8318            }
8319            return pkg;
8320        }
8321
8322        // Only privileged apps and updated privileged apps can add child packages.
8323        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8324            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8325                throw new PackageManagerException("Only privileged apps and updated "
8326                        + "privileged apps can add child packages. Ignoring package "
8327                        + pkg.packageName);
8328            }
8329            final int childCount = pkg.childPackages.size();
8330            for (int i = 0; i < childCount; i++) {
8331                PackageParser.Package childPkg = pkg.childPackages.get(i);
8332                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8333                        childPkg.packageName)) {
8334                    throw new PackageManagerException("Cannot override a child package of "
8335                            + "another disabled system app. Ignoring package " + pkg.packageName);
8336                }
8337            }
8338        }
8339
8340        // writer
8341        synchronized (mPackages) {
8342            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8343                // Only system apps can add new shared libraries.
8344                if (pkg.libraryNames != null) {
8345                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8346                        String name = pkg.libraryNames.get(i);
8347                        boolean allowed = false;
8348                        if (pkg.isUpdatedSystemApp()) {
8349                            // New library entries can only be added through the
8350                            // system image.  This is important to get rid of a lot
8351                            // of nasty edge cases: for example if we allowed a non-
8352                            // system update of the app to add a library, then uninstalling
8353                            // the update would make the library go away, and assumptions
8354                            // we made such as through app install filtering would now
8355                            // have allowed apps on the device which aren't compatible
8356                            // with it.  Better to just have the restriction here, be
8357                            // conservative, and create many fewer cases that can negatively
8358                            // impact the user experience.
8359                            final PackageSetting sysPs = mSettings
8360                                    .getDisabledSystemPkgLPr(pkg.packageName);
8361                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8362                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8363                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8364                                        allowed = true;
8365                                        break;
8366                                    }
8367                                }
8368                            }
8369                        } else {
8370                            allowed = true;
8371                        }
8372                        if (allowed) {
8373                            if (!mSharedLibraries.containsKey(name)) {
8374                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8375                            } else if (!name.equals(pkg.packageName)) {
8376                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8377                                        + name + " already exists; skipping");
8378                            }
8379                        } else {
8380                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8381                                    + name + " that is not declared on system image; skipping");
8382                        }
8383                    }
8384                    if ((scanFlags & SCAN_BOOTING) == 0) {
8385                        // If we are not booting, we need to update any applications
8386                        // that are clients of our shared library.  If we are booting,
8387                        // this will all be done once the scan is complete.
8388                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8389                    }
8390                }
8391            }
8392        }
8393
8394        if ((scanFlags & SCAN_BOOTING) != 0) {
8395            // No apps can run during boot scan, so they don't need to be frozen
8396        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8397            // Caller asked to not kill app, so it's probably not frozen
8398        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8399            // Caller asked us to ignore frozen check for some reason; they
8400            // probably didn't know the package name
8401        } else {
8402            // We're doing major surgery on this package, so it better be frozen
8403            // right now to keep it from launching
8404            checkPackageFrozen(pkgName);
8405        }
8406
8407        // Also need to kill any apps that are dependent on the library.
8408        if (clientLibPkgs != null) {
8409            for (int i=0; i<clientLibPkgs.size(); i++) {
8410                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8411                killApplication(clientPkg.applicationInfo.packageName,
8412                        clientPkg.applicationInfo.uid, "update lib");
8413            }
8414        }
8415
8416        // Make sure we're not adding any bogus keyset info
8417        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8418        ksms.assertScannedPackageValid(pkg);
8419
8420        // writer
8421        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8422
8423        boolean createIdmapFailed = false;
8424        synchronized (mPackages) {
8425            // We don't expect installation to fail beyond this point
8426
8427            // Add the new setting to mSettings
8428            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8429            // Add the new setting to mPackages
8430            mPackages.put(pkg.applicationInfo.packageName, pkg);
8431            // Make sure we don't accidentally delete its data.
8432            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8433            while (iter.hasNext()) {
8434                PackageCleanItem item = iter.next();
8435                if (pkgName.equals(item.packageName)) {
8436                    iter.remove();
8437                }
8438            }
8439
8440            // Take care of first install / last update times.
8441            if (currentTime != 0) {
8442                if (pkgSetting.firstInstallTime == 0) {
8443                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8444                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8445                    pkgSetting.lastUpdateTime = currentTime;
8446                }
8447            } else if (pkgSetting.firstInstallTime == 0) {
8448                // We need *something*.  Take time time stamp of the file.
8449                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8450            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8451                if (scanFileTime != pkgSetting.timeStamp) {
8452                    // A package on the system image has changed; consider this
8453                    // to be an update.
8454                    pkgSetting.lastUpdateTime = scanFileTime;
8455                }
8456            }
8457
8458            // Add the package's KeySets to the global KeySetManagerService
8459            ksms.addScannedPackageLPw(pkg);
8460
8461            int N = pkg.providers.size();
8462            StringBuilder r = null;
8463            int i;
8464            for (i=0; i<N; i++) {
8465                PackageParser.Provider p = pkg.providers.get(i);
8466                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8467                        p.info.processName, pkg.applicationInfo.uid);
8468                mProviders.addProvider(p);
8469                p.syncable = p.info.isSyncable;
8470                if (p.info.authority != null) {
8471                    String names[] = p.info.authority.split(";");
8472                    p.info.authority = null;
8473                    for (int j = 0; j < names.length; j++) {
8474                        if (j == 1 && p.syncable) {
8475                            // We only want the first authority for a provider to possibly be
8476                            // syncable, so if we already added this provider using a different
8477                            // authority clear the syncable flag. We copy the provider before
8478                            // changing it because the mProviders object contains a reference
8479                            // to a provider that we don't want to change.
8480                            // Only do this for the second authority since the resulting provider
8481                            // object can be the same for all future authorities for this provider.
8482                            p = new PackageParser.Provider(p);
8483                            p.syncable = false;
8484                        }
8485                        if (!mProvidersByAuthority.containsKey(names[j])) {
8486                            mProvidersByAuthority.put(names[j], p);
8487                            if (p.info.authority == null) {
8488                                p.info.authority = names[j];
8489                            } else {
8490                                p.info.authority = p.info.authority + ";" + names[j];
8491                            }
8492                            if (DEBUG_PACKAGE_SCANNING) {
8493                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8494                                    Log.d(TAG, "Registered content provider: " + names[j]
8495                                            + ", className = " + p.info.name + ", isSyncable = "
8496                                            + p.info.isSyncable);
8497                            }
8498                        } else {
8499                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8500                            Slog.w(TAG, "Skipping provider name " + names[j] +
8501                                    " (in package " + pkg.applicationInfo.packageName +
8502                                    "): name already used by "
8503                                    + ((other != null && other.getComponentName() != null)
8504                                            ? other.getComponentName().getPackageName() : "?"));
8505                        }
8506                    }
8507                }
8508                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8509                    if (r == null) {
8510                        r = new StringBuilder(256);
8511                    } else {
8512                        r.append(' ');
8513                    }
8514                    r.append(p.info.name);
8515                }
8516            }
8517            if (r != null) {
8518                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8519            }
8520
8521            N = pkg.services.size();
8522            r = null;
8523            for (i=0; i<N; i++) {
8524                PackageParser.Service s = pkg.services.get(i);
8525                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8526                        s.info.processName, pkg.applicationInfo.uid);
8527                mServices.addService(s);
8528                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8529                    if (r == null) {
8530                        r = new StringBuilder(256);
8531                    } else {
8532                        r.append(' ');
8533                    }
8534                    r.append(s.info.name);
8535                }
8536            }
8537            if (r != null) {
8538                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8539            }
8540
8541            N = pkg.receivers.size();
8542            r = null;
8543            for (i=0; i<N; i++) {
8544                PackageParser.Activity a = pkg.receivers.get(i);
8545                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8546                        a.info.processName, pkg.applicationInfo.uid);
8547                mReceivers.addActivity(a, "receiver");
8548                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8549                    if (r == null) {
8550                        r = new StringBuilder(256);
8551                    } else {
8552                        r.append(' ');
8553                    }
8554                    r.append(a.info.name);
8555                }
8556            }
8557            if (r != null) {
8558                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8559            }
8560
8561            N = pkg.activities.size();
8562            r = null;
8563            for (i=0; i<N; i++) {
8564                PackageParser.Activity a = pkg.activities.get(i);
8565                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8566                        a.info.processName, pkg.applicationInfo.uid);
8567                mActivities.addActivity(a, "activity");
8568                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8569                    if (r == null) {
8570                        r = new StringBuilder(256);
8571                    } else {
8572                        r.append(' ');
8573                    }
8574                    r.append(a.info.name);
8575                }
8576            }
8577            if (r != null) {
8578                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8579            }
8580
8581            N = pkg.permissionGroups.size();
8582            r = null;
8583            for (i=0; i<N; i++) {
8584                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8585                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8586                if (cur == null) {
8587                    mPermissionGroups.put(pg.info.name, pg);
8588                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8589                        if (r == null) {
8590                            r = new StringBuilder(256);
8591                        } else {
8592                            r.append(' ');
8593                        }
8594                        r.append(pg.info.name);
8595                    }
8596                } else {
8597                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8598                            + pg.info.packageName + " ignored: original from "
8599                            + cur.info.packageName);
8600                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8601                        if (r == null) {
8602                            r = new StringBuilder(256);
8603                        } else {
8604                            r.append(' ');
8605                        }
8606                        r.append("DUP:");
8607                        r.append(pg.info.name);
8608                    }
8609                }
8610            }
8611            if (r != null) {
8612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8613            }
8614
8615            N = pkg.permissions.size();
8616            r = null;
8617            for (i=0; i<N; i++) {
8618                PackageParser.Permission p = pkg.permissions.get(i);
8619
8620                // Assume by default that we did not install this permission into the system.
8621                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8622
8623                // Now that permission groups have a special meaning, we ignore permission
8624                // groups for legacy apps to prevent unexpected behavior. In particular,
8625                // permissions for one app being granted to someone just becase they happen
8626                // to be in a group defined by another app (before this had no implications).
8627                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8628                    p.group = mPermissionGroups.get(p.info.group);
8629                    // Warn for a permission in an unknown group.
8630                    if (p.info.group != null && p.group == null) {
8631                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8632                                + p.info.packageName + " in an unknown group " + p.info.group);
8633                    }
8634                }
8635
8636                ArrayMap<String, BasePermission> permissionMap =
8637                        p.tree ? mSettings.mPermissionTrees
8638                                : mSettings.mPermissions;
8639                BasePermission bp = permissionMap.get(p.info.name);
8640
8641                // Allow system apps to redefine non-system permissions
8642                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8643                    final boolean currentOwnerIsSystem = (bp.perm != null
8644                            && isSystemApp(bp.perm.owner));
8645                    if (isSystemApp(p.owner)) {
8646                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8647                            // It's a built-in permission and no owner, take ownership now
8648                            bp.packageSetting = pkgSetting;
8649                            bp.perm = p;
8650                            bp.uid = pkg.applicationInfo.uid;
8651                            bp.sourcePackage = p.info.packageName;
8652                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8653                        } else if (!currentOwnerIsSystem) {
8654                            String msg = "New decl " + p.owner + " of permission  "
8655                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8656                            reportSettingsProblem(Log.WARN, msg);
8657                            bp = null;
8658                        }
8659                    }
8660                }
8661
8662                if (bp == null) {
8663                    bp = new BasePermission(p.info.name, p.info.packageName,
8664                            BasePermission.TYPE_NORMAL);
8665                    permissionMap.put(p.info.name, bp);
8666                }
8667
8668                if (bp.perm == null) {
8669                    if (bp.sourcePackage == null
8670                            || bp.sourcePackage.equals(p.info.packageName)) {
8671                        BasePermission tree = findPermissionTreeLP(p.info.name);
8672                        if (tree == null
8673                                || tree.sourcePackage.equals(p.info.packageName)) {
8674                            bp.packageSetting = pkgSetting;
8675                            bp.perm = p;
8676                            bp.uid = pkg.applicationInfo.uid;
8677                            bp.sourcePackage = p.info.packageName;
8678                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8679                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8680                                if (r == null) {
8681                                    r = new StringBuilder(256);
8682                                } else {
8683                                    r.append(' ');
8684                                }
8685                                r.append(p.info.name);
8686                            }
8687                        } else {
8688                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8689                                    + p.info.packageName + " ignored: base tree "
8690                                    + tree.name + " is from package "
8691                                    + tree.sourcePackage);
8692                        }
8693                    } else {
8694                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8695                                + p.info.packageName + " ignored: original from "
8696                                + bp.sourcePackage);
8697                    }
8698                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8699                    if (r == null) {
8700                        r = new StringBuilder(256);
8701                    } else {
8702                        r.append(' ');
8703                    }
8704                    r.append("DUP:");
8705                    r.append(p.info.name);
8706                }
8707                if (bp.perm == p) {
8708                    bp.protectionLevel = p.info.protectionLevel;
8709                }
8710            }
8711
8712            if (r != null) {
8713                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8714            }
8715
8716            N = pkg.instrumentation.size();
8717            r = null;
8718            for (i=0; i<N; i++) {
8719                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8720                a.info.packageName = pkg.applicationInfo.packageName;
8721                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8722                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8723                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8724                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8725                a.info.dataDir = pkg.applicationInfo.dataDir;
8726                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8727                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8728
8729                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8730                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8731                mInstrumentation.put(a.getComponentName(), a);
8732                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8733                    if (r == null) {
8734                        r = new StringBuilder(256);
8735                    } else {
8736                        r.append(' ');
8737                    }
8738                    r.append(a.info.name);
8739                }
8740            }
8741            if (r != null) {
8742                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8743            }
8744
8745            if (pkg.protectedBroadcasts != null) {
8746                N = pkg.protectedBroadcasts.size();
8747                for (i=0; i<N; i++) {
8748                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8749                }
8750            }
8751
8752            pkgSetting.setTimeStamp(scanFileTime);
8753
8754            // Create idmap files for pairs of (packages, overlay packages).
8755            // Note: "android", ie framework-res.apk, is handled by native layers.
8756            if (pkg.mOverlayTarget != null) {
8757                // This is an overlay package.
8758                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8759                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8760                        mOverlays.put(pkg.mOverlayTarget,
8761                                new ArrayMap<String, PackageParser.Package>());
8762                    }
8763                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8764                    map.put(pkg.packageName, pkg);
8765                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8766                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8767                        createIdmapFailed = true;
8768                    }
8769                }
8770            } else if (mOverlays.containsKey(pkg.packageName) &&
8771                    !pkg.packageName.equals("android")) {
8772                // This is a regular package, with one or more known overlay packages.
8773                createIdmapsForPackageLI(pkg);
8774            }
8775        }
8776
8777        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8778
8779        if (createIdmapFailed) {
8780            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8781                    "scanPackageLI failed to createIdmap");
8782        }
8783        return pkg;
8784    }
8785
8786    /**
8787     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8788     * is derived purely on the basis of the contents of {@code scanFile} and
8789     * {@code cpuAbiOverride}.
8790     *
8791     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8792     */
8793    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8794                                 String cpuAbiOverride, boolean extractLibs)
8795            throws PackageManagerException {
8796        // TODO: We can probably be smarter about this stuff. For installed apps,
8797        // we can calculate this information at install time once and for all. For
8798        // system apps, we can probably assume that this information doesn't change
8799        // after the first boot scan. As things stand, we do lots of unnecessary work.
8800
8801        // Give ourselves some initial paths; we'll come back for another
8802        // pass once we've determined ABI below.
8803        setNativeLibraryPaths(pkg);
8804
8805        // We would never need to extract libs for forward-locked and external packages,
8806        // since the container service will do it for us. We shouldn't attempt to
8807        // extract libs from system app when it was not updated.
8808        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8809                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8810            extractLibs = false;
8811        }
8812
8813        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8814        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8815
8816        NativeLibraryHelper.Handle handle = null;
8817        try {
8818            handle = NativeLibraryHelper.Handle.create(pkg);
8819            // TODO(multiArch): This can be null for apps that didn't go through the
8820            // usual installation process. We can calculate it again, like we
8821            // do during install time.
8822            //
8823            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8824            // unnecessary.
8825            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8826
8827            // Null out the abis so that they can be recalculated.
8828            pkg.applicationInfo.primaryCpuAbi = null;
8829            pkg.applicationInfo.secondaryCpuAbi = null;
8830            if (isMultiArch(pkg.applicationInfo)) {
8831                // Warn if we've set an abiOverride for multi-lib packages..
8832                // By definition, we need to copy both 32 and 64 bit libraries for
8833                // such packages.
8834                if (pkg.cpuAbiOverride != null
8835                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8836                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8837                }
8838
8839                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8840                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8841                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8842                    if (extractLibs) {
8843                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8844                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8845                                useIsaSpecificSubdirs);
8846                    } else {
8847                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8848                    }
8849                }
8850
8851                maybeThrowExceptionForMultiArchCopy(
8852                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8853
8854                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8855                    if (extractLibs) {
8856                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8857                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8858                                useIsaSpecificSubdirs);
8859                    } else {
8860                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8861                    }
8862                }
8863
8864                maybeThrowExceptionForMultiArchCopy(
8865                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8866
8867                if (abi64 >= 0) {
8868                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8869                }
8870
8871                if (abi32 >= 0) {
8872                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8873                    if (abi64 >= 0) {
8874                        if (pkg.use32bitAbi) {
8875                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8876                            pkg.applicationInfo.primaryCpuAbi = abi;
8877                        } else {
8878                            pkg.applicationInfo.secondaryCpuAbi = abi;
8879                        }
8880                    } else {
8881                        pkg.applicationInfo.primaryCpuAbi = abi;
8882                    }
8883                }
8884
8885            } else {
8886                String[] abiList = (cpuAbiOverride != null) ?
8887                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8888
8889                // Enable gross and lame hacks for apps that are built with old
8890                // SDK tools. We must scan their APKs for renderscript bitcode and
8891                // not launch them if it's present. Don't bother checking on devices
8892                // that don't have 64 bit support.
8893                boolean needsRenderScriptOverride = false;
8894                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8895                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8896                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8897                    needsRenderScriptOverride = true;
8898                }
8899
8900                final int copyRet;
8901                if (extractLibs) {
8902                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8903                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8904                } else {
8905                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8906                }
8907
8908                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8909                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8910                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8911                }
8912
8913                if (copyRet >= 0) {
8914                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8915                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8916                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8917                } else if (needsRenderScriptOverride) {
8918                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8919                }
8920            }
8921        } catch (IOException ioe) {
8922            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8923        } finally {
8924            IoUtils.closeQuietly(handle);
8925        }
8926
8927        // Now that we've calculated the ABIs and determined if it's an internal app,
8928        // we will go ahead and populate the nativeLibraryPath.
8929        setNativeLibraryPaths(pkg);
8930    }
8931
8932    /**
8933     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8934     * i.e, so that all packages can be run inside a single process if required.
8935     *
8936     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8937     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8938     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8939     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8940     * updating a package that belongs to a shared user.
8941     *
8942     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8943     * adds unnecessary complexity.
8944     */
8945    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8946            PackageParser.Package scannedPackage, boolean bootComplete) {
8947        String requiredInstructionSet = null;
8948        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8949            requiredInstructionSet = VMRuntime.getInstructionSet(
8950                     scannedPackage.applicationInfo.primaryCpuAbi);
8951        }
8952
8953        PackageSetting requirer = null;
8954        for (PackageSetting ps : packagesForUser) {
8955            // If packagesForUser contains scannedPackage, we skip it. This will happen
8956            // when scannedPackage is an update of an existing package. Without this check,
8957            // we will never be able to change the ABI of any package belonging to a shared
8958            // user, even if it's compatible with other packages.
8959            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8960                if (ps.primaryCpuAbiString == null) {
8961                    continue;
8962                }
8963
8964                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8965                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8966                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8967                    // this but there's not much we can do.
8968                    String errorMessage = "Instruction set mismatch, "
8969                            + ((requirer == null) ? "[caller]" : requirer)
8970                            + " requires " + requiredInstructionSet + " whereas " + ps
8971                            + " requires " + instructionSet;
8972                    Slog.w(TAG, errorMessage);
8973                }
8974
8975                if (requiredInstructionSet == null) {
8976                    requiredInstructionSet = instructionSet;
8977                    requirer = ps;
8978                }
8979            }
8980        }
8981
8982        if (requiredInstructionSet != null) {
8983            String adjustedAbi;
8984            if (requirer != null) {
8985                // requirer != null implies that either scannedPackage was null or that scannedPackage
8986                // did not require an ABI, in which case we have to adjust scannedPackage to match
8987                // the ABI of the set (which is the same as requirer's ABI)
8988                adjustedAbi = requirer.primaryCpuAbiString;
8989                if (scannedPackage != null) {
8990                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8991                }
8992            } else {
8993                // requirer == null implies that we're updating all ABIs in the set to
8994                // match scannedPackage.
8995                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8996            }
8997
8998            for (PackageSetting ps : packagesForUser) {
8999                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9000                    if (ps.primaryCpuAbiString != null) {
9001                        continue;
9002                    }
9003
9004                    ps.primaryCpuAbiString = adjustedAbi;
9005                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9006                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9007                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9008                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9009                                + " (requirer="
9010                                + (requirer == null ? "null" : requirer.pkg.packageName)
9011                                + ", scannedPackage="
9012                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9013                                + ")");
9014                        try {
9015                            mInstaller.rmdex(ps.codePathString,
9016                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9017                        } catch (InstallerException ignored) {
9018                        }
9019                    }
9020                }
9021            }
9022        }
9023    }
9024
9025    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9026        synchronized (mPackages) {
9027            mResolverReplaced = true;
9028            // Set up information for custom user intent resolution activity.
9029            mResolveActivity.applicationInfo = pkg.applicationInfo;
9030            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9031            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9032            mResolveActivity.processName = pkg.applicationInfo.packageName;
9033            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9034            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9035                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9036            mResolveActivity.theme = 0;
9037            mResolveActivity.exported = true;
9038            mResolveActivity.enabled = true;
9039            mResolveInfo.activityInfo = mResolveActivity;
9040            mResolveInfo.priority = 0;
9041            mResolveInfo.preferredOrder = 0;
9042            mResolveInfo.match = 0;
9043            mResolveComponentName = mCustomResolverComponentName;
9044            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9045                    mResolveComponentName);
9046        }
9047    }
9048
9049    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9050        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9051
9052        // Set up information for ephemeral installer activity
9053        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9054        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9055        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9056        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9057        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9058        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9059                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9060        mEphemeralInstallerActivity.theme = 0;
9061        mEphemeralInstallerActivity.exported = true;
9062        mEphemeralInstallerActivity.enabled = true;
9063        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9064        mEphemeralInstallerInfo.priority = 0;
9065        mEphemeralInstallerInfo.preferredOrder = 0;
9066        mEphemeralInstallerInfo.match = 0;
9067
9068        if (DEBUG_EPHEMERAL) {
9069            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9070        }
9071    }
9072
9073    private static String calculateBundledApkRoot(final String codePathString) {
9074        final File codePath = new File(codePathString);
9075        final File codeRoot;
9076        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9077            codeRoot = Environment.getRootDirectory();
9078        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9079            codeRoot = Environment.getOemDirectory();
9080        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9081            codeRoot = Environment.getVendorDirectory();
9082        } else {
9083            // Unrecognized code path; take its top real segment as the apk root:
9084            // e.g. /something/app/blah.apk => /something
9085            try {
9086                File f = codePath.getCanonicalFile();
9087                File parent = f.getParentFile();    // non-null because codePath is a file
9088                File tmp;
9089                while ((tmp = parent.getParentFile()) != null) {
9090                    f = parent;
9091                    parent = tmp;
9092                }
9093                codeRoot = f;
9094                Slog.w(TAG, "Unrecognized code path "
9095                        + codePath + " - using " + codeRoot);
9096            } catch (IOException e) {
9097                // Can't canonicalize the code path -- shenanigans?
9098                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9099                return Environment.getRootDirectory().getPath();
9100            }
9101        }
9102        return codeRoot.getPath();
9103    }
9104
9105    /**
9106     * Derive and set the location of native libraries for the given package,
9107     * which varies depending on where and how the package was installed.
9108     */
9109    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9110        final ApplicationInfo info = pkg.applicationInfo;
9111        final String codePath = pkg.codePath;
9112        final File codeFile = new File(codePath);
9113        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9114        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9115
9116        info.nativeLibraryRootDir = null;
9117        info.nativeLibraryRootRequiresIsa = false;
9118        info.nativeLibraryDir = null;
9119        info.secondaryNativeLibraryDir = null;
9120
9121        if (isApkFile(codeFile)) {
9122            // Monolithic install
9123            if (bundledApp) {
9124                // If "/system/lib64/apkname" exists, assume that is the per-package
9125                // native library directory to use; otherwise use "/system/lib/apkname".
9126                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9127                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9128                        getPrimaryInstructionSet(info));
9129
9130                // This is a bundled system app so choose the path based on the ABI.
9131                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9132                // is just the default path.
9133                final String apkName = deriveCodePathName(codePath);
9134                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9135                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9136                        apkName).getAbsolutePath();
9137
9138                if (info.secondaryCpuAbi != null) {
9139                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9140                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9141                            secondaryLibDir, apkName).getAbsolutePath();
9142                }
9143            } else if (asecApp) {
9144                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9145                        .getAbsolutePath();
9146            } else {
9147                final String apkName = deriveCodePathName(codePath);
9148                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9149                        .getAbsolutePath();
9150            }
9151
9152            info.nativeLibraryRootRequiresIsa = false;
9153            info.nativeLibraryDir = info.nativeLibraryRootDir;
9154        } else {
9155            // Cluster install
9156            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9157            info.nativeLibraryRootRequiresIsa = true;
9158
9159            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9160                    getPrimaryInstructionSet(info)).getAbsolutePath();
9161
9162            if (info.secondaryCpuAbi != null) {
9163                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9164                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9165            }
9166        }
9167    }
9168
9169    /**
9170     * Calculate the abis and roots for a bundled app. These can uniquely
9171     * be determined from the contents of the system partition, i.e whether
9172     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9173     * of this information, and instead assume that the system was built
9174     * sensibly.
9175     */
9176    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9177                                           PackageSetting pkgSetting) {
9178        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9179
9180        // If "/system/lib64/apkname" exists, assume that is the per-package
9181        // native library directory to use; otherwise use "/system/lib/apkname".
9182        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9183        setBundledAppAbi(pkg, apkRoot, apkName);
9184        // pkgSetting might be null during rescan following uninstall of updates
9185        // to a bundled app, so accommodate that possibility.  The settings in
9186        // that case will be established later from the parsed package.
9187        //
9188        // If the settings aren't null, sync them up with what we've just derived.
9189        // note that apkRoot isn't stored in the package settings.
9190        if (pkgSetting != null) {
9191            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9192            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9193        }
9194    }
9195
9196    /**
9197     * Deduces the ABI of a bundled app and sets the relevant fields on the
9198     * parsed pkg object.
9199     *
9200     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9201     *        under which system libraries are installed.
9202     * @param apkName the name of the installed package.
9203     */
9204    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9205        final File codeFile = new File(pkg.codePath);
9206
9207        final boolean has64BitLibs;
9208        final boolean has32BitLibs;
9209        if (isApkFile(codeFile)) {
9210            // Monolithic install
9211            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9212            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9213        } else {
9214            // Cluster install
9215            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9216            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9217                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9218                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9219                has64BitLibs = (new File(rootDir, isa)).exists();
9220            } else {
9221                has64BitLibs = false;
9222            }
9223            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9224                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9225                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9226                has32BitLibs = (new File(rootDir, isa)).exists();
9227            } else {
9228                has32BitLibs = false;
9229            }
9230        }
9231
9232        if (has64BitLibs && !has32BitLibs) {
9233            // The package has 64 bit libs, but not 32 bit libs. Its primary
9234            // ABI should be 64 bit. We can safely assume here that the bundled
9235            // native libraries correspond to the most preferred ABI in the list.
9236
9237            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9238            pkg.applicationInfo.secondaryCpuAbi = null;
9239        } else if (has32BitLibs && !has64BitLibs) {
9240            // The package has 32 bit libs but not 64 bit libs. Its primary
9241            // ABI should be 32 bit.
9242
9243            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9244            pkg.applicationInfo.secondaryCpuAbi = null;
9245        } else if (has32BitLibs && has64BitLibs) {
9246            // The application has both 64 and 32 bit bundled libraries. We check
9247            // here that the app declares multiArch support, and warn if it doesn't.
9248            //
9249            // We will be lenient here and record both ABIs. The primary will be the
9250            // ABI that's higher on the list, i.e, a device that's configured to prefer
9251            // 64 bit apps will see a 64 bit primary ABI,
9252
9253            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9254                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9255            }
9256
9257            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9258                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9259                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9260            } else {
9261                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9262                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9263            }
9264        } else {
9265            pkg.applicationInfo.primaryCpuAbi = null;
9266            pkg.applicationInfo.secondaryCpuAbi = null;
9267        }
9268    }
9269
9270    private void killApplication(String pkgName, int appId, String reason) {
9271        // Request the ActivityManager to kill the process(only for existing packages)
9272        // so that we do not end up in a confused state while the user is still using the older
9273        // version of the application while the new one gets installed.
9274        final long token = Binder.clearCallingIdentity();
9275        try {
9276            IActivityManager am = ActivityManagerNative.getDefault();
9277            if (am != null) {
9278                try {
9279                    am.killApplicationWithAppId(pkgName, appId, reason);
9280                } catch (RemoteException e) {
9281                }
9282            }
9283        } finally {
9284            Binder.restoreCallingIdentity(token);
9285        }
9286    }
9287
9288    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9289        // Remove the parent package setting
9290        PackageSetting ps = (PackageSetting) pkg.mExtras;
9291        if (ps != null) {
9292            removePackageLI(ps, chatty);
9293        }
9294        // Remove the child package setting
9295        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9296        for (int i = 0; i < childCount; i++) {
9297            PackageParser.Package childPkg = pkg.childPackages.get(i);
9298            ps = (PackageSetting) childPkg.mExtras;
9299            if (ps != null) {
9300                removePackageLI(ps, chatty);
9301            }
9302        }
9303    }
9304
9305    void removePackageLI(PackageSetting ps, boolean chatty) {
9306        if (DEBUG_INSTALL) {
9307            if (chatty)
9308                Log.d(TAG, "Removing package " + ps.name);
9309        }
9310
9311        // writer
9312        synchronized (mPackages) {
9313            mPackages.remove(ps.name);
9314            final PackageParser.Package pkg = ps.pkg;
9315            if (pkg != null) {
9316                cleanPackageDataStructuresLILPw(pkg, chatty);
9317            }
9318        }
9319    }
9320
9321    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9322        if (DEBUG_INSTALL) {
9323            if (chatty)
9324                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9325        }
9326
9327        // writer
9328        synchronized (mPackages) {
9329            // Remove the parent package
9330            mPackages.remove(pkg.applicationInfo.packageName);
9331            cleanPackageDataStructuresLILPw(pkg, chatty);
9332
9333            // Remove the child packages
9334            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9335            for (int i = 0; i < childCount; i++) {
9336                PackageParser.Package childPkg = pkg.childPackages.get(i);
9337                mPackages.remove(childPkg.applicationInfo.packageName);
9338                cleanPackageDataStructuresLILPw(childPkg, chatty);
9339            }
9340        }
9341    }
9342
9343    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9344        int N = pkg.providers.size();
9345        StringBuilder r = null;
9346        int i;
9347        for (i=0; i<N; i++) {
9348            PackageParser.Provider p = pkg.providers.get(i);
9349            mProviders.removeProvider(p);
9350            if (p.info.authority == null) {
9351
9352                /* There was another ContentProvider with this authority when
9353                 * this app was installed so this authority is null,
9354                 * Ignore it as we don't have to unregister the provider.
9355                 */
9356                continue;
9357            }
9358            String names[] = p.info.authority.split(";");
9359            for (int j = 0; j < names.length; j++) {
9360                if (mProvidersByAuthority.get(names[j]) == p) {
9361                    mProvidersByAuthority.remove(names[j]);
9362                    if (DEBUG_REMOVE) {
9363                        if (chatty)
9364                            Log.d(TAG, "Unregistered content provider: " + names[j]
9365                                    + ", className = " + p.info.name + ", isSyncable = "
9366                                    + p.info.isSyncable);
9367                    }
9368                }
9369            }
9370            if (DEBUG_REMOVE && chatty) {
9371                if (r == null) {
9372                    r = new StringBuilder(256);
9373                } else {
9374                    r.append(' ');
9375                }
9376                r.append(p.info.name);
9377            }
9378        }
9379        if (r != null) {
9380            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9381        }
9382
9383        N = pkg.services.size();
9384        r = null;
9385        for (i=0; i<N; i++) {
9386            PackageParser.Service s = pkg.services.get(i);
9387            mServices.removeService(s);
9388            if (chatty) {
9389                if (r == null) {
9390                    r = new StringBuilder(256);
9391                } else {
9392                    r.append(' ');
9393                }
9394                r.append(s.info.name);
9395            }
9396        }
9397        if (r != null) {
9398            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9399        }
9400
9401        N = pkg.receivers.size();
9402        r = null;
9403        for (i=0; i<N; i++) {
9404            PackageParser.Activity a = pkg.receivers.get(i);
9405            mReceivers.removeActivity(a, "receiver");
9406            if (DEBUG_REMOVE && chatty) {
9407                if (r == null) {
9408                    r = new StringBuilder(256);
9409                } else {
9410                    r.append(' ');
9411                }
9412                r.append(a.info.name);
9413            }
9414        }
9415        if (r != null) {
9416            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9417        }
9418
9419        N = pkg.activities.size();
9420        r = null;
9421        for (i=0; i<N; i++) {
9422            PackageParser.Activity a = pkg.activities.get(i);
9423            mActivities.removeActivity(a, "activity");
9424            if (DEBUG_REMOVE && chatty) {
9425                if (r == null) {
9426                    r = new StringBuilder(256);
9427                } else {
9428                    r.append(' ');
9429                }
9430                r.append(a.info.name);
9431            }
9432        }
9433        if (r != null) {
9434            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9435        }
9436
9437        N = pkg.permissions.size();
9438        r = null;
9439        for (i=0; i<N; i++) {
9440            PackageParser.Permission p = pkg.permissions.get(i);
9441            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9442            if (bp == null) {
9443                bp = mSettings.mPermissionTrees.get(p.info.name);
9444            }
9445            if (bp != null && bp.perm == p) {
9446                bp.perm = null;
9447                if (DEBUG_REMOVE && chatty) {
9448                    if (r == null) {
9449                        r = new StringBuilder(256);
9450                    } else {
9451                        r.append(' ');
9452                    }
9453                    r.append(p.info.name);
9454                }
9455            }
9456            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9457                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9458                if (appOpPkgs != null) {
9459                    appOpPkgs.remove(pkg.packageName);
9460                }
9461            }
9462        }
9463        if (r != null) {
9464            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9465        }
9466
9467        N = pkg.requestedPermissions.size();
9468        r = null;
9469        for (i=0; i<N; i++) {
9470            String perm = pkg.requestedPermissions.get(i);
9471            BasePermission bp = mSettings.mPermissions.get(perm);
9472            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9473                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9474                if (appOpPkgs != null) {
9475                    appOpPkgs.remove(pkg.packageName);
9476                    if (appOpPkgs.isEmpty()) {
9477                        mAppOpPermissionPackages.remove(perm);
9478                    }
9479                }
9480            }
9481        }
9482        if (r != null) {
9483            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9484        }
9485
9486        N = pkg.instrumentation.size();
9487        r = null;
9488        for (i=0; i<N; i++) {
9489            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9490            mInstrumentation.remove(a.getComponentName());
9491            if (DEBUG_REMOVE && chatty) {
9492                if (r == null) {
9493                    r = new StringBuilder(256);
9494                } else {
9495                    r.append(' ');
9496                }
9497                r.append(a.info.name);
9498            }
9499        }
9500        if (r != null) {
9501            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9502        }
9503
9504        r = null;
9505        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9506            // Only system apps can hold shared libraries.
9507            if (pkg.libraryNames != null) {
9508                for (i=0; i<pkg.libraryNames.size(); i++) {
9509                    String name = pkg.libraryNames.get(i);
9510                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9511                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9512                        mSharedLibraries.remove(name);
9513                        if (DEBUG_REMOVE && chatty) {
9514                            if (r == null) {
9515                                r = new StringBuilder(256);
9516                            } else {
9517                                r.append(' ');
9518                            }
9519                            r.append(name);
9520                        }
9521                    }
9522                }
9523            }
9524        }
9525        if (r != null) {
9526            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9527        }
9528    }
9529
9530    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9531        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9532            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9533                return true;
9534            }
9535        }
9536        return false;
9537    }
9538
9539    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9540    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9541    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9542
9543    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9544        // Update the parent permissions
9545        updatePermissionsLPw(pkg.packageName, pkg, flags);
9546        // Update the child permissions
9547        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9548        for (int i = 0; i < childCount; i++) {
9549            PackageParser.Package childPkg = pkg.childPackages.get(i);
9550            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9551        }
9552    }
9553
9554    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9555            int flags) {
9556        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9557        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9558    }
9559
9560    private void updatePermissionsLPw(String changingPkg,
9561            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9562        // Make sure there are no dangling permission trees.
9563        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9564        while (it.hasNext()) {
9565            final BasePermission bp = it.next();
9566            if (bp.packageSetting == null) {
9567                // We may not yet have parsed the package, so just see if
9568                // we still know about its settings.
9569                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9570            }
9571            if (bp.packageSetting == null) {
9572                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9573                        + " from package " + bp.sourcePackage);
9574                it.remove();
9575            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9576                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9577                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9578                            + " from package " + bp.sourcePackage);
9579                    flags |= UPDATE_PERMISSIONS_ALL;
9580                    it.remove();
9581                }
9582            }
9583        }
9584
9585        // Make sure all dynamic permissions have been assigned to a package,
9586        // and make sure there are no dangling permissions.
9587        it = mSettings.mPermissions.values().iterator();
9588        while (it.hasNext()) {
9589            final BasePermission bp = it.next();
9590            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9591                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9592                        + bp.name + " pkg=" + bp.sourcePackage
9593                        + " info=" + bp.pendingInfo);
9594                if (bp.packageSetting == null && bp.pendingInfo != null) {
9595                    final BasePermission tree = findPermissionTreeLP(bp.name);
9596                    if (tree != null && tree.perm != null) {
9597                        bp.packageSetting = tree.packageSetting;
9598                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9599                                new PermissionInfo(bp.pendingInfo));
9600                        bp.perm.info.packageName = tree.perm.info.packageName;
9601                        bp.perm.info.name = bp.name;
9602                        bp.uid = tree.uid;
9603                    }
9604                }
9605            }
9606            if (bp.packageSetting == null) {
9607                // We may not yet have parsed the package, so just see if
9608                // we still know about its settings.
9609                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9610            }
9611            if (bp.packageSetting == null) {
9612                Slog.w(TAG, "Removing dangling permission: " + bp.name
9613                        + " from package " + bp.sourcePackage);
9614                it.remove();
9615            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9616                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9617                    Slog.i(TAG, "Removing old permission: " + bp.name
9618                            + " from package " + bp.sourcePackage);
9619                    flags |= UPDATE_PERMISSIONS_ALL;
9620                    it.remove();
9621                }
9622            }
9623        }
9624
9625        // Now update the permissions for all packages, in particular
9626        // replace the granted permissions of the system packages.
9627        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9628            for (PackageParser.Package pkg : mPackages.values()) {
9629                if (pkg != pkgInfo) {
9630                    // Only replace for packages on requested volume
9631                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9632                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9633                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9634                    grantPermissionsLPw(pkg, replace, changingPkg);
9635                }
9636            }
9637        }
9638
9639        if (pkgInfo != null) {
9640            // Only replace for packages on requested volume
9641            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9642            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9643                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9644            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9645        }
9646    }
9647
9648    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9649            String packageOfInterest) {
9650        // IMPORTANT: There are two types of permissions: install and runtime.
9651        // Install time permissions are granted when the app is installed to
9652        // all device users and users added in the future. Runtime permissions
9653        // are granted at runtime explicitly to specific users. Normal and signature
9654        // protected permissions are install time permissions. Dangerous permissions
9655        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9656        // otherwise they are runtime permissions. This function does not manage
9657        // runtime permissions except for the case an app targeting Lollipop MR1
9658        // being upgraded to target a newer SDK, in which case dangerous permissions
9659        // are transformed from install time to runtime ones.
9660
9661        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9662        if (ps == null) {
9663            return;
9664        }
9665
9666        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9667
9668        PermissionsState permissionsState = ps.getPermissionsState();
9669        PermissionsState origPermissions = permissionsState;
9670
9671        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9672
9673        boolean runtimePermissionsRevoked = false;
9674        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9675
9676        boolean changedInstallPermission = false;
9677
9678        if (replace) {
9679            ps.installPermissionsFixed = false;
9680            if (!ps.isSharedUser()) {
9681                origPermissions = new PermissionsState(permissionsState);
9682                permissionsState.reset();
9683            } else {
9684                // We need to know only about runtime permission changes since the
9685                // calling code always writes the install permissions state but
9686                // the runtime ones are written only if changed. The only cases of
9687                // changed runtime permissions here are promotion of an install to
9688                // runtime and revocation of a runtime from a shared user.
9689                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9690                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9691                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9692                    runtimePermissionsRevoked = true;
9693                }
9694            }
9695        }
9696
9697        permissionsState.setGlobalGids(mGlobalGids);
9698
9699        final int N = pkg.requestedPermissions.size();
9700        for (int i=0; i<N; i++) {
9701            final String name = pkg.requestedPermissions.get(i);
9702            final BasePermission bp = mSettings.mPermissions.get(name);
9703
9704            if (DEBUG_INSTALL) {
9705                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9706            }
9707
9708            if (bp == null || bp.packageSetting == null) {
9709                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9710                    Slog.w(TAG, "Unknown permission " + name
9711                            + " in package " + pkg.packageName);
9712                }
9713                continue;
9714            }
9715
9716            final String perm = bp.name;
9717            boolean allowedSig = false;
9718            int grant = GRANT_DENIED;
9719
9720            // Keep track of app op permissions.
9721            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9722                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9723                if (pkgs == null) {
9724                    pkgs = new ArraySet<>();
9725                    mAppOpPermissionPackages.put(bp.name, pkgs);
9726                }
9727                pkgs.add(pkg.packageName);
9728            }
9729
9730            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9731            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9732                    >= Build.VERSION_CODES.M;
9733            switch (level) {
9734                case PermissionInfo.PROTECTION_NORMAL: {
9735                    // For all apps normal permissions are install time ones.
9736                    grant = GRANT_INSTALL;
9737                } break;
9738
9739                case PermissionInfo.PROTECTION_DANGEROUS: {
9740                    // If a permission review is required for legacy apps we represent
9741                    // their permissions as always granted runtime ones since we need
9742                    // to keep the review required permission flag per user while an
9743                    // install permission's state is shared across all users.
9744                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9745                        // For legacy apps dangerous permissions are install time ones.
9746                        grant = GRANT_INSTALL;
9747                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9748                        // For legacy apps that became modern, install becomes runtime.
9749                        grant = GRANT_UPGRADE;
9750                    } else if (mPromoteSystemApps
9751                            && isSystemApp(ps)
9752                            && mExistingSystemPackages.contains(ps.name)) {
9753                        // For legacy system apps, install becomes runtime.
9754                        // We cannot check hasInstallPermission() for system apps since those
9755                        // permissions were granted implicitly and not persisted pre-M.
9756                        grant = GRANT_UPGRADE;
9757                    } else {
9758                        // For modern apps keep runtime permissions unchanged.
9759                        grant = GRANT_RUNTIME;
9760                    }
9761                } break;
9762
9763                case PermissionInfo.PROTECTION_SIGNATURE: {
9764                    // For all apps signature permissions are install time ones.
9765                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9766                    if (allowedSig) {
9767                        grant = GRANT_INSTALL;
9768                    }
9769                } break;
9770            }
9771
9772            if (DEBUG_INSTALL) {
9773                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9774            }
9775
9776            if (grant != GRANT_DENIED) {
9777                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9778                    // If this is an existing, non-system package, then
9779                    // we can't add any new permissions to it.
9780                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9781                        // Except...  if this is a permission that was added
9782                        // to the platform (note: need to only do this when
9783                        // updating the platform).
9784                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9785                            grant = GRANT_DENIED;
9786                        }
9787                    }
9788                }
9789
9790                switch (grant) {
9791                    case GRANT_INSTALL: {
9792                        // Revoke this as runtime permission to handle the case of
9793                        // a runtime permission being downgraded to an install one.
9794                        // Also in permission review mode we keep dangerous permissions
9795                        // for legacy apps
9796                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9797                            if (origPermissions.getRuntimePermissionState(
9798                                    bp.name, userId) != null) {
9799                                // Revoke the runtime permission and clear the flags.
9800                                origPermissions.revokeRuntimePermission(bp, userId);
9801                                origPermissions.updatePermissionFlags(bp, userId,
9802                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9803                                // If we revoked a permission permission, we have to write.
9804                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9805                                        changedRuntimePermissionUserIds, userId);
9806                            }
9807                        }
9808                        // Grant an install permission.
9809                        if (permissionsState.grantInstallPermission(bp) !=
9810                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9811                            changedInstallPermission = true;
9812                        }
9813                    } break;
9814
9815                    case GRANT_RUNTIME: {
9816                        // Grant previously granted runtime permissions.
9817                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9818                            PermissionState permissionState = origPermissions
9819                                    .getRuntimePermissionState(bp.name, userId);
9820                            int flags = permissionState != null
9821                                    ? permissionState.getFlags() : 0;
9822                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9823                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9824                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9825                                    // If we cannot put the permission as it was, we have to write.
9826                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9827                                            changedRuntimePermissionUserIds, userId);
9828                                }
9829                                // If the app supports runtime permissions no need for a review.
9830                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9831                                        && appSupportsRuntimePermissions
9832                                        && (flags & PackageManager
9833                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9834                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9835                                    // Since we changed the flags, we have to write.
9836                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9837                                            changedRuntimePermissionUserIds, userId);
9838                                }
9839                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9840                                    && !appSupportsRuntimePermissions) {
9841                                // For legacy apps that need a permission review, every new
9842                                // runtime permission is granted but it is pending a review.
9843                                // We also need to review only platform defined runtime
9844                                // permissions as these are the only ones the platform knows
9845                                // how to disable the API to simulate revocation as legacy
9846                                // apps don't expect to run with revoked permissions.
9847                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9848                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9849                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9850                                        // We changed the flags, hence have to write.
9851                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9852                                                changedRuntimePermissionUserIds, userId);
9853                                    }
9854                                }
9855                                if (permissionsState.grantRuntimePermission(bp, userId)
9856                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9857                                    // We changed the permission, hence have to write.
9858                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9859                                            changedRuntimePermissionUserIds, userId);
9860                                }
9861                            }
9862                            // Propagate the permission flags.
9863                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9864                        }
9865                    } break;
9866
9867                    case GRANT_UPGRADE: {
9868                        // Grant runtime permissions for a previously held install permission.
9869                        PermissionState permissionState = origPermissions
9870                                .getInstallPermissionState(bp.name);
9871                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9872
9873                        if (origPermissions.revokeInstallPermission(bp)
9874                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9875                            // We will be transferring the permission flags, so clear them.
9876                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9877                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9878                            changedInstallPermission = true;
9879                        }
9880
9881                        // If the permission is not to be promoted to runtime we ignore it and
9882                        // also its other flags as they are not applicable to install permissions.
9883                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9884                            for (int userId : currentUserIds) {
9885                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9886                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9887                                    // Transfer the permission flags.
9888                                    permissionsState.updatePermissionFlags(bp, userId,
9889                                            flags, flags);
9890                                    // If we granted the permission, we have to write.
9891                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9892                                            changedRuntimePermissionUserIds, userId);
9893                                }
9894                            }
9895                        }
9896                    } break;
9897
9898                    default: {
9899                        if (packageOfInterest == null
9900                                || packageOfInterest.equals(pkg.packageName)) {
9901                            Slog.w(TAG, "Not granting permission " + perm
9902                                    + " to package " + pkg.packageName
9903                                    + " because it was previously installed without");
9904                        }
9905                    } break;
9906                }
9907            } else {
9908                if (permissionsState.revokeInstallPermission(bp) !=
9909                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9910                    // Also drop the permission flags.
9911                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9912                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9913                    changedInstallPermission = true;
9914                    Slog.i(TAG, "Un-granting permission " + perm
9915                            + " from package " + pkg.packageName
9916                            + " (protectionLevel=" + bp.protectionLevel
9917                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9918                            + ")");
9919                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9920                    // Don't print warning for app op permissions, since it is fine for them
9921                    // not to be granted, there is a UI for the user to decide.
9922                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9923                        Slog.w(TAG, "Not granting permission " + perm
9924                                + " to package " + pkg.packageName
9925                                + " (protectionLevel=" + bp.protectionLevel
9926                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9927                                + ")");
9928                    }
9929                }
9930            }
9931        }
9932
9933        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9934                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9935            // This is the first that we have heard about this package, so the
9936            // permissions we have now selected are fixed until explicitly
9937            // changed.
9938            ps.installPermissionsFixed = true;
9939        }
9940
9941        // Persist the runtime permissions state for users with changes. If permissions
9942        // were revoked because no app in the shared user declares them we have to
9943        // write synchronously to avoid losing runtime permissions state.
9944        for (int userId : changedRuntimePermissionUserIds) {
9945            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9946        }
9947
9948        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9949    }
9950
9951    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9952        boolean allowed = false;
9953        final int NP = PackageParser.NEW_PERMISSIONS.length;
9954        for (int ip=0; ip<NP; ip++) {
9955            final PackageParser.NewPermissionInfo npi
9956                    = PackageParser.NEW_PERMISSIONS[ip];
9957            if (npi.name.equals(perm)
9958                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9959                allowed = true;
9960                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9961                        + pkg.packageName);
9962                break;
9963            }
9964        }
9965        return allowed;
9966    }
9967
9968    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9969            BasePermission bp, PermissionsState origPermissions) {
9970        boolean allowed;
9971        allowed = (compareSignatures(
9972                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9973                        == PackageManager.SIGNATURE_MATCH)
9974                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9975                        == PackageManager.SIGNATURE_MATCH);
9976        if (!allowed && (bp.protectionLevel
9977                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9978            if (isSystemApp(pkg)) {
9979                // For updated system applications, a system permission
9980                // is granted only if it had been defined by the original application.
9981                if (pkg.isUpdatedSystemApp()) {
9982                    final PackageSetting sysPs = mSettings
9983                            .getDisabledSystemPkgLPr(pkg.packageName);
9984                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9985                        // If the original was granted this permission, we take
9986                        // that grant decision as read and propagate it to the
9987                        // update.
9988                        if (sysPs.isPrivileged()) {
9989                            allowed = true;
9990                        }
9991                    } else {
9992                        // The system apk may have been updated with an older
9993                        // version of the one on the data partition, but which
9994                        // granted a new system permission that it didn't have
9995                        // before.  In this case we do want to allow the app to
9996                        // now get the new permission if the ancestral apk is
9997                        // privileged to get it.
9998                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9999                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10000                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10001                                    allowed = true;
10002                                    break;
10003                                }
10004                            }
10005                        }
10006                        // Also if a privileged parent package on the system image or any of
10007                        // its children requested a privileged permission, the updated child
10008                        // packages can also get the permission.
10009                        if (pkg.parentPackage != null) {
10010                            final PackageSetting disabledSysParentPs = mSettings
10011                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10012                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10013                                    && disabledSysParentPs.isPrivileged()) {
10014                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10015                                    allowed = true;
10016                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10017                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10018                                    for (int i = 0; i < count; i++) {
10019                                        PackageParser.Package disabledSysChildPkg =
10020                                                disabledSysParentPs.pkg.childPackages.get(i);
10021                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10022                                                perm)) {
10023                                            allowed = true;
10024                                            break;
10025                                        }
10026                                    }
10027                                }
10028                            }
10029                        }
10030                    }
10031                } else {
10032                    allowed = isPrivilegedApp(pkg);
10033                }
10034            }
10035        }
10036        if (!allowed) {
10037            if (!allowed && (bp.protectionLevel
10038                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10039                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10040                // If this was a previously normal/dangerous permission that got moved
10041                // to a system permission as part of the runtime permission redesign, then
10042                // we still want to blindly grant it to old apps.
10043                allowed = true;
10044            }
10045            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10046                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10047                // If this permission is to be granted to the system installer and
10048                // this app is an installer, then it gets the permission.
10049                allowed = true;
10050            }
10051            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10052                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10053                // If this permission is to be granted to the system verifier and
10054                // this app is a verifier, then it gets the permission.
10055                allowed = true;
10056            }
10057            if (!allowed && (bp.protectionLevel
10058                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10059                    && isSystemApp(pkg)) {
10060                // Any pre-installed system app is allowed to get this permission.
10061                allowed = true;
10062            }
10063            if (!allowed && (bp.protectionLevel
10064                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10065                // For development permissions, a development permission
10066                // is granted only if it was already granted.
10067                allowed = origPermissions.hasInstallPermission(perm);
10068            }
10069            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10070                    && pkg.packageName.equals(mSetupWizardPackage)) {
10071                // If this permission is to be granted to the system setup wizard and
10072                // this app is a setup wizard, then it gets the permission.
10073                allowed = true;
10074            }
10075        }
10076        return allowed;
10077    }
10078
10079    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10080        final int permCount = pkg.requestedPermissions.size();
10081        for (int j = 0; j < permCount; j++) {
10082            String requestedPermission = pkg.requestedPermissions.get(j);
10083            if (permission.equals(requestedPermission)) {
10084                return true;
10085            }
10086        }
10087        return false;
10088    }
10089
10090    final class ActivityIntentResolver
10091            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10092        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10093                boolean defaultOnly, int userId) {
10094            if (!sUserManager.exists(userId)) return null;
10095            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10096            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10097        }
10098
10099        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10100                int userId) {
10101            if (!sUserManager.exists(userId)) return null;
10102            mFlags = flags;
10103            return super.queryIntent(intent, resolvedType,
10104                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10105        }
10106
10107        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10108                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10109            if (!sUserManager.exists(userId)) return null;
10110            if (packageActivities == null) {
10111                return null;
10112            }
10113            mFlags = flags;
10114            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10115            final int N = packageActivities.size();
10116            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10117                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10118
10119            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10120            for (int i = 0; i < N; ++i) {
10121                intentFilters = packageActivities.get(i).intents;
10122                if (intentFilters != null && intentFilters.size() > 0) {
10123                    PackageParser.ActivityIntentInfo[] array =
10124                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10125                    intentFilters.toArray(array);
10126                    listCut.add(array);
10127                }
10128            }
10129            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10130        }
10131
10132        /**
10133         * Finds a privileged activity that matches the specified activity names.
10134         */
10135        private PackageParser.Activity findMatchingActivity(
10136                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10137            for (PackageParser.Activity sysActivity : activityList) {
10138                if (sysActivity.info.name.equals(activityInfo.name)) {
10139                    return sysActivity;
10140                }
10141                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10142                    return sysActivity;
10143                }
10144                if (sysActivity.info.targetActivity != null) {
10145                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10146                        return sysActivity;
10147                    }
10148                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10149                        return sysActivity;
10150                    }
10151                }
10152            }
10153            return null;
10154        }
10155
10156        public class IterGenerator<E> {
10157            public Iterator<E> generate(ActivityIntentInfo info) {
10158                return null;
10159            }
10160        }
10161
10162        public class ActionIterGenerator extends IterGenerator<String> {
10163            @Override
10164            public Iterator<String> generate(ActivityIntentInfo info) {
10165                return info.actionsIterator();
10166            }
10167        }
10168
10169        public class CategoriesIterGenerator extends IterGenerator<String> {
10170            @Override
10171            public Iterator<String> generate(ActivityIntentInfo info) {
10172                return info.categoriesIterator();
10173            }
10174        }
10175
10176        public class SchemesIterGenerator extends IterGenerator<String> {
10177            @Override
10178            public Iterator<String> generate(ActivityIntentInfo info) {
10179                return info.schemesIterator();
10180            }
10181        }
10182
10183        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10184            @Override
10185            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10186                return info.authoritiesIterator();
10187            }
10188        }
10189
10190        /**
10191         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10192         * MODIFIED. Do not pass in a list that should not be changed.
10193         */
10194        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10195                IterGenerator<T> generator, Iterator<T> searchIterator) {
10196            // loop through the set of actions; every one must be found in the intent filter
10197            while (searchIterator.hasNext()) {
10198                // we must have at least one filter in the list to consider a match
10199                if (intentList.size() == 0) {
10200                    break;
10201                }
10202
10203                final T searchAction = searchIterator.next();
10204
10205                // loop through the set of intent filters
10206                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10207                while (intentIter.hasNext()) {
10208                    final ActivityIntentInfo intentInfo = intentIter.next();
10209                    boolean selectionFound = false;
10210
10211                    // loop through the intent filter's selection criteria; at least one
10212                    // of them must match the searched criteria
10213                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10214                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10215                        final T intentSelection = intentSelectionIter.next();
10216                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10217                            selectionFound = true;
10218                            break;
10219                        }
10220                    }
10221
10222                    // the selection criteria wasn't found in this filter's set; this filter
10223                    // is not a potential match
10224                    if (!selectionFound) {
10225                        intentIter.remove();
10226                    }
10227                }
10228            }
10229        }
10230
10231        private boolean isProtectedAction(ActivityIntentInfo filter) {
10232            final Iterator<String> actionsIter = filter.actionsIterator();
10233            while (actionsIter != null && actionsIter.hasNext()) {
10234                final String filterAction = actionsIter.next();
10235                if (PROTECTED_ACTIONS.contains(filterAction)) {
10236                    return true;
10237                }
10238            }
10239            return false;
10240        }
10241
10242        /**
10243         * Adjusts the priority of the given intent filter according to policy.
10244         * <p>
10245         * <ul>
10246         * <li>The priority for non privileged applications is capped to '0'</li>
10247         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10248         * <li>The priority for unbundled updates to privileged applications is capped to the
10249         *      priority defined on the system partition</li>
10250         * </ul>
10251         * <p>
10252         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10253         * allowed to obtain any priority on any action.
10254         */
10255        private void adjustPriority(
10256                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10257            // nothing to do; priority is fine as-is
10258            if (intent.getPriority() <= 0) {
10259                return;
10260            }
10261
10262            final ActivityInfo activityInfo = intent.activity.info;
10263            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10264
10265            final boolean privilegedApp =
10266                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10267            if (!privilegedApp) {
10268                // non-privileged applications can never define a priority >0
10269                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10270                        + " package: " + applicationInfo.packageName
10271                        + " activity: " + intent.activity.className
10272                        + " origPrio: " + intent.getPriority());
10273                intent.setPriority(0);
10274                return;
10275            }
10276
10277            if (systemActivities == null) {
10278                // the system package is not disabled; we're parsing the system partition
10279                if (isProtectedAction(intent)) {
10280                    if (mDeferProtectedFilters) {
10281                        // We can't deal with these just yet. No component should ever obtain a
10282                        // >0 priority for a protected actions, with ONE exception -- the setup
10283                        // wizard. The setup wizard, however, cannot be known until we're able to
10284                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10285                        // until all intent filters have been processed. Chicken, meet egg.
10286                        // Let the filter temporarily have a high priority and rectify the
10287                        // priorities after all system packages have been scanned.
10288                        mProtectedFilters.add(intent);
10289                        if (DEBUG_FILTERS) {
10290                            Slog.i(TAG, "Protected action; save for later;"
10291                                    + " package: " + applicationInfo.packageName
10292                                    + " activity: " + intent.activity.className
10293                                    + " origPrio: " + intent.getPriority());
10294                        }
10295                        return;
10296                    } else {
10297                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10298                            Slog.i(TAG, "No setup wizard;"
10299                                + " All protected intents capped to priority 0");
10300                        }
10301                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10302                            if (DEBUG_FILTERS) {
10303                                Slog.i(TAG, "Found setup wizard;"
10304                                    + " allow priority " + intent.getPriority() + ";"
10305                                    + " package: " + intent.activity.info.packageName
10306                                    + " activity: " + intent.activity.className
10307                                    + " priority: " + intent.getPriority());
10308                            }
10309                            // setup wizard gets whatever it wants
10310                            return;
10311                        }
10312                        Slog.w(TAG, "Protected action; cap priority to 0;"
10313                                + " package: " + intent.activity.info.packageName
10314                                + " activity: " + intent.activity.className
10315                                + " origPrio: " + intent.getPriority());
10316                        intent.setPriority(0);
10317                        return;
10318                    }
10319                }
10320                // privileged apps on the system image get whatever priority they request
10321                return;
10322            }
10323
10324            // privileged app unbundled update ... try to find the same activity
10325            final PackageParser.Activity foundActivity =
10326                    findMatchingActivity(systemActivities, activityInfo);
10327            if (foundActivity == null) {
10328                // this is a new activity; it cannot obtain >0 priority
10329                if (DEBUG_FILTERS) {
10330                    Slog.i(TAG, "New activity; cap priority to 0;"
10331                            + " package: " + applicationInfo.packageName
10332                            + " activity: " + intent.activity.className
10333                            + " origPrio: " + intent.getPriority());
10334                }
10335                intent.setPriority(0);
10336                return;
10337            }
10338
10339            // found activity, now check for filter equivalence
10340
10341            // a shallow copy is enough; we modify the list, not its contents
10342            final List<ActivityIntentInfo> intentListCopy =
10343                    new ArrayList<>(foundActivity.intents);
10344            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10345
10346            // find matching action subsets
10347            final Iterator<String> actionsIterator = intent.actionsIterator();
10348            if (actionsIterator != null) {
10349                getIntentListSubset(
10350                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10351                if (intentListCopy.size() == 0) {
10352                    // no more intents to match; we're not equivalent
10353                    if (DEBUG_FILTERS) {
10354                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10355                                + " package: " + applicationInfo.packageName
10356                                + " activity: " + intent.activity.className
10357                                + " origPrio: " + intent.getPriority());
10358                    }
10359                    intent.setPriority(0);
10360                    return;
10361                }
10362            }
10363
10364            // find matching category subsets
10365            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10366            if (categoriesIterator != null) {
10367                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10368                        categoriesIterator);
10369                if (intentListCopy.size() == 0) {
10370                    // no more intents to match; we're not equivalent
10371                    if (DEBUG_FILTERS) {
10372                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10373                                + " package: " + applicationInfo.packageName
10374                                + " activity: " + intent.activity.className
10375                                + " origPrio: " + intent.getPriority());
10376                    }
10377                    intent.setPriority(0);
10378                    return;
10379                }
10380            }
10381
10382            // find matching schemes subsets
10383            final Iterator<String> schemesIterator = intent.schemesIterator();
10384            if (schemesIterator != null) {
10385                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10386                        schemesIterator);
10387                if (intentListCopy.size() == 0) {
10388                    // no more intents to match; we're not equivalent
10389                    if (DEBUG_FILTERS) {
10390                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10391                                + " package: " + applicationInfo.packageName
10392                                + " activity: " + intent.activity.className
10393                                + " origPrio: " + intent.getPriority());
10394                    }
10395                    intent.setPriority(0);
10396                    return;
10397                }
10398            }
10399
10400            // find matching authorities subsets
10401            final Iterator<IntentFilter.AuthorityEntry>
10402                    authoritiesIterator = intent.authoritiesIterator();
10403            if (authoritiesIterator != null) {
10404                getIntentListSubset(intentListCopy,
10405                        new AuthoritiesIterGenerator(),
10406                        authoritiesIterator);
10407                if (intentListCopy.size() == 0) {
10408                    // no more intents to match; we're not equivalent
10409                    if (DEBUG_FILTERS) {
10410                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10411                                + " package: " + applicationInfo.packageName
10412                                + " activity: " + intent.activity.className
10413                                + " origPrio: " + intent.getPriority());
10414                    }
10415                    intent.setPriority(0);
10416                    return;
10417                }
10418            }
10419
10420            // we found matching filter(s); app gets the max priority of all intents
10421            int cappedPriority = 0;
10422            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10423                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10424            }
10425            if (intent.getPriority() > cappedPriority) {
10426                if (DEBUG_FILTERS) {
10427                    Slog.i(TAG, "Found matching filter(s);"
10428                            + " cap priority to " + cappedPriority + ";"
10429                            + " package: " + applicationInfo.packageName
10430                            + " activity: " + intent.activity.className
10431                            + " origPrio: " + intent.getPriority());
10432                }
10433                intent.setPriority(cappedPriority);
10434                return;
10435            }
10436            // all this for nothing; the requested priority was <= what was on the system
10437        }
10438
10439        public final void addActivity(PackageParser.Activity a, String type) {
10440            mActivities.put(a.getComponentName(), a);
10441            if (DEBUG_SHOW_INFO)
10442                Log.v(
10443                TAG, "  " + type + " " +
10444                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10445            if (DEBUG_SHOW_INFO)
10446                Log.v(TAG, "    Class=" + a.info.name);
10447            final int NI = a.intents.size();
10448            for (int j=0; j<NI; j++) {
10449                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10450                if ("activity".equals(type)) {
10451                    final PackageSetting ps =
10452                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10453                    final List<PackageParser.Activity> systemActivities =
10454                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10455                    adjustPriority(systemActivities, intent);
10456                }
10457                if (DEBUG_SHOW_INFO) {
10458                    Log.v(TAG, "    IntentFilter:");
10459                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10460                }
10461                if (!intent.debugCheck()) {
10462                    Log.w(TAG, "==> For Activity " + a.info.name);
10463                }
10464                addFilter(intent);
10465            }
10466        }
10467
10468        public final void removeActivity(PackageParser.Activity a, String type) {
10469            mActivities.remove(a.getComponentName());
10470            if (DEBUG_SHOW_INFO) {
10471                Log.v(TAG, "  " + type + " "
10472                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10473                                : a.info.name) + ":");
10474                Log.v(TAG, "    Class=" + a.info.name);
10475            }
10476            final int NI = a.intents.size();
10477            for (int j=0; j<NI; j++) {
10478                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10479                if (DEBUG_SHOW_INFO) {
10480                    Log.v(TAG, "    IntentFilter:");
10481                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10482                }
10483                removeFilter(intent);
10484            }
10485        }
10486
10487        @Override
10488        protected boolean allowFilterResult(
10489                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10490            ActivityInfo filterAi = filter.activity.info;
10491            for (int i=dest.size()-1; i>=0; i--) {
10492                ActivityInfo destAi = dest.get(i).activityInfo;
10493                if (destAi.name == filterAi.name
10494                        && destAi.packageName == filterAi.packageName) {
10495                    return false;
10496                }
10497            }
10498            return true;
10499        }
10500
10501        @Override
10502        protected ActivityIntentInfo[] newArray(int size) {
10503            return new ActivityIntentInfo[size];
10504        }
10505
10506        @Override
10507        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10508            if (!sUserManager.exists(userId)) return true;
10509            PackageParser.Package p = filter.activity.owner;
10510            if (p != null) {
10511                PackageSetting ps = (PackageSetting)p.mExtras;
10512                if (ps != null) {
10513                    // System apps are never considered stopped for purposes of
10514                    // filtering, because there may be no way for the user to
10515                    // actually re-launch them.
10516                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10517                            && ps.getStopped(userId);
10518                }
10519            }
10520            return false;
10521        }
10522
10523        @Override
10524        protected boolean isPackageForFilter(String packageName,
10525                PackageParser.ActivityIntentInfo info) {
10526            return packageName.equals(info.activity.owner.packageName);
10527        }
10528
10529        @Override
10530        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10531                int match, int userId) {
10532            if (!sUserManager.exists(userId)) return null;
10533            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10534                return null;
10535            }
10536            final PackageParser.Activity activity = info.activity;
10537            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10538            if (ps == null) {
10539                return null;
10540            }
10541            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10542                    ps.readUserState(userId), userId);
10543            if (ai == null) {
10544                return null;
10545            }
10546            final ResolveInfo res = new ResolveInfo();
10547            res.activityInfo = ai;
10548            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10549                res.filter = info;
10550            }
10551            if (info != null) {
10552                res.handleAllWebDataURI = info.handleAllWebDataURI();
10553            }
10554            res.priority = info.getPriority();
10555            res.preferredOrder = activity.owner.mPreferredOrder;
10556            //System.out.println("Result: " + res.activityInfo.className +
10557            //                   " = " + res.priority);
10558            res.match = match;
10559            res.isDefault = info.hasDefault;
10560            res.labelRes = info.labelRes;
10561            res.nonLocalizedLabel = info.nonLocalizedLabel;
10562            if (userNeedsBadging(userId)) {
10563                res.noResourceId = true;
10564            } else {
10565                res.icon = info.icon;
10566            }
10567            res.iconResourceId = info.icon;
10568            res.system = res.activityInfo.applicationInfo.isSystemApp();
10569            return res;
10570        }
10571
10572        @Override
10573        protected void sortResults(List<ResolveInfo> results) {
10574            Collections.sort(results, mResolvePrioritySorter);
10575        }
10576
10577        @Override
10578        protected void dumpFilter(PrintWriter out, String prefix,
10579                PackageParser.ActivityIntentInfo filter) {
10580            out.print(prefix); out.print(
10581                    Integer.toHexString(System.identityHashCode(filter.activity)));
10582                    out.print(' ');
10583                    filter.activity.printComponentShortName(out);
10584                    out.print(" filter ");
10585                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10586        }
10587
10588        @Override
10589        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10590            return filter.activity;
10591        }
10592
10593        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10594            PackageParser.Activity activity = (PackageParser.Activity)label;
10595            out.print(prefix); out.print(
10596                    Integer.toHexString(System.identityHashCode(activity)));
10597                    out.print(' ');
10598                    activity.printComponentShortName(out);
10599            if (count > 1) {
10600                out.print(" ("); out.print(count); out.print(" filters)");
10601            }
10602            out.println();
10603        }
10604
10605        // Keys are String (activity class name), values are Activity.
10606        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10607                = new ArrayMap<ComponentName, PackageParser.Activity>();
10608        private int mFlags;
10609    }
10610
10611    private final class ServiceIntentResolver
10612            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10613        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10614                boolean defaultOnly, int userId) {
10615            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10616            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10617        }
10618
10619        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10620                int userId) {
10621            if (!sUserManager.exists(userId)) return null;
10622            mFlags = flags;
10623            return super.queryIntent(intent, resolvedType,
10624                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10625        }
10626
10627        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10628                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10629            if (!sUserManager.exists(userId)) return null;
10630            if (packageServices == null) {
10631                return null;
10632            }
10633            mFlags = flags;
10634            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10635            final int N = packageServices.size();
10636            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10637                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10638
10639            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10640            for (int i = 0; i < N; ++i) {
10641                intentFilters = packageServices.get(i).intents;
10642                if (intentFilters != null && intentFilters.size() > 0) {
10643                    PackageParser.ServiceIntentInfo[] array =
10644                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10645                    intentFilters.toArray(array);
10646                    listCut.add(array);
10647                }
10648            }
10649            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10650        }
10651
10652        public final void addService(PackageParser.Service s) {
10653            mServices.put(s.getComponentName(), s);
10654            if (DEBUG_SHOW_INFO) {
10655                Log.v(TAG, "  "
10656                        + (s.info.nonLocalizedLabel != null
10657                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10658                Log.v(TAG, "    Class=" + s.info.name);
10659            }
10660            final int NI = s.intents.size();
10661            int j;
10662            for (j=0; j<NI; j++) {
10663                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10664                if (DEBUG_SHOW_INFO) {
10665                    Log.v(TAG, "    IntentFilter:");
10666                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10667                }
10668                if (!intent.debugCheck()) {
10669                    Log.w(TAG, "==> For Service " + s.info.name);
10670                }
10671                addFilter(intent);
10672            }
10673        }
10674
10675        public final void removeService(PackageParser.Service s) {
10676            mServices.remove(s.getComponentName());
10677            if (DEBUG_SHOW_INFO) {
10678                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10679                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10680                Log.v(TAG, "    Class=" + s.info.name);
10681            }
10682            final int NI = s.intents.size();
10683            int j;
10684            for (j=0; j<NI; j++) {
10685                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10686                if (DEBUG_SHOW_INFO) {
10687                    Log.v(TAG, "    IntentFilter:");
10688                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10689                }
10690                removeFilter(intent);
10691            }
10692        }
10693
10694        @Override
10695        protected boolean allowFilterResult(
10696                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10697            ServiceInfo filterSi = filter.service.info;
10698            for (int i=dest.size()-1; i>=0; i--) {
10699                ServiceInfo destAi = dest.get(i).serviceInfo;
10700                if (destAi.name == filterSi.name
10701                        && destAi.packageName == filterSi.packageName) {
10702                    return false;
10703                }
10704            }
10705            return true;
10706        }
10707
10708        @Override
10709        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10710            return new PackageParser.ServiceIntentInfo[size];
10711        }
10712
10713        @Override
10714        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10715            if (!sUserManager.exists(userId)) return true;
10716            PackageParser.Package p = filter.service.owner;
10717            if (p != null) {
10718                PackageSetting ps = (PackageSetting)p.mExtras;
10719                if (ps != null) {
10720                    // System apps are never considered stopped for purposes of
10721                    // filtering, because there may be no way for the user to
10722                    // actually re-launch them.
10723                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10724                            && ps.getStopped(userId);
10725                }
10726            }
10727            return false;
10728        }
10729
10730        @Override
10731        protected boolean isPackageForFilter(String packageName,
10732                PackageParser.ServiceIntentInfo info) {
10733            return packageName.equals(info.service.owner.packageName);
10734        }
10735
10736        @Override
10737        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10738                int match, int userId) {
10739            if (!sUserManager.exists(userId)) return null;
10740            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10741            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10742                return null;
10743            }
10744            final PackageParser.Service service = info.service;
10745            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10746            if (ps == null) {
10747                return null;
10748            }
10749            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10750                    ps.readUserState(userId), userId);
10751            if (si == null) {
10752                return null;
10753            }
10754            final ResolveInfo res = new ResolveInfo();
10755            res.serviceInfo = si;
10756            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10757                res.filter = filter;
10758            }
10759            res.priority = info.getPriority();
10760            res.preferredOrder = service.owner.mPreferredOrder;
10761            res.match = match;
10762            res.isDefault = info.hasDefault;
10763            res.labelRes = info.labelRes;
10764            res.nonLocalizedLabel = info.nonLocalizedLabel;
10765            res.icon = info.icon;
10766            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10767            return res;
10768        }
10769
10770        @Override
10771        protected void sortResults(List<ResolveInfo> results) {
10772            Collections.sort(results, mResolvePrioritySorter);
10773        }
10774
10775        @Override
10776        protected void dumpFilter(PrintWriter out, String prefix,
10777                PackageParser.ServiceIntentInfo filter) {
10778            out.print(prefix); out.print(
10779                    Integer.toHexString(System.identityHashCode(filter.service)));
10780                    out.print(' ');
10781                    filter.service.printComponentShortName(out);
10782                    out.print(" filter ");
10783                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10784        }
10785
10786        @Override
10787        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10788            return filter.service;
10789        }
10790
10791        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10792            PackageParser.Service service = (PackageParser.Service)label;
10793            out.print(prefix); out.print(
10794                    Integer.toHexString(System.identityHashCode(service)));
10795                    out.print(' ');
10796                    service.printComponentShortName(out);
10797            if (count > 1) {
10798                out.print(" ("); out.print(count); out.print(" filters)");
10799            }
10800            out.println();
10801        }
10802
10803//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10804//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10805//            final List<ResolveInfo> retList = Lists.newArrayList();
10806//            while (i.hasNext()) {
10807//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10808//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10809//                    retList.add(resolveInfo);
10810//                }
10811//            }
10812//            return retList;
10813//        }
10814
10815        // Keys are String (activity class name), values are Activity.
10816        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10817                = new ArrayMap<ComponentName, PackageParser.Service>();
10818        private int mFlags;
10819    };
10820
10821    private final class ProviderIntentResolver
10822            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10823        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10824                boolean defaultOnly, int userId) {
10825            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10826            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10827        }
10828
10829        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10830                int userId) {
10831            if (!sUserManager.exists(userId))
10832                return null;
10833            mFlags = flags;
10834            return super.queryIntent(intent, resolvedType,
10835                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10836        }
10837
10838        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10839                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10840            if (!sUserManager.exists(userId))
10841                return null;
10842            if (packageProviders == null) {
10843                return null;
10844            }
10845            mFlags = flags;
10846            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10847            final int N = packageProviders.size();
10848            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10849                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10850
10851            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10852            for (int i = 0; i < N; ++i) {
10853                intentFilters = packageProviders.get(i).intents;
10854                if (intentFilters != null && intentFilters.size() > 0) {
10855                    PackageParser.ProviderIntentInfo[] array =
10856                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10857                    intentFilters.toArray(array);
10858                    listCut.add(array);
10859                }
10860            }
10861            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10862        }
10863
10864        public final void addProvider(PackageParser.Provider p) {
10865            if (mProviders.containsKey(p.getComponentName())) {
10866                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10867                return;
10868            }
10869
10870            mProviders.put(p.getComponentName(), p);
10871            if (DEBUG_SHOW_INFO) {
10872                Log.v(TAG, "  "
10873                        + (p.info.nonLocalizedLabel != null
10874                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10875                Log.v(TAG, "    Class=" + p.info.name);
10876            }
10877            final int NI = p.intents.size();
10878            int j;
10879            for (j = 0; j < NI; j++) {
10880                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10881                if (DEBUG_SHOW_INFO) {
10882                    Log.v(TAG, "    IntentFilter:");
10883                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10884                }
10885                if (!intent.debugCheck()) {
10886                    Log.w(TAG, "==> For Provider " + p.info.name);
10887                }
10888                addFilter(intent);
10889            }
10890        }
10891
10892        public final void removeProvider(PackageParser.Provider p) {
10893            mProviders.remove(p.getComponentName());
10894            if (DEBUG_SHOW_INFO) {
10895                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10896                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10897                Log.v(TAG, "    Class=" + p.info.name);
10898            }
10899            final int NI = p.intents.size();
10900            int j;
10901            for (j = 0; j < NI; j++) {
10902                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10903                if (DEBUG_SHOW_INFO) {
10904                    Log.v(TAG, "    IntentFilter:");
10905                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10906                }
10907                removeFilter(intent);
10908            }
10909        }
10910
10911        @Override
10912        protected boolean allowFilterResult(
10913                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10914            ProviderInfo filterPi = filter.provider.info;
10915            for (int i = dest.size() - 1; i >= 0; i--) {
10916                ProviderInfo destPi = dest.get(i).providerInfo;
10917                if (destPi.name == filterPi.name
10918                        && destPi.packageName == filterPi.packageName) {
10919                    return false;
10920                }
10921            }
10922            return true;
10923        }
10924
10925        @Override
10926        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10927            return new PackageParser.ProviderIntentInfo[size];
10928        }
10929
10930        @Override
10931        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10932            if (!sUserManager.exists(userId))
10933                return true;
10934            PackageParser.Package p = filter.provider.owner;
10935            if (p != null) {
10936                PackageSetting ps = (PackageSetting) p.mExtras;
10937                if (ps != null) {
10938                    // System apps are never considered stopped for purposes of
10939                    // filtering, because there may be no way for the user to
10940                    // actually re-launch them.
10941                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10942                            && ps.getStopped(userId);
10943                }
10944            }
10945            return false;
10946        }
10947
10948        @Override
10949        protected boolean isPackageForFilter(String packageName,
10950                PackageParser.ProviderIntentInfo info) {
10951            return packageName.equals(info.provider.owner.packageName);
10952        }
10953
10954        @Override
10955        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10956                int match, int userId) {
10957            if (!sUserManager.exists(userId))
10958                return null;
10959            final PackageParser.ProviderIntentInfo info = filter;
10960            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10961                return null;
10962            }
10963            final PackageParser.Provider provider = info.provider;
10964            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10965            if (ps == null) {
10966                return null;
10967            }
10968            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10969                    ps.readUserState(userId), userId);
10970            if (pi == null) {
10971                return null;
10972            }
10973            final ResolveInfo res = new ResolveInfo();
10974            res.providerInfo = pi;
10975            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10976                res.filter = filter;
10977            }
10978            res.priority = info.getPriority();
10979            res.preferredOrder = provider.owner.mPreferredOrder;
10980            res.match = match;
10981            res.isDefault = info.hasDefault;
10982            res.labelRes = info.labelRes;
10983            res.nonLocalizedLabel = info.nonLocalizedLabel;
10984            res.icon = info.icon;
10985            res.system = res.providerInfo.applicationInfo.isSystemApp();
10986            return res;
10987        }
10988
10989        @Override
10990        protected void sortResults(List<ResolveInfo> results) {
10991            Collections.sort(results, mResolvePrioritySorter);
10992        }
10993
10994        @Override
10995        protected void dumpFilter(PrintWriter out, String prefix,
10996                PackageParser.ProviderIntentInfo filter) {
10997            out.print(prefix);
10998            out.print(
10999                    Integer.toHexString(System.identityHashCode(filter.provider)));
11000            out.print(' ');
11001            filter.provider.printComponentShortName(out);
11002            out.print(" filter ");
11003            out.println(Integer.toHexString(System.identityHashCode(filter)));
11004        }
11005
11006        @Override
11007        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11008            return filter.provider;
11009        }
11010
11011        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11012            PackageParser.Provider provider = (PackageParser.Provider)label;
11013            out.print(prefix); out.print(
11014                    Integer.toHexString(System.identityHashCode(provider)));
11015                    out.print(' ');
11016                    provider.printComponentShortName(out);
11017            if (count > 1) {
11018                out.print(" ("); out.print(count); out.print(" filters)");
11019            }
11020            out.println();
11021        }
11022
11023        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11024                = new ArrayMap<ComponentName, PackageParser.Provider>();
11025        private int mFlags;
11026    }
11027
11028    private static final class EphemeralIntentResolver
11029            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11030        @Override
11031        protected EphemeralResolveIntentInfo[] newArray(int size) {
11032            return new EphemeralResolveIntentInfo[size];
11033        }
11034
11035        @Override
11036        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11037            return true;
11038        }
11039
11040        @Override
11041        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11042                int userId) {
11043            if (!sUserManager.exists(userId)) {
11044                return null;
11045            }
11046            return info.getEphemeralResolveInfo();
11047        }
11048    }
11049
11050    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11051            new Comparator<ResolveInfo>() {
11052        public int compare(ResolveInfo r1, ResolveInfo r2) {
11053            int v1 = r1.priority;
11054            int v2 = r2.priority;
11055            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11056            if (v1 != v2) {
11057                return (v1 > v2) ? -1 : 1;
11058            }
11059            v1 = r1.preferredOrder;
11060            v2 = r2.preferredOrder;
11061            if (v1 != v2) {
11062                return (v1 > v2) ? -1 : 1;
11063            }
11064            if (r1.isDefault != r2.isDefault) {
11065                return r1.isDefault ? -1 : 1;
11066            }
11067            v1 = r1.match;
11068            v2 = r2.match;
11069            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11070            if (v1 != v2) {
11071                return (v1 > v2) ? -1 : 1;
11072            }
11073            if (r1.system != r2.system) {
11074                return r1.system ? -1 : 1;
11075            }
11076            if (r1.activityInfo != null) {
11077                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11078            }
11079            if (r1.serviceInfo != null) {
11080                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11081            }
11082            if (r1.providerInfo != null) {
11083                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11084            }
11085            return 0;
11086        }
11087    };
11088
11089    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11090            new Comparator<ProviderInfo>() {
11091        public int compare(ProviderInfo p1, ProviderInfo p2) {
11092            final int v1 = p1.initOrder;
11093            final int v2 = p2.initOrder;
11094            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11095        }
11096    };
11097
11098    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11099            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11100            final int[] userIds) {
11101        mHandler.post(new Runnable() {
11102            @Override
11103            public void run() {
11104                try {
11105                    final IActivityManager am = ActivityManagerNative.getDefault();
11106                    if (am == null) return;
11107                    final int[] resolvedUserIds;
11108                    if (userIds == null) {
11109                        resolvedUserIds = am.getRunningUserIds();
11110                    } else {
11111                        resolvedUserIds = userIds;
11112                    }
11113                    for (int id : resolvedUserIds) {
11114                        final Intent intent = new Intent(action,
11115                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11116                        if (extras != null) {
11117                            intent.putExtras(extras);
11118                        }
11119                        if (targetPkg != null) {
11120                            intent.setPackage(targetPkg);
11121                        }
11122                        // Modify the UID when posting to other users
11123                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11124                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11125                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11126                            intent.putExtra(Intent.EXTRA_UID, uid);
11127                        }
11128                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11129                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11130                        if (DEBUG_BROADCASTS) {
11131                            RuntimeException here = new RuntimeException("here");
11132                            here.fillInStackTrace();
11133                            Slog.d(TAG, "Sending to user " + id + ": "
11134                                    + intent.toShortString(false, true, false, false)
11135                                    + " " + intent.getExtras(), here);
11136                        }
11137                        am.broadcastIntent(null, intent, null, finishedReceiver,
11138                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11139                                null, finishedReceiver != null, false, id);
11140                    }
11141                } catch (RemoteException ex) {
11142                }
11143            }
11144        });
11145    }
11146
11147    /**
11148     * Check if the external storage media is available. This is true if there
11149     * is a mounted external storage medium or if the external storage is
11150     * emulated.
11151     */
11152    private boolean isExternalMediaAvailable() {
11153        return mMediaMounted || Environment.isExternalStorageEmulated();
11154    }
11155
11156    @Override
11157    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11158        // writer
11159        synchronized (mPackages) {
11160            if (!isExternalMediaAvailable()) {
11161                // If the external storage is no longer mounted at this point,
11162                // the caller may not have been able to delete all of this
11163                // packages files and can not delete any more.  Bail.
11164                return null;
11165            }
11166            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11167            if (lastPackage != null) {
11168                pkgs.remove(lastPackage);
11169            }
11170            if (pkgs.size() > 0) {
11171                return pkgs.get(0);
11172            }
11173        }
11174        return null;
11175    }
11176
11177    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11178        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11179                userId, andCode ? 1 : 0, packageName);
11180        if (mSystemReady) {
11181            msg.sendToTarget();
11182        } else {
11183            if (mPostSystemReadyMessages == null) {
11184                mPostSystemReadyMessages = new ArrayList<>();
11185            }
11186            mPostSystemReadyMessages.add(msg);
11187        }
11188    }
11189
11190    void startCleaningPackages() {
11191        // reader
11192        if (!isExternalMediaAvailable()) {
11193            return;
11194        }
11195        synchronized (mPackages) {
11196            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11197                return;
11198            }
11199        }
11200        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11201        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11202        IActivityManager am = ActivityManagerNative.getDefault();
11203        if (am != null) {
11204            try {
11205                am.startService(null, intent, null, mContext.getOpPackageName(),
11206                        UserHandle.USER_SYSTEM);
11207            } catch (RemoteException e) {
11208            }
11209        }
11210    }
11211
11212    @Override
11213    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11214            int installFlags, String installerPackageName, int userId) {
11215        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11216
11217        final int callingUid = Binder.getCallingUid();
11218        enforceCrossUserPermission(callingUid, userId,
11219                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11220
11221        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11222            try {
11223                if (observer != null) {
11224                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11225                }
11226            } catch (RemoteException re) {
11227            }
11228            return;
11229        }
11230
11231        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11232            installFlags |= PackageManager.INSTALL_FROM_ADB;
11233
11234        } else {
11235            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11236            // about installerPackageName.
11237
11238            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11239            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11240        }
11241
11242        UserHandle user;
11243        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11244            user = UserHandle.ALL;
11245        } else {
11246            user = new UserHandle(userId);
11247        }
11248
11249        // Only system components can circumvent runtime permissions when installing.
11250        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11251                && mContext.checkCallingOrSelfPermission(Manifest.permission
11252                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11253            throw new SecurityException("You need the "
11254                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11255                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11256        }
11257
11258        final File originFile = new File(originPath);
11259        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11260
11261        final Message msg = mHandler.obtainMessage(INIT_COPY);
11262        final VerificationInfo verificationInfo = new VerificationInfo(
11263                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11264        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11265                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11266                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11267                null /*certificates*/);
11268        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11269        msg.obj = params;
11270
11271        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11272                System.identityHashCode(msg.obj));
11273        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11274                System.identityHashCode(msg.obj));
11275
11276        mHandler.sendMessage(msg);
11277    }
11278
11279    void installStage(String packageName, File stagedDir, String stagedCid,
11280            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11281            String installerPackageName, int installerUid, UserHandle user,
11282            Certificate[][] certificates) {
11283        if (DEBUG_EPHEMERAL) {
11284            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11285                Slog.d(TAG, "Ephemeral install of " + packageName);
11286            }
11287        }
11288        final VerificationInfo verificationInfo = new VerificationInfo(
11289                sessionParams.originatingUri, sessionParams.referrerUri,
11290                sessionParams.originatingUid, installerUid);
11291
11292        final OriginInfo origin;
11293        if (stagedDir != null) {
11294            origin = OriginInfo.fromStagedFile(stagedDir);
11295        } else {
11296            origin = OriginInfo.fromStagedContainer(stagedCid);
11297        }
11298
11299        final Message msg = mHandler.obtainMessage(INIT_COPY);
11300        final InstallParams params = new InstallParams(origin, null, observer,
11301                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11302                verificationInfo, user, sessionParams.abiOverride,
11303                sessionParams.grantedRuntimePermissions, certificates);
11304        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11305        msg.obj = params;
11306
11307        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11308                System.identityHashCode(msg.obj));
11309        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11310                System.identityHashCode(msg.obj));
11311
11312        mHandler.sendMessage(msg);
11313    }
11314
11315    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11316            int userId) {
11317        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11318        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11319    }
11320
11321    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11322            int appId, int userId) {
11323        Bundle extras = new Bundle(1);
11324        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11325
11326        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11327                packageName, extras, 0, null, null, new int[] {userId});
11328        try {
11329            IActivityManager am = ActivityManagerNative.getDefault();
11330            if (isSystem && am.isUserRunning(userId, 0)) {
11331                // The just-installed/enabled app is bundled on the system, so presumed
11332                // to be able to run automatically without needing an explicit launch.
11333                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11334                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11335                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11336                        .setPackage(packageName);
11337                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11338                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11339            }
11340        } catch (RemoteException e) {
11341            // shouldn't happen
11342            Slog.w(TAG, "Unable to bootstrap installed package", e);
11343        }
11344    }
11345
11346    @Override
11347    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11348            int userId) {
11349        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11350        PackageSetting pkgSetting;
11351        final int uid = Binder.getCallingUid();
11352        enforceCrossUserPermission(uid, userId,
11353                true /* requireFullPermission */, true /* checkShell */,
11354                "setApplicationHiddenSetting for user " + userId);
11355
11356        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11357            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11358            return false;
11359        }
11360
11361        long callingId = Binder.clearCallingIdentity();
11362        try {
11363            boolean sendAdded = false;
11364            boolean sendRemoved = false;
11365            // writer
11366            synchronized (mPackages) {
11367                pkgSetting = mSettings.mPackages.get(packageName);
11368                if (pkgSetting == null) {
11369                    return false;
11370                }
11371                if (pkgSetting.getHidden(userId) != hidden) {
11372                    pkgSetting.setHidden(hidden, userId);
11373                    mSettings.writePackageRestrictionsLPr(userId);
11374                    if (hidden) {
11375                        sendRemoved = true;
11376                    } else {
11377                        sendAdded = true;
11378                    }
11379                }
11380            }
11381            if (sendAdded) {
11382                sendPackageAddedForUser(packageName, pkgSetting, userId);
11383                return true;
11384            }
11385            if (sendRemoved) {
11386                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11387                        "hiding pkg");
11388                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11389                return true;
11390            }
11391        } finally {
11392            Binder.restoreCallingIdentity(callingId);
11393        }
11394        return false;
11395    }
11396
11397    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11398            int userId) {
11399        final PackageRemovedInfo info = new PackageRemovedInfo();
11400        info.removedPackage = packageName;
11401        info.removedUsers = new int[] {userId};
11402        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11403        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11404    }
11405
11406    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11407        if (pkgList.length > 0) {
11408            Bundle extras = new Bundle(1);
11409            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11410
11411            sendPackageBroadcast(
11412                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11413                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11414                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11415                    new int[] {userId});
11416        }
11417    }
11418
11419    /**
11420     * Returns true if application is not found or there was an error. Otherwise it returns
11421     * the hidden state of the package for the given user.
11422     */
11423    @Override
11424    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11425        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11426        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11427                true /* requireFullPermission */, false /* checkShell */,
11428                "getApplicationHidden for user " + userId);
11429        PackageSetting pkgSetting;
11430        long callingId = Binder.clearCallingIdentity();
11431        try {
11432            // writer
11433            synchronized (mPackages) {
11434                pkgSetting = mSettings.mPackages.get(packageName);
11435                if (pkgSetting == null) {
11436                    return true;
11437                }
11438                return pkgSetting.getHidden(userId);
11439            }
11440        } finally {
11441            Binder.restoreCallingIdentity(callingId);
11442        }
11443    }
11444
11445    /**
11446     * @hide
11447     */
11448    @Override
11449    public int installExistingPackageAsUser(String packageName, int userId) {
11450        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11451                null);
11452        PackageSetting pkgSetting;
11453        final int uid = Binder.getCallingUid();
11454        enforceCrossUserPermission(uid, userId,
11455                true /* requireFullPermission */, true /* checkShell */,
11456                "installExistingPackage for user " + userId);
11457        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11458            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11459        }
11460
11461        long callingId = Binder.clearCallingIdentity();
11462        try {
11463            boolean installed = false;
11464
11465            // writer
11466            synchronized (mPackages) {
11467                pkgSetting = mSettings.mPackages.get(packageName);
11468                if (pkgSetting == null) {
11469                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11470                }
11471                if (!pkgSetting.getInstalled(userId)) {
11472                    pkgSetting.setInstalled(true, userId);
11473                    pkgSetting.setHidden(false, userId);
11474                    mSettings.writePackageRestrictionsLPr(userId);
11475                    installed = true;
11476                }
11477            }
11478
11479            if (installed) {
11480                if (pkgSetting.pkg != null) {
11481                    synchronized (mInstallLock) {
11482                        // We don't need to freeze for a brand new install
11483                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11484                    }
11485                }
11486                sendPackageAddedForUser(packageName, pkgSetting, userId);
11487            }
11488        } finally {
11489            Binder.restoreCallingIdentity(callingId);
11490        }
11491
11492        return PackageManager.INSTALL_SUCCEEDED;
11493    }
11494
11495    boolean isUserRestricted(int userId, String restrictionKey) {
11496        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11497        if (restrictions.getBoolean(restrictionKey, false)) {
11498            Log.w(TAG, "User is restricted: " + restrictionKey);
11499            return true;
11500        }
11501        return false;
11502    }
11503
11504    @Override
11505    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11506            int userId) {
11507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11508        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11509                true /* requireFullPermission */, true /* checkShell */,
11510                "setPackagesSuspended for user " + userId);
11511
11512        if (ArrayUtils.isEmpty(packageNames)) {
11513            return packageNames;
11514        }
11515
11516        // List of package names for whom the suspended state has changed.
11517        List<String> changedPackages = new ArrayList<>(packageNames.length);
11518        // List of package names for whom the suspended state is not set as requested in this
11519        // method.
11520        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11521        long callingId = Binder.clearCallingIdentity();
11522        try {
11523            for (int i = 0; i < packageNames.length; i++) {
11524                String packageName = packageNames[i];
11525                boolean changed = false;
11526                final int appId;
11527                synchronized (mPackages) {
11528                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11529                    if (pkgSetting == null) {
11530                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11531                                + "\". Skipping suspending/un-suspending.");
11532                        unactionedPackages.add(packageName);
11533                        continue;
11534                    }
11535                    appId = pkgSetting.appId;
11536                    if (pkgSetting.getSuspended(userId) != suspended) {
11537                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11538                            unactionedPackages.add(packageName);
11539                            continue;
11540                        }
11541                        pkgSetting.setSuspended(suspended, userId);
11542                        mSettings.writePackageRestrictionsLPr(userId);
11543                        changed = true;
11544                        changedPackages.add(packageName);
11545                    }
11546                }
11547
11548                if (changed && suspended) {
11549                    killApplication(packageName, UserHandle.getUid(userId, appId),
11550                            "suspending package");
11551                }
11552            }
11553        } finally {
11554            Binder.restoreCallingIdentity(callingId);
11555        }
11556
11557        if (!changedPackages.isEmpty()) {
11558            sendPackagesSuspendedForUser(changedPackages.toArray(
11559                    new String[changedPackages.size()]), userId, suspended);
11560        }
11561
11562        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11563    }
11564
11565    @Override
11566    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11567        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11568                true /* requireFullPermission */, false /* checkShell */,
11569                "isPackageSuspendedForUser for user " + userId);
11570        synchronized (mPackages) {
11571            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11572            if (pkgSetting == null) {
11573                throw new IllegalArgumentException("Unknown target package: " + packageName);
11574            }
11575            return pkgSetting.getSuspended(userId);
11576        }
11577    }
11578
11579    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11580        if (isPackageDeviceAdmin(packageName, userId)) {
11581            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11582                    + "\": has an active device admin");
11583            return false;
11584        }
11585
11586        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11587        if (packageName.equals(activeLauncherPackageName)) {
11588            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11589                    + "\": contains the active launcher");
11590            return false;
11591        }
11592
11593        if (packageName.equals(mRequiredInstallerPackage)) {
11594            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11595                    + "\": required for package installation");
11596            return false;
11597        }
11598
11599        if (packageName.equals(mRequiredVerifierPackage)) {
11600            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11601                    + "\": required for package verification");
11602            return false;
11603        }
11604
11605        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11606            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11607                    + "\": is the default dialer");
11608            return false;
11609        }
11610
11611        return true;
11612    }
11613
11614    private String getActiveLauncherPackageName(int userId) {
11615        Intent intent = new Intent(Intent.ACTION_MAIN);
11616        intent.addCategory(Intent.CATEGORY_HOME);
11617        ResolveInfo resolveInfo = resolveIntent(
11618                intent,
11619                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11620                PackageManager.MATCH_DEFAULT_ONLY,
11621                userId);
11622
11623        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11624    }
11625
11626    private String getDefaultDialerPackageName(int userId) {
11627        synchronized (mPackages) {
11628            return mSettings.getDefaultDialerPackageNameLPw(userId);
11629        }
11630    }
11631
11632    @Override
11633    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11634        mContext.enforceCallingOrSelfPermission(
11635                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11636                "Only package verification agents can verify applications");
11637
11638        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11639        final PackageVerificationResponse response = new PackageVerificationResponse(
11640                verificationCode, Binder.getCallingUid());
11641        msg.arg1 = id;
11642        msg.obj = response;
11643        mHandler.sendMessage(msg);
11644    }
11645
11646    @Override
11647    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11648            long millisecondsToDelay) {
11649        mContext.enforceCallingOrSelfPermission(
11650                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11651                "Only package verification agents can extend verification timeouts");
11652
11653        final PackageVerificationState state = mPendingVerification.get(id);
11654        final PackageVerificationResponse response = new PackageVerificationResponse(
11655                verificationCodeAtTimeout, Binder.getCallingUid());
11656
11657        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11658            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11659        }
11660        if (millisecondsToDelay < 0) {
11661            millisecondsToDelay = 0;
11662        }
11663        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11664                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11665            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11666        }
11667
11668        if ((state != null) && !state.timeoutExtended()) {
11669            state.extendTimeout();
11670
11671            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11672            msg.arg1 = id;
11673            msg.obj = response;
11674            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11675        }
11676    }
11677
11678    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11679            int verificationCode, UserHandle user) {
11680        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11681        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11682        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11683        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11684        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11685
11686        mContext.sendBroadcastAsUser(intent, user,
11687                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11688    }
11689
11690    private ComponentName matchComponentForVerifier(String packageName,
11691            List<ResolveInfo> receivers) {
11692        ActivityInfo targetReceiver = null;
11693
11694        final int NR = receivers.size();
11695        for (int i = 0; i < NR; i++) {
11696            final ResolveInfo info = receivers.get(i);
11697            if (info.activityInfo == null) {
11698                continue;
11699            }
11700
11701            if (packageName.equals(info.activityInfo.packageName)) {
11702                targetReceiver = info.activityInfo;
11703                break;
11704            }
11705        }
11706
11707        if (targetReceiver == null) {
11708            return null;
11709        }
11710
11711        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11712    }
11713
11714    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11715            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11716        if (pkgInfo.verifiers.length == 0) {
11717            return null;
11718        }
11719
11720        final int N = pkgInfo.verifiers.length;
11721        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11722        for (int i = 0; i < N; i++) {
11723            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11724
11725            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11726                    receivers);
11727            if (comp == null) {
11728                continue;
11729            }
11730
11731            final int verifierUid = getUidForVerifier(verifierInfo);
11732            if (verifierUid == -1) {
11733                continue;
11734            }
11735
11736            if (DEBUG_VERIFY) {
11737                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11738                        + " with the correct signature");
11739            }
11740            sufficientVerifiers.add(comp);
11741            verificationState.addSufficientVerifier(verifierUid);
11742        }
11743
11744        return sufficientVerifiers;
11745    }
11746
11747    private int getUidForVerifier(VerifierInfo verifierInfo) {
11748        synchronized (mPackages) {
11749            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11750            if (pkg == null) {
11751                return -1;
11752            } else if (pkg.mSignatures.length != 1) {
11753                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11754                        + " has more than one signature; ignoring");
11755                return -1;
11756            }
11757
11758            /*
11759             * If the public key of the package's signature does not match
11760             * our expected public key, then this is a different package and
11761             * we should skip.
11762             */
11763
11764            final byte[] expectedPublicKey;
11765            try {
11766                final Signature verifierSig = pkg.mSignatures[0];
11767                final PublicKey publicKey = verifierSig.getPublicKey();
11768                expectedPublicKey = publicKey.getEncoded();
11769            } catch (CertificateException e) {
11770                return -1;
11771            }
11772
11773            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11774
11775            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11776                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11777                        + " does not have the expected public key; ignoring");
11778                return -1;
11779            }
11780
11781            return pkg.applicationInfo.uid;
11782        }
11783    }
11784
11785    @Override
11786    public void finishPackageInstall(int token, boolean didLaunch) {
11787        enforceSystemOrRoot("Only the system is allowed to finish installs");
11788
11789        if (DEBUG_INSTALL) {
11790            Slog.v(TAG, "BM finishing package install for " + token);
11791        }
11792        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11793
11794        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11795        mHandler.sendMessage(msg);
11796    }
11797
11798    /**
11799     * Get the verification agent timeout.
11800     *
11801     * @return verification timeout in milliseconds
11802     */
11803    private long getVerificationTimeout() {
11804        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11805                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11806                DEFAULT_VERIFICATION_TIMEOUT);
11807    }
11808
11809    /**
11810     * Get the default verification agent response code.
11811     *
11812     * @return default verification response code
11813     */
11814    private int getDefaultVerificationResponse() {
11815        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11816                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11817                DEFAULT_VERIFICATION_RESPONSE);
11818    }
11819
11820    /**
11821     * Check whether or not package verification has been enabled.
11822     *
11823     * @return true if verification should be performed
11824     */
11825    private boolean isVerificationEnabled(int userId, int installFlags) {
11826        if (!DEFAULT_VERIFY_ENABLE) {
11827            return false;
11828        }
11829        // Ephemeral apps don't get the full verification treatment
11830        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11831            if (DEBUG_EPHEMERAL) {
11832                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11833            }
11834            return false;
11835        }
11836
11837        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11838
11839        // Check if installing from ADB
11840        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11841            // Do not run verification in a test harness environment
11842            if (ActivityManager.isRunningInTestHarness()) {
11843                return false;
11844            }
11845            if (ensureVerifyAppsEnabled) {
11846                return true;
11847            }
11848            // Check if the developer does not want package verification for ADB installs
11849            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11850                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11851                return false;
11852            }
11853        }
11854
11855        if (ensureVerifyAppsEnabled) {
11856            return true;
11857        }
11858
11859        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11860                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11861    }
11862
11863    @Override
11864    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11865            throws RemoteException {
11866        mContext.enforceCallingOrSelfPermission(
11867                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11868                "Only intentfilter verification agents can verify applications");
11869
11870        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11871        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11872                Binder.getCallingUid(), verificationCode, failedDomains);
11873        msg.arg1 = id;
11874        msg.obj = response;
11875        mHandler.sendMessage(msg);
11876    }
11877
11878    @Override
11879    public int getIntentVerificationStatus(String packageName, int userId) {
11880        synchronized (mPackages) {
11881            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11882        }
11883    }
11884
11885    @Override
11886    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11887        mContext.enforceCallingOrSelfPermission(
11888                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11889
11890        boolean result = false;
11891        synchronized (mPackages) {
11892            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11893        }
11894        if (result) {
11895            scheduleWritePackageRestrictionsLocked(userId);
11896        }
11897        return result;
11898    }
11899
11900    @Override
11901    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11902            String packageName) {
11903        synchronized (mPackages) {
11904            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11905        }
11906    }
11907
11908    @Override
11909    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11910        if (TextUtils.isEmpty(packageName)) {
11911            return ParceledListSlice.emptyList();
11912        }
11913        synchronized (mPackages) {
11914            PackageParser.Package pkg = mPackages.get(packageName);
11915            if (pkg == null || pkg.activities == null) {
11916                return ParceledListSlice.emptyList();
11917            }
11918            final int count = pkg.activities.size();
11919            ArrayList<IntentFilter> result = new ArrayList<>();
11920            for (int n=0; n<count; n++) {
11921                PackageParser.Activity activity = pkg.activities.get(n);
11922                if (activity.intents != null && activity.intents.size() > 0) {
11923                    result.addAll(activity.intents);
11924                }
11925            }
11926            return new ParceledListSlice<>(result);
11927        }
11928    }
11929
11930    @Override
11931    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11932        mContext.enforceCallingOrSelfPermission(
11933                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11934
11935        synchronized (mPackages) {
11936            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11937            if (packageName != null) {
11938                result |= updateIntentVerificationStatus(packageName,
11939                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11940                        userId);
11941                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11942                        packageName, userId);
11943            }
11944            return result;
11945        }
11946    }
11947
11948    @Override
11949    public String getDefaultBrowserPackageName(int userId) {
11950        synchronized (mPackages) {
11951            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11952        }
11953    }
11954
11955    /**
11956     * Get the "allow unknown sources" setting.
11957     *
11958     * @return the current "allow unknown sources" setting
11959     */
11960    private int getUnknownSourcesSettings() {
11961        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11962                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11963                -1);
11964    }
11965
11966    @Override
11967    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11968        final int uid = Binder.getCallingUid();
11969        // writer
11970        synchronized (mPackages) {
11971            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11972            if (targetPackageSetting == null) {
11973                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11974            }
11975
11976            PackageSetting installerPackageSetting;
11977            if (installerPackageName != null) {
11978                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11979                if (installerPackageSetting == null) {
11980                    throw new IllegalArgumentException("Unknown installer package: "
11981                            + installerPackageName);
11982                }
11983            } else {
11984                installerPackageSetting = null;
11985            }
11986
11987            Signature[] callerSignature;
11988            Object obj = mSettings.getUserIdLPr(uid);
11989            if (obj != null) {
11990                if (obj instanceof SharedUserSetting) {
11991                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11992                } else if (obj instanceof PackageSetting) {
11993                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11994                } else {
11995                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11996                }
11997            } else {
11998                throw new SecurityException("Unknown calling UID: " + uid);
11999            }
12000
12001            // Verify: can't set installerPackageName to a package that is
12002            // not signed with the same cert as the caller.
12003            if (installerPackageSetting != null) {
12004                if (compareSignatures(callerSignature,
12005                        installerPackageSetting.signatures.mSignatures)
12006                        != PackageManager.SIGNATURE_MATCH) {
12007                    throw new SecurityException(
12008                            "Caller does not have same cert as new installer package "
12009                            + installerPackageName);
12010                }
12011            }
12012
12013            // Verify: if target already has an installer package, it must
12014            // be signed with the same cert as the caller.
12015            if (targetPackageSetting.installerPackageName != null) {
12016                PackageSetting setting = mSettings.mPackages.get(
12017                        targetPackageSetting.installerPackageName);
12018                // If the currently set package isn't valid, then it's always
12019                // okay to change it.
12020                if (setting != null) {
12021                    if (compareSignatures(callerSignature,
12022                            setting.signatures.mSignatures)
12023                            != PackageManager.SIGNATURE_MATCH) {
12024                        throw new SecurityException(
12025                                "Caller does not have same cert as old installer package "
12026                                + targetPackageSetting.installerPackageName);
12027                    }
12028                }
12029            }
12030
12031            // Okay!
12032            targetPackageSetting.installerPackageName = installerPackageName;
12033            if (installerPackageName != null) {
12034                mSettings.mInstallerPackages.add(installerPackageName);
12035            }
12036            scheduleWriteSettingsLocked();
12037        }
12038    }
12039
12040    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12041        // Queue up an async operation since the package installation may take a little while.
12042        mHandler.post(new Runnable() {
12043            public void run() {
12044                mHandler.removeCallbacks(this);
12045                 // Result object to be returned
12046                PackageInstalledInfo res = new PackageInstalledInfo();
12047                res.setReturnCode(currentStatus);
12048                res.uid = -1;
12049                res.pkg = null;
12050                res.removedInfo = null;
12051                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12052                    args.doPreInstall(res.returnCode);
12053                    synchronized (mInstallLock) {
12054                        installPackageTracedLI(args, res);
12055                    }
12056                    args.doPostInstall(res.returnCode, res.uid);
12057                }
12058
12059                // A restore should be performed at this point if (a) the install
12060                // succeeded, (b) the operation is not an update, and (c) the new
12061                // package has not opted out of backup participation.
12062                final boolean update = res.removedInfo != null
12063                        && res.removedInfo.removedPackage != null;
12064                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12065                boolean doRestore = !update
12066                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12067
12068                // Set up the post-install work request bookkeeping.  This will be used
12069                // and cleaned up by the post-install event handling regardless of whether
12070                // there's a restore pass performed.  Token values are >= 1.
12071                int token;
12072                if (mNextInstallToken < 0) mNextInstallToken = 1;
12073                token = mNextInstallToken++;
12074
12075                PostInstallData data = new PostInstallData(args, res);
12076                mRunningInstalls.put(token, data);
12077                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12078
12079                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12080                    // Pass responsibility to the Backup Manager.  It will perform a
12081                    // restore if appropriate, then pass responsibility back to the
12082                    // Package Manager to run the post-install observer callbacks
12083                    // and broadcasts.
12084                    IBackupManager bm = IBackupManager.Stub.asInterface(
12085                            ServiceManager.getService(Context.BACKUP_SERVICE));
12086                    if (bm != null) {
12087                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12088                                + " to BM for possible restore");
12089                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12090                        try {
12091                            // TODO: http://b/22388012
12092                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12093                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12094                            } else {
12095                                doRestore = false;
12096                            }
12097                        } catch (RemoteException e) {
12098                            // can't happen; the backup manager is local
12099                        } catch (Exception e) {
12100                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12101                            doRestore = false;
12102                        }
12103                    } else {
12104                        Slog.e(TAG, "Backup Manager not found!");
12105                        doRestore = false;
12106                    }
12107                }
12108
12109                if (!doRestore) {
12110                    // No restore possible, or the Backup Manager was mysteriously not
12111                    // available -- just fire the post-install work request directly.
12112                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12113
12114                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12115
12116                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12117                    mHandler.sendMessage(msg);
12118                }
12119            }
12120        });
12121    }
12122
12123    /**
12124     * Callback from PackageSettings whenever an app is first transitioned out of the
12125     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12126     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12127     * here whether the app is the target of an ongoing install, and only send the
12128     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12129     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12130     * handling.
12131     */
12132    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12133        // Serialize this with the rest of the install-process message chain.  In the
12134        // restore-at-install case, this Runnable will necessarily run before the
12135        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12136        // are coherent.  In the non-restore case, the app has already completed install
12137        // and been launched through some other means, so it is not in a problematic
12138        // state for observers to see the FIRST_LAUNCH signal.
12139        mHandler.post(new Runnable() {
12140            @Override
12141            public void run() {
12142                for (int i = 0; i < mRunningInstalls.size(); i++) {
12143                    final PostInstallData data = mRunningInstalls.valueAt(i);
12144                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12145                        // right package; but is it for the right user?
12146                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12147                            if (userId == data.res.newUsers[uIndex]) {
12148                                if (DEBUG_BACKUP) {
12149                                    Slog.i(TAG, "Package " + pkgName
12150                                            + " being restored so deferring FIRST_LAUNCH");
12151                                }
12152                                return;
12153                            }
12154                        }
12155                    }
12156                }
12157                // didn't find it, so not being restored
12158                if (DEBUG_BACKUP) {
12159                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12160                }
12161                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12162            }
12163        });
12164    }
12165
12166    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12167        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12168                installerPkg, null, userIds);
12169    }
12170
12171    private abstract class HandlerParams {
12172        private static final int MAX_RETRIES = 4;
12173
12174        /**
12175         * Number of times startCopy() has been attempted and had a non-fatal
12176         * error.
12177         */
12178        private int mRetries = 0;
12179
12180        /** User handle for the user requesting the information or installation. */
12181        private final UserHandle mUser;
12182        String traceMethod;
12183        int traceCookie;
12184
12185        HandlerParams(UserHandle user) {
12186            mUser = user;
12187        }
12188
12189        UserHandle getUser() {
12190            return mUser;
12191        }
12192
12193        HandlerParams setTraceMethod(String traceMethod) {
12194            this.traceMethod = traceMethod;
12195            return this;
12196        }
12197
12198        HandlerParams setTraceCookie(int traceCookie) {
12199            this.traceCookie = traceCookie;
12200            return this;
12201        }
12202
12203        final boolean startCopy() {
12204            boolean res;
12205            try {
12206                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12207
12208                if (++mRetries > MAX_RETRIES) {
12209                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12210                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12211                    handleServiceError();
12212                    return false;
12213                } else {
12214                    handleStartCopy();
12215                    res = true;
12216                }
12217            } catch (RemoteException e) {
12218                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12219                mHandler.sendEmptyMessage(MCS_RECONNECT);
12220                res = false;
12221            }
12222            handleReturnCode();
12223            return res;
12224        }
12225
12226        final void serviceError() {
12227            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12228            handleServiceError();
12229            handleReturnCode();
12230        }
12231
12232        abstract void handleStartCopy() throws RemoteException;
12233        abstract void handleServiceError();
12234        abstract void handleReturnCode();
12235    }
12236
12237    class MeasureParams extends HandlerParams {
12238        private final PackageStats mStats;
12239        private boolean mSuccess;
12240
12241        private final IPackageStatsObserver mObserver;
12242
12243        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12244            super(new UserHandle(stats.userHandle));
12245            mObserver = observer;
12246            mStats = stats;
12247        }
12248
12249        @Override
12250        public String toString() {
12251            return "MeasureParams{"
12252                + Integer.toHexString(System.identityHashCode(this))
12253                + " " + mStats.packageName + "}";
12254        }
12255
12256        @Override
12257        void handleStartCopy() throws RemoteException {
12258            synchronized (mInstallLock) {
12259                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12260            }
12261
12262            if (mSuccess) {
12263                final boolean mounted;
12264                if (Environment.isExternalStorageEmulated()) {
12265                    mounted = true;
12266                } else {
12267                    final String status = Environment.getExternalStorageState();
12268                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12269                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12270                }
12271
12272                if (mounted) {
12273                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12274
12275                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12276                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12277
12278                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12279                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12280
12281                    // Always subtract cache size, since it's a subdirectory
12282                    mStats.externalDataSize -= mStats.externalCacheSize;
12283
12284                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12285                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12286
12287                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12288                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12289                }
12290            }
12291        }
12292
12293        @Override
12294        void handleReturnCode() {
12295            if (mObserver != null) {
12296                try {
12297                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12298                } catch (RemoteException e) {
12299                    Slog.i(TAG, "Observer no longer exists.");
12300                }
12301            }
12302        }
12303
12304        @Override
12305        void handleServiceError() {
12306            Slog.e(TAG, "Could not measure application " + mStats.packageName
12307                            + " external storage");
12308        }
12309    }
12310
12311    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12312            throws RemoteException {
12313        long result = 0;
12314        for (File path : paths) {
12315            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12316        }
12317        return result;
12318    }
12319
12320    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12321        for (File path : paths) {
12322            try {
12323                mcs.clearDirectory(path.getAbsolutePath());
12324            } catch (RemoteException e) {
12325            }
12326        }
12327    }
12328
12329    static class OriginInfo {
12330        /**
12331         * Location where install is coming from, before it has been
12332         * copied/renamed into place. This could be a single monolithic APK
12333         * file, or a cluster directory. This location may be untrusted.
12334         */
12335        final File file;
12336        final String cid;
12337
12338        /**
12339         * Flag indicating that {@link #file} or {@link #cid} has already been
12340         * staged, meaning downstream users don't need to defensively copy the
12341         * contents.
12342         */
12343        final boolean staged;
12344
12345        /**
12346         * Flag indicating that {@link #file} or {@link #cid} is an already
12347         * installed app that is being moved.
12348         */
12349        final boolean existing;
12350
12351        final String resolvedPath;
12352        final File resolvedFile;
12353
12354        static OriginInfo fromNothing() {
12355            return new OriginInfo(null, null, false, false);
12356        }
12357
12358        static OriginInfo fromUntrustedFile(File file) {
12359            return new OriginInfo(file, null, false, false);
12360        }
12361
12362        static OriginInfo fromExistingFile(File file) {
12363            return new OriginInfo(file, null, false, true);
12364        }
12365
12366        static OriginInfo fromStagedFile(File file) {
12367            return new OriginInfo(file, null, true, false);
12368        }
12369
12370        static OriginInfo fromStagedContainer(String cid) {
12371            return new OriginInfo(null, cid, true, false);
12372        }
12373
12374        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12375            this.file = file;
12376            this.cid = cid;
12377            this.staged = staged;
12378            this.existing = existing;
12379
12380            if (cid != null) {
12381                resolvedPath = PackageHelper.getSdDir(cid);
12382                resolvedFile = new File(resolvedPath);
12383            } else if (file != null) {
12384                resolvedPath = file.getAbsolutePath();
12385                resolvedFile = file;
12386            } else {
12387                resolvedPath = null;
12388                resolvedFile = null;
12389            }
12390        }
12391    }
12392
12393    static class MoveInfo {
12394        final int moveId;
12395        final String fromUuid;
12396        final String toUuid;
12397        final String packageName;
12398        final String dataAppName;
12399        final int appId;
12400        final String seinfo;
12401        final int targetSdkVersion;
12402
12403        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12404                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12405            this.moveId = moveId;
12406            this.fromUuid = fromUuid;
12407            this.toUuid = toUuid;
12408            this.packageName = packageName;
12409            this.dataAppName = dataAppName;
12410            this.appId = appId;
12411            this.seinfo = seinfo;
12412            this.targetSdkVersion = targetSdkVersion;
12413        }
12414    }
12415
12416    static class VerificationInfo {
12417        /** A constant used to indicate that a uid value is not present. */
12418        public static final int NO_UID = -1;
12419
12420        /** URI referencing where the package was downloaded from. */
12421        final Uri originatingUri;
12422
12423        /** HTTP referrer URI associated with the originatingURI. */
12424        final Uri referrer;
12425
12426        /** UID of the application that the install request originated from. */
12427        final int originatingUid;
12428
12429        /** UID of application requesting the install */
12430        final int installerUid;
12431
12432        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12433            this.originatingUri = originatingUri;
12434            this.referrer = referrer;
12435            this.originatingUid = originatingUid;
12436            this.installerUid = installerUid;
12437        }
12438    }
12439
12440    class InstallParams extends HandlerParams {
12441        final OriginInfo origin;
12442        final MoveInfo move;
12443        final IPackageInstallObserver2 observer;
12444        int installFlags;
12445        final String installerPackageName;
12446        final String volumeUuid;
12447        private InstallArgs mArgs;
12448        private int mRet;
12449        final String packageAbiOverride;
12450        final String[] grantedRuntimePermissions;
12451        final VerificationInfo verificationInfo;
12452        final Certificate[][] certificates;
12453
12454        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12455                int installFlags, String installerPackageName, String volumeUuid,
12456                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12457                String[] grantedPermissions, Certificate[][] certificates) {
12458            super(user);
12459            this.origin = origin;
12460            this.move = move;
12461            this.observer = observer;
12462            this.installFlags = installFlags;
12463            this.installerPackageName = installerPackageName;
12464            this.volumeUuid = volumeUuid;
12465            this.verificationInfo = verificationInfo;
12466            this.packageAbiOverride = packageAbiOverride;
12467            this.grantedRuntimePermissions = grantedPermissions;
12468            this.certificates = certificates;
12469        }
12470
12471        @Override
12472        public String toString() {
12473            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12474                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12475        }
12476
12477        private int installLocationPolicy(PackageInfoLite pkgLite) {
12478            String packageName = pkgLite.packageName;
12479            int installLocation = pkgLite.installLocation;
12480            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12481            // reader
12482            synchronized (mPackages) {
12483                // Currently installed package which the new package is attempting to replace or
12484                // null if no such package is installed.
12485                PackageParser.Package installedPkg = mPackages.get(packageName);
12486                // Package which currently owns the data which the new package will own if installed.
12487                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12488                // will be null whereas dataOwnerPkg will contain information about the package
12489                // which was uninstalled while keeping its data.
12490                PackageParser.Package dataOwnerPkg = installedPkg;
12491                if (dataOwnerPkg  == null) {
12492                    PackageSetting ps = mSettings.mPackages.get(packageName);
12493                    if (ps != null) {
12494                        dataOwnerPkg = ps.pkg;
12495                    }
12496                }
12497
12498                if (dataOwnerPkg != null) {
12499                    // If installed, the package will get access to data left on the device by its
12500                    // predecessor. As a security measure, this is permited only if this is not a
12501                    // version downgrade or if the predecessor package is marked as debuggable and
12502                    // a downgrade is explicitly requested.
12503                    //
12504                    // On debuggable platform builds, downgrades are permitted even for
12505                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12506                    // not offer security guarantees and thus it's OK to disable some security
12507                    // mechanisms to make debugging/testing easier on those builds. However, even on
12508                    // debuggable builds downgrades of packages are permitted only if requested via
12509                    // installFlags. This is because we aim to keep the behavior of debuggable
12510                    // platform builds as close as possible to the behavior of non-debuggable
12511                    // platform builds.
12512                    final boolean downgradeRequested =
12513                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12514                    final boolean packageDebuggable =
12515                                (dataOwnerPkg.applicationInfo.flags
12516                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12517                    final boolean downgradePermitted =
12518                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12519                    if (!downgradePermitted) {
12520                        try {
12521                            checkDowngrade(dataOwnerPkg, pkgLite);
12522                        } catch (PackageManagerException e) {
12523                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12524                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12525                        }
12526                    }
12527                }
12528
12529                if (installedPkg != null) {
12530                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12531                        // Check for updated system application.
12532                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12533                            if (onSd) {
12534                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12535                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12536                            }
12537                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12538                        } else {
12539                            if (onSd) {
12540                                // Install flag overrides everything.
12541                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12542                            }
12543                            // If current upgrade specifies particular preference
12544                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12545                                // Application explicitly specified internal.
12546                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12547                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12548                                // App explictly prefers external. Let policy decide
12549                            } else {
12550                                // Prefer previous location
12551                                if (isExternal(installedPkg)) {
12552                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12553                                }
12554                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12555                            }
12556                        }
12557                    } else {
12558                        // Invalid install. Return error code
12559                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12560                    }
12561                }
12562            }
12563            // All the special cases have been taken care of.
12564            // Return result based on recommended install location.
12565            if (onSd) {
12566                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12567            }
12568            return pkgLite.recommendedInstallLocation;
12569        }
12570
12571        /*
12572         * Invoke remote method to get package information and install
12573         * location values. Override install location based on default
12574         * policy if needed and then create install arguments based
12575         * on the install location.
12576         */
12577        public void handleStartCopy() throws RemoteException {
12578            int ret = PackageManager.INSTALL_SUCCEEDED;
12579
12580            // If we're already staged, we've firmly committed to an install location
12581            if (origin.staged) {
12582                if (origin.file != null) {
12583                    installFlags |= PackageManager.INSTALL_INTERNAL;
12584                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12585                } else if (origin.cid != null) {
12586                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12587                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12588                } else {
12589                    throw new IllegalStateException("Invalid stage location");
12590                }
12591            }
12592
12593            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12594            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12595            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12596            PackageInfoLite pkgLite = null;
12597
12598            if (onInt && onSd) {
12599                // Check if both bits are set.
12600                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12601                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12602            } else if (onSd && ephemeral) {
12603                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12604                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12605            } else {
12606                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12607                        packageAbiOverride);
12608
12609                if (DEBUG_EPHEMERAL && ephemeral) {
12610                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12611                }
12612
12613                /*
12614                 * If we have too little free space, try to free cache
12615                 * before giving up.
12616                 */
12617                if (!origin.staged && pkgLite.recommendedInstallLocation
12618                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12619                    // TODO: focus freeing disk space on the target device
12620                    final StorageManager storage = StorageManager.from(mContext);
12621                    final long lowThreshold = storage.getStorageLowBytes(
12622                            Environment.getDataDirectory());
12623
12624                    final long sizeBytes = mContainerService.calculateInstalledSize(
12625                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12626
12627                    try {
12628                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12629                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12630                                installFlags, packageAbiOverride);
12631                    } catch (InstallerException e) {
12632                        Slog.w(TAG, "Failed to free cache", e);
12633                    }
12634
12635                    /*
12636                     * The cache free must have deleted the file we
12637                     * downloaded to install.
12638                     *
12639                     * TODO: fix the "freeCache" call to not delete
12640                     *       the file we care about.
12641                     */
12642                    if (pkgLite.recommendedInstallLocation
12643                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12644                        pkgLite.recommendedInstallLocation
12645                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12646                    }
12647                }
12648            }
12649
12650            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12651                int loc = pkgLite.recommendedInstallLocation;
12652                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12653                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12654                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12655                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12656                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12657                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12658                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12659                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12660                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12661                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12662                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12663                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12664                } else {
12665                    // Override with defaults if needed.
12666                    loc = installLocationPolicy(pkgLite);
12667                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12668                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12669                    } else if (!onSd && !onInt) {
12670                        // Override install location with flags
12671                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12672                            // Set the flag to install on external media.
12673                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12674                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12675                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12676                            if (DEBUG_EPHEMERAL) {
12677                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12678                            }
12679                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12680                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12681                                    |PackageManager.INSTALL_INTERNAL);
12682                        } else {
12683                            // Make sure the flag for installing on external
12684                            // media is unset
12685                            installFlags |= PackageManager.INSTALL_INTERNAL;
12686                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12687                        }
12688                    }
12689                }
12690            }
12691
12692            final InstallArgs args = createInstallArgs(this);
12693            mArgs = args;
12694
12695            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12696                // TODO: http://b/22976637
12697                // Apps installed for "all" users use the device owner to verify the app
12698                UserHandle verifierUser = getUser();
12699                if (verifierUser == UserHandle.ALL) {
12700                    verifierUser = UserHandle.SYSTEM;
12701                }
12702
12703                /*
12704                 * Determine if we have any installed package verifiers. If we
12705                 * do, then we'll defer to them to verify the packages.
12706                 */
12707                final int requiredUid = mRequiredVerifierPackage == null ? -1
12708                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12709                                verifierUser.getIdentifier());
12710                if (!origin.existing && requiredUid != -1
12711                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12712                    final Intent verification = new Intent(
12713                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12714                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12715                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12716                            PACKAGE_MIME_TYPE);
12717                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12718
12719                    // Query all live verifiers based on current user state
12720                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12721                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12722
12723                    if (DEBUG_VERIFY) {
12724                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12725                                + verification.toString() + " with " + pkgLite.verifiers.length
12726                                + " optional verifiers");
12727                    }
12728
12729                    final int verificationId = mPendingVerificationToken++;
12730
12731                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12732
12733                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12734                            installerPackageName);
12735
12736                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12737                            installFlags);
12738
12739                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12740                            pkgLite.packageName);
12741
12742                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12743                            pkgLite.versionCode);
12744
12745                    if (verificationInfo != null) {
12746                        if (verificationInfo.originatingUri != null) {
12747                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12748                                    verificationInfo.originatingUri);
12749                        }
12750                        if (verificationInfo.referrer != null) {
12751                            verification.putExtra(Intent.EXTRA_REFERRER,
12752                                    verificationInfo.referrer);
12753                        }
12754                        if (verificationInfo.originatingUid >= 0) {
12755                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12756                                    verificationInfo.originatingUid);
12757                        }
12758                        if (verificationInfo.installerUid >= 0) {
12759                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12760                                    verificationInfo.installerUid);
12761                        }
12762                    }
12763
12764                    final PackageVerificationState verificationState = new PackageVerificationState(
12765                            requiredUid, args);
12766
12767                    mPendingVerification.append(verificationId, verificationState);
12768
12769                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12770                            receivers, verificationState);
12771
12772                    /*
12773                     * If any sufficient verifiers were listed in the package
12774                     * manifest, attempt to ask them.
12775                     */
12776                    if (sufficientVerifiers != null) {
12777                        final int N = sufficientVerifiers.size();
12778                        if (N == 0) {
12779                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12780                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12781                        } else {
12782                            for (int i = 0; i < N; i++) {
12783                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12784
12785                                final Intent sufficientIntent = new Intent(verification);
12786                                sufficientIntent.setComponent(verifierComponent);
12787                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12788                            }
12789                        }
12790                    }
12791
12792                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12793                            mRequiredVerifierPackage, receivers);
12794                    if (ret == PackageManager.INSTALL_SUCCEEDED
12795                            && mRequiredVerifierPackage != null) {
12796                        Trace.asyncTraceBegin(
12797                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12798                        /*
12799                         * Send the intent to the required verification agent,
12800                         * but only start the verification timeout after the
12801                         * target BroadcastReceivers have run.
12802                         */
12803                        verification.setComponent(requiredVerifierComponent);
12804                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12805                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12806                                new BroadcastReceiver() {
12807                                    @Override
12808                                    public void onReceive(Context context, Intent intent) {
12809                                        final Message msg = mHandler
12810                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12811                                        msg.arg1 = verificationId;
12812                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12813                                    }
12814                                }, null, 0, null, null);
12815
12816                        /*
12817                         * We don't want the copy to proceed until verification
12818                         * succeeds, so null out this field.
12819                         */
12820                        mArgs = null;
12821                    }
12822                } else {
12823                    /*
12824                     * No package verification is enabled, so immediately start
12825                     * the remote call to initiate copy using temporary file.
12826                     */
12827                    ret = args.copyApk(mContainerService, true);
12828                }
12829            }
12830
12831            mRet = ret;
12832        }
12833
12834        @Override
12835        void handleReturnCode() {
12836            // If mArgs is null, then MCS couldn't be reached. When it
12837            // reconnects, it will try again to install. At that point, this
12838            // will succeed.
12839            if (mArgs != null) {
12840                processPendingInstall(mArgs, mRet);
12841            }
12842        }
12843
12844        @Override
12845        void handleServiceError() {
12846            mArgs = createInstallArgs(this);
12847            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12848        }
12849
12850        public boolean isForwardLocked() {
12851            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12852        }
12853    }
12854
12855    /**
12856     * Used during creation of InstallArgs
12857     *
12858     * @param installFlags package installation flags
12859     * @return true if should be installed on external storage
12860     */
12861    private static boolean installOnExternalAsec(int installFlags) {
12862        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12863            return false;
12864        }
12865        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12866            return true;
12867        }
12868        return false;
12869    }
12870
12871    /**
12872     * Used during creation of InstallArgs
12873     *
12874     * @param installFlags package installation flags
12875     * @return true if should be installed as forward locked
12876     */
12877    private static boolean installForwardLocked(int installFlags) {
12878        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12879    }
12880
12881    private InstallArgs createInstallArgs(InstallParams params) {
12882        if (params.move != null) {
12883            return new MoveInstallArgs(params);
12884        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12885            return new AsecInstallArgs(params);
12886        } else {
12887            return new FileInstallArgs(params);
12888        }
12889    }
12890
12891    /**
12892     * Create args that describe an existing installed package. Typically used
12893     * when cleaning up old installs, or used as a move source.
12894     */
12895    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12896            String resourcePath, String[] instructionSets) {
12897        final boolean isInAsec;
12898        if (installOnExternalAsec(installFlags)) {
12899            /* Apps on SD card are always in ASEC containers. */
12900            isInAsec = true;
12901        } else if (installForwardLocked(installFlags)
12902                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12903            /*
12904             * Forward-locked apps are only in ASEC containers if they're the
12905             * new style
12906             */
12907            isInAsec = true;
12908        } else {
12909            isInAsec = false;
12910        }
12911
12912        if (isInAsec) {
12913            return new AsecInstallArgs(codePath, instructionSets,
12914                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12915        } else {
12916            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12917        }
12918    }
12919
12920    static abstract class InstallArgs {
12921        /** @see InstallParams#origin */
12922        final OriginInfo origin;
12923        /** @see InstallParams#move */
12924        final MoveInfo move;
12925
12926        final IPackageInstallObserver2 observer;
12927        // Always refers to PackageManager flags only
12928        final int installFlags;
12929        final String installerPackageName;
12930        final String volumeUuid;
12931        final UserHandle user;
12932        final String abiOverride;
12933        final String[] installGrantPermissions;
12934        /** If non-null, drop an async trace when the install completes */
12935        final String traceMethod;
12936        final int traceCookie;
12937        final Certificate[][] certificates;
12938
12939        // The list of instruction sets supported by this app. This is currently
12940        // only used during the rmdex() phase to clean up resources. We can get rid of this
12941        // if we move dex files under the common app path.
12942        /* nullable */ String[] instructionSets;
12943
12944        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12945                int installFlags, String installerPackageName, String volumeUuid,
12946                UserHandle user, String[] instructionSets,
12947                String abiOverride, String[] installGrantPermissions,
12948                String traceMethod, int traceCookie, Certificate[][] certificates) {
12949            this.origin = origin;
12950            this.move = move;
12951            this.installFlags = installFlags;
12952            this.observer = observer;
12953            this.installerPackageName = installerPackageName;
12954            this.volumeUuid = volumeUuid;
12955            this.user = user;
12956            this.instructionSets = instructionSets;
12957            this.abiOverride = abiOverride;
12958            this.installGrantPermissions = installGrantPermissions;
12959            this.traceMethod = traceMethod;
12960            this.traceCookie = traceCookie;
12961            this.certificates = certificates;
12962        }
12963
12964        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12965        abstract int doPreInstall(int status);
12966
12967        /**
12968         * Rename package into final resting place. All paths on the given
12969         * scanned package should be updated to reflect the rename.
12970         */
12971        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12972        abstract int doPostInstall(int status, int uid);
12973
12974        /** @see PackageSettingBase#codePathString */
12975        abstract String getCodePath();
12976        /** @see PackageSettingBase#resourcePathString */
12977        abstract String getResourcePath();
12978
12979        // Need installer lock especially for dex file removal.
12980        abstract void cleanUpResourcesLI();
12981        abstract boolean doPostDeleteLI(boolean delete);
12982
12983        /**
12984         * Called before the source arguments are copied. This is used mostly
12985         * for MoveParams when it needs to read the source file to put it in the
12986         * destination.
12987         */
12988        int doPreCopy() {
12989            return PackageManager.INSTALL_SUCCEEDED;
12990        }
12991
12992        /**
12993         * Called after the source arguments are copied. This is used mostly for
12994         * MoveParams when it needs to read the source file to put it in the
12995         * destination.
12996         */
12997        int doPostCopy(int uid) {
12998            return PackageManager.INSTALL_SUCCEEDED;
12999        }
13000
13001        protected boolean isFwdLocked() {
13002            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13003        }
13004
13005        protected boolean isExternalAsec() {
13006            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13007        }
13008
13009        protected boolean isEphemeral() {
13010            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13011        }
13012
13013        UserHandle getUser() {
13014            return user;
13015        }
13016    }
13017
13018    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13019        if (!allCodePaths.isEmpty()) {
13020            if (instructionSets == null) {
13021                throw new IllegalStateException("instructionSet == null");
13022            }
13023            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13024            for (String codePath : allCodePaths) {
13025                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13026                    try {
13027                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13028                    } catch (InstallerException ignored) {
13029                    }
13030                }
13031            }
13032        }
13033    }
13034
13035    /**
13036     * Logic to handle installation of non-ASEC applications, including copying
13037     * and renaming logic.
13038     */
13039    class FileInstallArgs extends InstallArgs {
13040        private File codeFile;
13041        private File resourceFile;
13042
13043        // Example topology:
13044        // /data/app/com.example/base.apk
13045        // /data/app/com.example/split_foo.apk
13046        // /data/app/com.example/lib/arm/libfoo.so
13047        // /data/app/com.example/lib/arm64/libfoo.so
13048        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13049
13050        /** New install */
13051        FileInstallArgs(InstallParams params) {
13052            super(params.origin, params.move, params.observer, params.installFlags,
13053                    params.installerPackageName, params.volumeUuid,
13054                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13055                    params.grantedRuntimePermissions,
13056                    params.traceMethod, params.traceCookie, params.certificates);
13057            if (isFwdLocked()) {
13058                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13059            }
13060        }
13061
13062        /** Existing install */
13063        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13064            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13065                    null, null, null, 0, null /*certificates*/);
13066            this.codeFile = (codePath != null) ? new File(codePath) : null;
13067            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13068        }
13069
13070        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13071            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13072            try {
13073                return doCopyApk(imcs, temp);
13074            } finally {
13075                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13076            }
13077        }
13078
13079        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13080            if (origin.staged) {
13081                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13082                codeFile = origin.file;
13083                resourceFile = origin.file;
13084                return PackageManager.INSTALL_SUCCEEDED;
13085            }
13086
13087            try {
13088                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13089                final File tempDir =
13090                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13091                codeFile = tempDir;
13092                resourceFile = tempDir;
13093            } catch (IOException e) {
13094                Slog.w(TAG, "Failed to create copy file: " + e);
13095                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13096            }
13097
13098            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13099                @Override
13100                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13101                    if (!FileUtils.isValidExtFilename(name)) {
13102                        throw new IllegalArgumentException("Invalid filename: " + name);
13103                    }
13104                    try {
13105                        final File file = new File(codeFile, name);
13106                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13107                                O_RDWR | O_CREAT, 0644);
13108                        Os.chmod(file.getAbsolutePath(), 0644);
13109                        return new ParcelFileDescriptor(fd);
13110                    } catch (ErrnoException e) {
13111                        throw new RemoteException("Failed to open: " + e.getMessage());
13112                    }
13113                }
13114            };
13115
13116            int ret = PackageManager.INSTALL_SUCCEEDED;
13117            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13118            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13119                Slog.e(TAG, "Failed to copy package");
13120                return ret;
13121            }
13122
13123            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13124            NativeLibraryHelper.Handle handle = null;
13125            try {
13126                handle = NativeLibraryHelper.Handle.create(codeFile);
13127                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13128                        abiOverride);
13129            } catch (IOException e) {
13130                Slog.e(TAG, "Copying native libraries failed", e);
13131                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13132            } finally {
13133                IoUtils.closeQuietly(handle);
13134            }
13135
13136            return ret;
13137        }
13138
13139        int doPreInstall(int status) {
13140            if (status != PackageManager.INSTALL_SUCCEEDED) {
13141                cleanUp();
13142            }
13143            return status;
13144        }
13145
13146        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13147            if (status != PackageManager.INSTALL_SUCCEEDED) {
13148                cleanUp();
13149                return false;
13150            }
13151
13152            final File targetDir = codeFile.getParentFile();
13153            final File beforeCodeFile = codeFile;
13154            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13155
13156            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13157            try {
13158                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13159            } catch (ErrnoException e) {
13160                Slog.w(TAG, "Failed to rename", e);
13161                return false;
13162            }
13163
13164            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13165                Slog.w(TAG, "Failed to restorecon");
13166                return false;
13167            }
13168
13169            // Reflect the rename internally
13170            codeFile = afterCodeFile;
13171            resourceFile = afterCodeFile;
13172
13173            // Reflect the rename in scanned details
13174            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13175            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13176                    afterCodeFile, pkg.baseCodePath));
13177            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13178                    afterCodeFile, pkg.splitCodePaths));
13179
13180            // Reflect the rename in app info
13181            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13182            pkg.setApplicationInfoCodePath(pkg.codePath);
13183            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13184            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13185            pkg.setApplicationInfoResourcePath(pkg.codePath);
13186            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13187            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13188
13189            return true;
13190        }
13191
13192        int doPostInstall(int status, int uid) {
13193            if (status != PackageManager.INSTALL_SUCCEEDED) {
13194                cleanUp();
13195            }
13196            return status;
13197        }
13198
13199        @Override
13200        String getCodePath() {
13201            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13202        }
13203
13204        @Override
13205        String getResourcePath() {
13206            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13207        }
13208
13209        private boolean cleanUp() {
13210            if (codeFile == null || !codeFile.exists()) {
13211                return false;
13212            }
13213
13214            removeCodePathLI(codeFile);
13215
13216            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13217                resourceFile.delete();
13218            }
13219
13220            return true;
13221        }
13222
13223        void cleanUpResourcesLI() {
13224            // Try enumerating all code paths before deleting
13225            List<String> allCodePaths = Collections.EMPTY_LIST;
13226            if (codeFile != null && codeFile.exists()) {
13227                try {
13228                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13229                    allCodePaths = pkg.getAllCodePaths();
13230                } catch (PackageParserException e) {
13231                    // Ignored; we tried our best
13232                }
13233            }
13234
13235            cleanUp();
13236            removeDexFiles(allCodePaths, instructionSets);
13237        }
13238
13239        boolean doPostDeleteLI(boolean delete) {
13240            // XXX err, shouldn't we respect the delete flag?
13241            cleanUpResourcesLI();
13242            return true;
13243        }
13244    }
13245
13246    private boolean isAsecExternal(String cid) {
13247        final String asecPath = PackageHelper.getSdFilesystem(cid);
13248        return !asecPath.startsWith(mAsecInternalPath);
13249    }
13250
13251    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13252            PackageManagerException {
13253        if (copyRet < 0) {
13254            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13255                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13256                throw new PackageManagerException(copyRet, message);
13257            }
13258        }
13259    }
13260
13261    /**
13262     * Extract the MountService "container ID" from the full code path of an
13263     * .apk.
13264     */
13265    static String cidFromCodePath(String fullCodePath) {
13266        int eidx = fullCodePath.lastIndexOf("/");
13267        String subStr1 = fullCodePath.substring(0, eidx);
13268        int sidx = subStr1.lastIndexOf("/");
13269        return subStr1.substring(sidx+1, eidx);
13270    }
13271
13272    /**
13273     * Logic to handle installation of ASEC applications, including copying and
13274     * renaming logic.
13275     */
13276    class AsecInstallArgs extends InstallArgs {
13277        static final String RES_FILE_NAME = "pkg.apk";
13278        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13279
13280        String cid;
13281        String packagePath;
13282        String resourcePath;
13283
13284        /** New install */
13285        AsecInstallArgs(InstallParams params) {
13286            super(params.origin, params.move, params.observer, params.installFlags,
13287                    params.installerPackageName, params.volumeUuid,
13288                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13289                    params.grantedRuntimePermissions,
13290                    params.traceMethod, params.traceCookie, params.certificates);
13291        }
13292
13293        /** Existing install */
13294        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13295                        boolean isExternal, boolean isForwardLocked) {
13296            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13297              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13298                    instructionSets, null, null, null, 0, null /*certificates*/);
13299            // Hackily pretend we're still looking at a full code path
13300            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13301                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13302            }
13303
13304            // Extract cid from fullCodePath
13305            int eidx = fullCodePath.lastIndexOf("/");
13306            String subStr1 = fullCodePath.substring(0, eidx);
13307            int sidx = subStr1.lastIndexOf("/");
13308            cid = subStr1.substring(sidx+1, eidx);
13309            setMountPath(subStr1);
13310        }
13311
13312        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13313            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13314              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13315                    instructionSets, null, null, null, 0, null /*certificates*/);
13316            this.cid = cid;
13317            setMountPath(PackageHelper.getSdDir(cid));
13318        }
13319
13320        void createCopyFile() {
13321            cid = mInstallerService.allocateExternalStageCidLegacy();
13322        }
13323
13324        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13325            if (origin.staged && origin.cid != null) {
13326                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13327                cid = origin.cid;
13328                setMountPath(PackageHelper.getSdDir(cid));
13329                return PackageManager.INSTALL_SUCCEEDED;
13330            }
13331
13332            if (temp) {
13333                createCopyFile();
13334            } else {
13335                /*
13336                 * Pre-emptively destroy the container since it's destroyed if
13337                 * copying fails due to it existing anyway.
13338                 */
13339                PackageHelper.destroySdDir(cid);
13340            }
13341
13342            final String newMountPath = imcs.copyPackageToContainer(
13343                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13344                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13345
13346            if (newMountPath != null) {
13347                setMountPath(newMountPath);
13348                return PackageManager.INSTALL_SUCCEEDED;
13349            } else {
13350                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13351            }
13352        }
13353
13354        @Override
13355        String getCodePath() {
13356            return packagePath;
13357        }
13358
13359        @Override
13360        String getResourcePath() {
13361            return resourcePath;
13362        }
13363
13364        int doPreInstall(int status) {
13365            if (status != PackageManager.INSTALL_SUCCEEDED) {
13366                // Destroy container
13367                PackageHelper.destroySdDir(cid);
13368            } else {
13369                boolean mounted = PackageHelper.isContainerMounted(cid);
13370                if (!mounted) {
13371                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13372                            Process.SYSTEM_UID);
13373                    if (newMountPath != null) {
13374                        setMountPath(newMountPath);
13375                    } else {
13376                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13377                    }
13378                }
13379            }
13380            return status;
13381        }
13382
13383        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13384            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13385            String newMountPath = null;
13386            if (PackageHelper.isContainerMounted(cid)) {
13387                // Unmount the container
13388                if (!PackageHelper.unMountSdDir(cid)) {
13389                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13390                    return false;
13391                }
13392            }
13393            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13394                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13395                        " which might be stale. Will try to clean up.");
13396                // Clean up the stale container and proceed to recreate.
13397                if (!PackageHelper.destroySdDir(newCacheId)) {
13398                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13399                    return false;
13400                }
13401                // Successfully cleaned up stale container. Try to rename again.
13402                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13403                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13404                            + " inspite of cleaning it up.");
13405                    return false;
13406                }
13407            }
13408            if (!PackageHelper.isContainerMounted(newCacheId)) {
13409                Slog.w(TAG, "Mounting container " + newCacheId);
13410                newMountPath = PackageHelper.mountSdDir(newCacheId,
13411                        getEncryptKey(), Process.SYSTEM_UID);
13412            } else {
13413                newMountPath = PackageHelper.getSdDir(newCacheId);
13414            }
13415            if (newMountPath == null) {
13416                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13417                return false;
13418            }
13419            Log.i(TAG, "Succesfully renamed " + cid +
13420                    " to " + newCacheId +
13421                    " at new path: " + newMountPath);
13422            cid = newCacheId;
13423
13424            final File beforeCodeFile = new File(packagePath);
13425            setMountPath(newMountPath);
13426            final File afterCodeFile = new File(packagePath);
13427
13428            // Reflect the rename in scanned details
13429            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13430            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13431                    afterCodeFile, pkg.baseCodePath));
13432            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13433                    afterCodeFile, pkg.splitCodePaths));
13434
13435            // Reflect the rename in app info
13436            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13437            pkg.setApplicationInfoCodePath(pkg.codePath);
13438            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13439            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13440            pkg.setApplicationInfoResourcePath(pkg.codePath);
13441            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13442            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13443
13444            return true;
13445        }
13446
13447        private void setMountPath(String mountPath) {
13448            final File mountFile = new File(mountPath);
13449
13450            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13451            if (monolithicFile.exists()) {
13452                packagePath = monolithicFile.getAbsolutePath();
13453                if (isFwdLocked()) {
13454                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13455                } else {
13456                    resourcePath = packagePath;
13457                }
13458            } else {
13459                packagePath = mountFile.getAbsolutePath();
13460                resourcePath = packagePath;
13461            }
13462        }
13463
13464        int doPostInstall(int status, int uid) {
13465            if (status != PackageManager.INSTALL_SUCCEEDED) {
13466                cleanUp();
13467            } else {
13468                final int groupOwner;
13469                final String protectedFile;
13470                if (isFwdLocked()) {
13471                    groupOwner = UserHandle.getSharedAppGid(uid);
13472                    protectedFile = RES_FILE_NAME;
13473                } else {
13474                    groupOwner = -1;
13475                    protectedFile = null;
13476                }
13477
13478                if (uid < Process.FIRST_APPLICATION_UID
13479                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13480                    Slog.e(TAG, "Failed to finalize " + cid);
13481                    PackageHelper.destroySdDir(cid);
13482                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13483                }
13484
13485                boolean mounted = PackageHelper.isContainerMounted(cid);
13486                if (!mounted) {
13487                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13488                }
13489            }
13490            return status;
13491        }
13492
13493        private void cleanUp() {
13494            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13495
13496            // Destroy secure container
13497            PackageHelper.destroySdDir(cid);
13498        }
13499
13500        private List<String> getAllCodePaths() {
13501            final File codeFile = new File(getCodePath());
13502            if (codeFile != null && codeFile.exists()) {
13503                try {
13504                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13505                    return pkg.getAllCodePaths();
13506                } catch (PackageParserException e) {
13507                    // Ignored; we tried our best
13508                }
13509            }
13510            return Collections.EMPTY_LIST;
13511        }
13512
13513        void cleanUpResourcesLI() {
13514            // Enumerate all code paths before deleting
13515            cleanUpResourcesLI(getAllCodePaths());
13516        }
13517
13518        private void cleanUpResourcesLI(List<String> allCodePaths) {
13519            cleanUp();
13520            removeDexFiles(allCodePaths, instructionSets);
13521        }
13522
13523        String getPackageName() {
13524            return getAsecPackageName(cid);
13525        }
13526
13527        boolean doPostDeleteLI(boolean delete) {
13528            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13529            final List<String> allCodePaths = getAllCodePaths();
13530            boolean mounted = PackageHelper.isContainerMounted(cid);
13531            if (mounted) {
13532                // Unmount first
13533                if (PackageHelper.unMountSdDir(cid)) {
13534                    mounted = false;
13535                }
13536            }
13537            if (!mounted && delete) {
13538                cleanUpResourcesLI(allCodePaths);
13539            }
13540            return !mounted;
13541        }
13542
13543        @Override
13544        int doPreCopy() {
13545            if (isFwdLocked()) {
13546                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13547                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13548                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13549                }
13550            }
13551
13552            return PackageManager.INSTALL_SUCCEEDED;
13553        }
13554
13555        @Override
13556        int doPostCopy(int uid) {
13557            if (isFwdLocked()) {
13558                if (uid < Process.FIRST_APPLICATION_UID
13559                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13560                                RES_FILE_NAME)) {
13561                    Slog.e(TAG, "Failed to finalize " + cid);
13562                    PackageHelper.destroySdDir(cid);
13563                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13564                }
13565            }
13566
13567            return PackageManager.INSTALL_SUCCEEDED;
13568        }
13569    }
13570
13571    /**
13572     * Logic to handle movement of existing installed applications.
13573     */
13574    class MoveInstallArgs extends InstallArgs {
13575        private File codeFile;
13576        private File resourceFile;
13577
13578        /** New install */
13579        MoveInstallArgs(InstallParams params) {
13580            super(params.origin, params.move, params.observer, params.installFlags,
13581                    params.installerPackageName, params.volumeUuid,
13582                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13583                    params.grantedRuntimePermissions,
13584                    params.traceMethod, params.traceCookie, params.certificates);
13585        }
13586
13587        int copyApk(IMediaContainerService imcs, boolean temp) {
13588            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13589                    + move.fromUuid + " to " + move.toUuid);
13590            synchronized (mInstaller) {
13591                try {
13592                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13593                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13594                } catch (InstallerException e) {
13595                    Slog.w(TAG, "Failed to move app", e);
13596                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13597                }
13598            }
13599
13600            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13601            resourceFile = codeFile;
13602            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13603
13604            return PackageManager.INSTALL_SUCCEEDED;
13605        }
13606
13607        int doPreInstall(int status) {
13608            if (status != PackageManager.INSTALL_SUCCEEDED) {
13609                cleanUp(move.toUuid);
13610            }
13611            return status;
13612        }
13613
13614        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13615            if (status != PackageManager.INSTALL_SUCCEEDED) {
13616                cleanUp(move.toUuid);
13617                return false;
13618            }
13619
13620            // Reflect the move in app info
13621            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13622            pkg.setApplicationInfoCodePath(pkg.codePath);
13623            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13624            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13625            pkg.setApplicationInfoResourcePath(pkg.codePath);
13626            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13627            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13628
13629            return true;
13630        }
13631
13632        int doPostInstall(int status, int uid) {
13633            if (status == PackageManager.INSTALL_SUCCEEDED) {
13634                cleanUp(move.fromUuid);
13635            } else {
13636                cleanUp(move.toUuid);
13637            }
13638            return status;
13639        }
13640
13641        @Override
13642        String getCodePath() {
13643            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13644        }
13645
13646        @Override
13647        String getResourcePath() {
13648            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13649        }
13650
13651        private boolean cleanUp(String volumeUuid) {
13652            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13653                    move.dataAppName);
13654            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13655            final int[] userIds = sUserManager.getUserIds();
13656            synchronized (mInstallLock) {
13657                // Clean up both app data and code
13658                // All package moves are frozen until finished
13659                for (int userId : userIds) {
13660                    try {
13661                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13662                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13663                    } catch (InstallerException e) {
13664                        Slog.w(TAG, String.valueOf(e));
13665                    }
13666                }
13667                removeCodePathLI(codeFile);
13668            }
13669            return true;
13670        }
13671
13672        void cleanUpResourcesLI() {
13673            throw new UnsupportedOperationException();
13674        }
13675
13676        boolean doPostDeleteLI(boolean delete) {
13677            throw new UnsupportedOperationException();
13678        }
13679    }
13680
13681    static String getAsecPackageName(String packageCid) {
13682        int idx = packageCid.lastIndexOf("-");
13683        if (idx == -1) {
13684            return packageCid;
13685        }
13686        return packageCid.substring(0, idx);
13687    }
13688
13689    // Utility method used to create code paths based on package name and available index.
13690    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13691        String idxStr = "";
13692        int idx = 1;
13693        // Fall back to default value of idx=1 if prefix is not
13694        // part of oldCodePath
13695        if (oldCodePath != null) {
13696            String subStr = oldCodePath;
13697            // Drop the suffix right away
13698            if (suffix != null && subStr.endsWith(suffix)) {
13699                subStr = subStr.substring(0, subStr.length() - suffix.length());
13700            }
13701            // If oldCodePath already contains prefix find out the
13702            // ending index to either increment or decrement.
13703            int sidx = subStr.lastIndexOf(prefix);
13704            if (sidx != -1) {
13705                subStr = subStr.substring(sidx + prefix.length());
13706                if (subStr != null) {
13707                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13708                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13709                    }
13710                    try {
13711                        idx = Integer.parseInt(subStr);
13712                        if (idx <= 1) {
13713                            idx++;
13714                        } else {
13715                            idx--;
13716                        }
13717                    } catch(NumberFormatException e) {
13718                    }
13719                }
13720            }
13721        }
13722        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13723        return prefix + idxStr;
13724    }
13725
13726    private File getNextCodePath(File targetDir, String packageName) {
13727        int suffix = 1;
13728        File result;
13729        do {
13730            result = new File(targetDir, packageName + "-" + suffix);
13731            suffix++;
13732        } while (result.exists());
13733        return result;
13734    }
13735
13736    // Utility method that returns the relative package path with respect
13737    // to the installation directory. Like say for /data/data/com.test-1.apk
13738    // string com.test-1 is returned.
13739    static String deriveCodePathName(String codePath) {
13740        if (codePath == null) {
13741            return null;
13742        }
13743        final File codeFile = new File(codePath);
13744        final String name = codeFile.getName();
13745        if (codeFile.isDirectory()) {
13746            return name;
13747        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13748            final int lastDot = name.lastIndexOf('.');
13749            return name.substring(0, lastDot);
13750        } else {
13751            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13752            return null;
13753        }
13754    }
13755
13756    static class PackageInstalledInfo {
13757        String name;
13758        int uid;
13759        // The set of users that originally had this package installed.
13760        int[] origUsers;
13761        // The set of users that now have this package installed.
13762        int[] newUsers;
13763        PackageParser.Package pkg;
13764        int returnCode;
13765        String returnMsg;
13766        PackageRemovedInfo removedInfo;
13767        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13768
13769        public void setError(int code, String msg) {
13770            setReturnCode(code);
13771            setReturnMessage(msg);
13772            Slog.w(TAG, msg);
13773        }
13774
13775        public void setError(String msg, PackageParserException e) {
13776            setReturnCode(e.error);
13777            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13778            Slog.w(TAG, msg, e);
13779        }
13780
13781        public void setError(String msg, PackageManagerException e) {
13782            returnCode = e.error;
13783            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13784            Slog.w(TAG, msg, e);
13785        }
13786
13787        public void setReturnCode(int returnCode) {
13788            this.returnCode = returnCode;
13789            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13790            for (int i = 0; i < childCount; i++) {
13791                addedChildPackages.valueAt(i).returnCode = returnCode;
13792            }
13793        }
13794
13795        private void setReturnMessage(String returnMsg) {
13796            this.returnMsg = returnMsg;
13797            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13798            for (int i = 0; i < childCount; i++) {
13799                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13800            }
13801        }
13802
13803        // In some error cases we want to convey more info back to the observer
13804        String origPackage;
13805        String origPermission;
13806    }
13807
13808    /*
13809     * Install a non-existing package.
13810     */
13811    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13812            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13813            PackageInstalledInfo res) {
13814        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13815
13816        // Remember this for later, in case we need to rollback this install
13817        String pkgName = pkg.packageName;
13818
13819        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13820
13821        synchronized(mPackages) {
13822            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13823                // A package with the same name is already installed, though
13824                // it has been renamed to an older name.  The package we
13825                // are trying to install should be installed as an update to
13826                // the existing one, but that has not been requested, so bail.
13827                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13828                        + " without first uninstalling package running as "
13829                        + mSettings.mRenamedPackages.get(pkgName));
13830                return;
13831            }
13832            if (mPackages.containsKey(pkgName)) {
13833                // Don't allow installation over an existing package with the same name.
13834                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13835                        + " without first uninstalling.");
13836                return;
13837            }
13838        }
13839
13840        try {
13841            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
13842                    System.currentTimeMillis(), user);
13843
13844            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13845
13846            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13847                prepareAppDataAfterInstallLIF(newPackage);
13848
13849            } else {
13850                // Remove package from internal structures, but keep around any
13851                // data that might have already existed
13852                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
13853                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13854            }
13855        } catch (PackageManagerException e) {
13856            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13857        }
13858
13859        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13860    }
13861
13862    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13863        // Can't rotate keys during boot or if sharedUser.
13864        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13865                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13866            return false;
13867        }
13868        // app is using upgradeKeySets; make sure all are valid
13869        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13870        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13871        for (int i = 0; i < upgradeKeySets.length; i++) {
13872            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13873                Slog.wtf(TAG, "Package "
13874                         + (oldPs.name != null ? oldPs.name : "<null>")
13875                         + " contains upgrade-key-set reference to unknown key-set: "
13876                         + upgradeKeySets[i]
13877                         + " reverting to signatures check.");
13878                return false;
13879            }
13880        }
13881        return true;
13882    }
13883
13884    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13885        // Upgrade keysets are being used.  Determine if new package has a superset of the
13886        // required keys.
13887        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13888        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13889        for (int i = 0; i < upgradeKeySets.length; i++) {
13890            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13891            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13892                return true;
13893            }
13894        }
13895        return false;
13896    }
13897
13898    private static void updateDigest(MessageDigest digest, File file) throws IOException {
13899        try (DigestInputStream digestStream =
13900                new DigestInputStream(new FileInputStream(file), digest)) {
13901            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
13902        }
13903    }
13904
13905    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
13906            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13907        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13908
13909        final PackageParser.Package oldPackage;
13910        final String pkgName = pkg.packageName;
13911        final int[] allUsers;
13912        final int[] installedUsers;
13913
13914        synchronized(mPackages) {
13915            oldPackage = mPackages.get(pkgName);
13916            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13917
13918            // don't allow upgrade to target a release SDK from a pre-release SDK
13919            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
13920                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13921            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
13922                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
13923            if (oldTargetsPreRelease
13924                    && !newTargetsPreRelease
13925                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
13926                Slog.w(TAG, "Can't install package targeting released sdk");
13927                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
13928                return;
13929            }
13930
13931            // don't allow an upgrade from full to ephemeral
13932            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13933            if (isEphemeral && !oldIsEphemeral) {
13934                // can't downgrade from full to ephemeral
13935                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13936                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13937                return;
13938            }
13939
13940            // verify signatures are valid
13941            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13942            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13943                if (!checkUpgradeKeySetLP(ps, pkg)) {
13944                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13945                            "New package not signed by keys specified by upgrade-keysets: "
13946                                    + pkgName);
13947                    return;
13948                }
13949            } else {
13950                // default to original signature matching
13951                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13952                        != PackageManager.SIGNATURE_MATCH) {
13953                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13954                            "New package has a different signature: " + pkgName);
13955                    return;
13956                }
13957            }
13958
13959            // don't allow a system upgrade unless the upgrade hash matches
13960            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
13961                byte[] digestBytes = null;
13962                try {
13963                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
13964                    updateDigest(digest, new File(pkg.baseCodePath));
13965                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
13966                        for (String path : pkg.splitCodePaths) {
13967                            updateDigest(digest, new File(path));
13968                        }
13969                    }
13970                    digestBytes = digest.digest();
13971                } catch (NoSuchAlgorithmException | IOException e) {
13972                    res.setError(INSTALL_FAILED_INVALID_APK,
13973                            "Could not compute hash: " + pkgName);
13974                    return;
13975                }
13976                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
13977                    res.setError(INSTALL_FAILED_INVALID_APK,
13978                            "New package fails restrict-update check: " + pkgName);
13979                    return;
13980                }
13981                // retain upgrade restriction
13982                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
13983            }
13984
13985            // Check for shared user id changes
13986            String invalidPackageName =
13987                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
13988            if (invalidPackageName != null) {
13989                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13990                        "Package " + invalidPackageName + " tried to change user "
13991                                + oldPackage.mSharedUserId);
13992                return;
13993            }
13994
13995            // In case of rollback, remember per-user/profile install state
13996            allUsers = sUserManager.getUserIds();
13997            installedUsers = ps.queryInstalledUsers(allUsers, true);
13998        }
13999
14000        // Update what is removed
14001        res.removedInfo = new PackageRemovedInfo();
14002        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14003        res.removedInfo.removedPackage = oldPackage.packageName;
14004        res.removedInfo.isUpdate = true;
14005        res.removedInfo.origUsers = installedUsers;
14006        final int childCount = (oldPackage.childPackages != null)
14007                ? oldPackage.childPackages.size() : 0;
14008        for (int i = 0; i < childCount; i++) {
14009            boolean childPackageUpdated = false;
14010            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14011            if (res.addedChildPackages != null) {
14012                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14013                if (childRes != null) {
14014                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14015                    childRes.removedInfo.removedPackage = childPkg.packageName;
14016                    childRes.removedInfo.isUpdate = true;
14017                    childPackageUpdated = true;
14018                }
14019            }
14020            if (!childPackageUpdated) {
14021                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14022                childRemovedRes.removedPackage = childPkg.packageName;
14023                childRemovedRes.isUpdate = false;
14024                childRemovedRes.dataRemoved = true;
14025                synchronized (mPackages) {
14026                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14027                    if (childPs != null) {
14028                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14029                    }
14030                }
14031                if (res.removedInfo.removedChildPackages == null) {
14032                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14033                }
14034                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14035            }
14036        }
14037
14038        boolean sysPkg = (isSystemApp(oldPackage));
14039        if (sysPkg) {
14040            // Set the system/privileged flags as needed
14041            final boolean privileged =
14042                    (oldPackage.applicationInfo.privateFlags
14043                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14044            final int systemPolicyFlags = policyFlags
14045                    | PackageParser.PARSE_IS_SYSTEM
14046                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14047
14048            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14049                    user, allUsers, installerPackageName, res);
14050        } else {
14051            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14052                    user, allUsers, installerPackageName, res);
14053        }
14054    }
14055
14056    public List<String> getPreviousCodePaths(String packageName) {
14057        final PackageSetting ps = mSettings.mPackages.get(packageName);
14058        final List<String> result = new ArrayList<String>();
14059        if (ps != null && ps.oldCodePaths != null) {
14060            result.addAll(ps.oldCodePaths);
14061        }
14062        return result;
14063    }
14064
14065    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14066            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14067            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14068        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14069                + deletedPackage);
14070
14071        String pkgName = deletedPackage.packageName;
14072        boolean deletedPkg = true;
14073        boolean addedPkg = false;
14074        boolean updatedSettings = false;
14075        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14076        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14077                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14078
14079        final long origUpdateTime = (pkg.mExtras != null)
14080                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14081
14082        // First delete the existing package while retaining the data directory
14083        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14084                res.removedInfo, true, pkg)) {
14085            // If the existing package wasn't successfully deleted
14086            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14087            deletedPkg = false;
14088        } else {
14089            // Successfully deleted the old package; proceed with replace.
14090
14091            // If deleted package lived in a container, give users a chance to
14092            // relinquish resources before killing.
14093            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14094                if (DEBUG_INSTALL) {
14095                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14096                }
14097                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14098                final ArrayList<String> pkgList = new ArrayList<String>(1);
14099                pkgList.add(deletedPackage.applicationInfo.packageName);
14100                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14101            }
14102
14103            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14104                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14105            clearAppProfilesLIF(pkg);
14106
14107            try {
14108                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14109                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14110                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14111
14112                // Update the in-memory copy of the previous code paths.
14113                PackageSetting ps = mSettings.mPackages.get(pkgName);
14114                if (!killApp) {
14115                    if (ps.oldCodePaths == null) {
14116                        ps.oldCodePaths = new ArraySet<>();
14117                    }
14118                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14119                    if (deletedPackage.splitCodePaths != null) {
14120                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14121                    }
14122                } else {
14123                    ps.oldCodePaths = null;
14124                }
14125                if (ps.childPackageNames != null) {
14126                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14127                        final String childPkgName = ps.childPackageNames.get(i);
14128                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14129                        childPs.oldCodePaths = ps.oldCodePaths;
14130                    }
14131                }
14132                prepareAppDataAfterInstallLIF(newPackage);
14133                addedPkg = true;
14134            } catch (PackageManagerException e) {
14135                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14136            }
14137        }
14138
14139        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14140            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14141
14142            // Revert all internal state mutations and added folders for the failed install
14143            if (addedPkg) {
14144                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14145                        res.removedInfo, true, null);
14146            }
14147
14148            // Restore the old package
14149            if (deletedPkg) {
14150                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14151                File restoreFile = new File(deletedPackage.codePath);
14152                // Parse old package
14153                boolean oldExternal = isExternal(deletedPackage);
14154                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14155                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14156                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14157                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14158                try {
14159                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14160                            null);
14161                } catch (PackageManagerException e) {
14162                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14163                            + e.getMessage());
14164                    return;
14165                }
14166
14167                synchronized (mPackages) {
14168                    // Ensure the installer package name up to date
14169                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14170
14171                    // Update permissions for restored package
14172                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14173
14174                    mSettings.writeLPr();
14175                }
14176
14177                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14178            }
14179        } else {
14180            synchronized (mPackages) {
14181                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14182                if (ps != null) {
14183                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14184                    if (res.removedInfo.removedChildPackages != null) {
14185                        final int childCount = res.removedInfo.removedChildPackages.size();
14186                        // Iterate in reverse as we may modify the collection
14187                        for (int i = childCount - 1; i >= 0; i--) {
14188                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14189                            if (res.addedChildPackages.containsKey(childPackageName)) {
14190                                res.removedInfo.removedChildPackages.removeAt(i);
14191                            } else {
14192                                PackageRemovedInfo childInfo = res.removedInfo
14193                                        .removedChildPackages.valueAt(i);
14194                                childInfo.removedForAllUsers = mPackages.get(
14195                                        childInfo.removedPackage) == null;
14196                            }
14197                        }
14198                    }
14199                }
14200            }
14201        }
14202    }
14203
14204    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14205            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14206            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14207        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14208                + ", old=" + deletedPackage);
14209
14210        final boolean disabledSystem;
14211
14212        // Remove existing system package
14213        removePackageLI(deletedPackage, true);
14214
14215        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14216        if (!disabledSystem) {
14217            // We didn't need to disable the .apk as a current system package,
14218            // which means we are replacing another update that is already
14219            // installed.  We need to make sure to delete the older one's .apk.
14220            res.removedInfo.args = createInstallArgsForExisting(0,
14221                    deletedPackage.applicationInfo.getCodePath(),
14222                    deletedPackage.applicationInfo.getResourcePath(),
14223                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14224        } else {
14225            res.removedInfo.args = null;
14226        }
14227
14228        // Successfully disabled the old package. Now proceed with re-installation
14229        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14230                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14231        clearAppProfilesLIF(pkg);
14232
14233        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14234        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14235                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14236
14237        PackageParser.Package newPackage = null;
14238        try {
14239            // Add the package to the internal data structures
14240            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14241
14242            // Set the update and install times
14243            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14244            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14245                    System.currentTimeMillis());
14246
14247            // Update the package dynamic state if succeeded
14248            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14249                // Now that the install succeeded make sure we remove data
14250                // directories for any child package the update removed.
14251                final int deletedChildCount = (deletedPackage.childPackages != null)
14252                        ? deletedPackage.childPackages.size() : 0;
14253                final int newChildCount = (newPackage.childPackages != null)
14254                        ? newPackage.childPackages.size() : 0;
14255                for (int i = 0; i < deletedChildCount; i++) {
14256                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14257                    boolean childPackageDeleted = true;
14258                    for (int j = 0; j < newChildCount; j++) {
14259                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14260                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14261                            childPackageDeleted = false;
14262                            break;
14263                        }
14264                    }
14265                    if (childPackageDeleted) {
14266                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14267                                deletedChildPkg.packageName);
14268                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14269                            PackageRemovedInfo removedChildRes = res.removedInfo
14270                                    .removedChildPackages.get(deletedChildPkg.packageName);
14271                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14272                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14273                        }
14274                    }
14275                }
14276
14277                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14278                prepareAppDataAfterInstallLIF(newPackage);
14279            }
14280        } catch (PackageManagerException e) {
14281            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14282            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14283        }
14284
14285        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14286            // Re installation failed. Restore old information
14287            // Remove new pkg information
14288            if (newPackage != null) {
14289                removeInstalledPackageLI(newPackage, true);
14290            }
14291            // Add back the old system package
14292            try {
14293                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14294            } catch (PackageManagerException e) {
14295                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14296            }
14297
14298            synchronized (mPackages) {
14299                if (disabledSystem) {
14300                    enableSystemPackageLPw(deletedPackage);
14301                }
14302
14303                // Ensure the installer package name up to date
14304                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14305
14306                // Update permissions for restored package
14307                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14308
14309                mSettings.writeLPr();
14310            }
14311
14312            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14313                    + " after failed upgrade");
14314        }
14315    }
14316
14317    /**
14318     * Checks whether the parent or any of the child packages have a change shared
14319     * user. For a package to be a valid update the shred users of the parent and
14320     * the children should match. We may later support changing child shared users.
14321     * @param oldPkg The updated package.
14322     * @param newPkg The update package.
14323     * @return The shared user that change between the versions.
14324     */
14325    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14326            PackageParser.Package newPkg) {
14327        // Check parent shared user
14328        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14329            return newPkg.packageName;
14330        }
14331        // Check child shared users
14332        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14333        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14334        for (int i = 0; i < newChildCount; i++) {
14335            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14336            // If this child was present, did it have the same shared user?
14337            for (int j = 0; j < oldChildCount; j++) {
14338                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14339                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14340                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14341                    return newChildPkg.packageName;
14342                }
14343            }
14344        }
14345        return null;
14346    }
14347
14348    private void removeNativeBinariesLI(PackageSetting ps) {
14349        // Remove the lib path for the parent package
14350        if (ps != null) {
14351            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14352            // Remove the lib path for the child packages
14353            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14354            for (int i = 0; i < childCount; i++) {
14355                PackageSetting childPs = null;
14356                synchronized (mPackages) {
14357                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14358                }
14359                if (childPs != null) {
14360                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14361                            .legacyNativeLibraryPathString);
14362                }
14363            }
14364        }
14365    }
14366
14367    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14368        // Enable the parent package
14369        mSettings.enableSystemPackageLPw(pkg.packageName);
14370        // Enable the child packages
14371        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14372        for (int i = 0; i < childCount; i++) {
14373            PackageParser.Package childPkg = pkg.childPackages.get(i);
14374            mSettings.enableSystemPackageLPw(childPkg.packageName);
14375        }
14376    }
14377
14378    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14379            PackageParser.Package newPkg) {
14380        // Disable the parent package (parent always replaced)
14381        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14382        // Disable the child packages
14383        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14384        for (int i = 0; i < childCount; i++) {
14385            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14386            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14387            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14388        }
14389        return disabled;
14390    }
14391
14392    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14393            String installerPackageName) {
14394        // Enable the parent package
14395        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14396        // Enable the child packages
14397        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14398        for (int i = 0; i < childCount; i++) {
14399            PackageParser.Package childPkg = pkg.childPackages.get(i);
14400            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14401        }
14402    }
14403
14404    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14405        // Collect all used permissions in the UID
14406        ArraySet<String> usedPermissions = new ArraySet<>();
14407        final int packageCount = su.packages.size();
14408        for (int i = 0; i < packageCount; i++) {
14409            PackageSetting ps = su.packages.valueAt(i);
14410            if (ps.pkg == null) {
14411                continue;
14412            }
14413            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14414            for (int j = 0; j < requestedPermCount; j++) {
14415                String permission = ps.pkg.requestedPermissions.get(j);
14416                BasePermission bp = mSettings.mPermissions.get(permission);
14417                if (bp != null) {
14418                    usedPermissions.add(permission);
14419                }
14420            }
14421        }
14422
14423        PermissionsState permissionsState = su.getPermissionsState();
14424        // Prune install permissions
14425        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14426        final int installPermCount = installPermStates.size();
14427        for (int i = installPermCount - 1; i >= 0;  i--) {
14428            PermissionState permissionState = installPermStates.get(i);
14429            if (!usedPermissions.contains(permissionState.getName())) {
14430                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14431                if (bp != null) {
14432                    permissionsState.revokeInstallPermission(bp);
14433                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14434                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14435                }
14436            }
14437        }
14438
14439        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14440
14441        // Prune runtime permissions
14442        for (int userId : allUserIds) {
14443            List<PermissionState> runtimePermStates = permissionsState
14444                    .getRuntimePermissionStates(userId);
14445            final int runtimePermCount = runtimePermStates.size();
14446            for (int i = runtimePermCount - 1; i >= 0; i--) {
14447                PermissionState permissionState = runtimePermStates.get(i);
14448                if (!usedPermissions.contains(permissionState.getName())) {
14449                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14450                    if (bp != null) {
14451                        permissionsState.revokeRuntimePermission(bp, userId);
14452                        permissionsState.updatePermissionFlags(bp, userId,
14453                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14454                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14455                                runtimePermissionChangedUserIds, userId);
14456                    }
14457                }
14458            }
14459        }
14460
14461        return runtimePermissionChangedUserIds;
14462    }
14463
14464    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14465            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14466        // Update the parent package setting
14467        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14468                res, user);
14469        // Update the child packages setting
14470        final int childCount = (newPackage.childPackages != null)
14471                ? newPackage.childPackages.size() : 0;
14472        for (int i = 0; i < childCount; i++) {
14473            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14474            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14475            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14476                    childRes.origUsers, childRes, user);
14477        }
14478    }
14479
14480    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14481            String installerPackageName, int[] allUsers, int[] installedForUsers,
14482            PackageInstalledInfo res, UserHandle user) {
14483        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14484
14485        String pkgName = newPackage.packageName;
14486        synchronized (mPackages) {
14487            //write settings. the installStatus will be incomplete at this stage.
14488            //note that the new package setting would have already been
14489            //added to mPackages. It hasn't been persisted yet.
14490            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14491            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14492            mSettings.writeLPr();
14493            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14494        }
14495
14496        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14497        synchronized (mPackages) {
14498            updatePermissionsLPw(newPackage.packageName, newPackage,
14499                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14500                            ? UPDATE_PERMISSIONS_ALL : 0));
14501            // For system-bundled packages, we assume that installing an upgraded version
14502            // of the package implies that the user actually wants to run that new code,
14503            // so we enable the package.
14504            PackageSetting ps = mSettings.mPackages.get(pkgName);
14505            final int userId = user.getIdentifier();
14506            if (ps != null) {
14507                if (isSystemApp(newPackage)) {
14508                    if (DEBUG_INSTALL) {
14509                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14510                    }
14511                    // Enable system package for requested users
14512                    if (res.origUsers != null) {
14513                        for (int origUserId : res.origUsers) {
14514                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14515                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14516                                        origUserId, installerPackageName);
14517                            }
14518                        }
14519                    }
14520                    // Also convey the prior install/uninstall state
14521                    if (allUsers != null && installedForUsers != null) {
14522                        for (int currentUserId : allUsers) {
14523                            final boolean installed = ArrayUtils.contains(
14524                                    installedForUsers, currentUserId);
14525                            if (DEBUG_INSTALL) {
14526                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14527                            }
14528                            ps.setInstalled(installed, currentUserId);
14529                        }
14530                        // these install state changes will be persisted in the
14531                        // upcoming call to mSettings.writeLPr().
14532                    }
14533                }
14534                // It's implied that when a user requests installation, they want the app to be
14535                // installed and enabled.
14536                if (userId != UserHandle.USER_ALL) {
14537                    ps.setInstalled(true, userId);
14538                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14539                }
14540            }
14541            res.name = pkgName;
14542            res.uid = newPackage.applicationInfo.uid;
14543            res.pkg = newPackage;
14544            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14545            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14546            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14547            //to update install status
14548            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14549            mSettings.writeLPr();
14550            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14551        }
14552
14553        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14554    }
14555
14556    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14557        try {
14558            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14559            installPackageLI(args, res);
14560        } finally {
14561            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14562        }
14563    }
14564
14565    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14566        final int installFlags = args.installFlags;
14567        final String installerPackageName = args.installerPackageName;
14568        final String volumeUuid = args.volumeUuid;
14569        final File tmpPackageFile = new File(args.getCodePath());
14570        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14571        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14572                || (args.volumeUuid != null));
14573        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14574        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14575        boolean replace = false;
14576        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14577        if (args.move != null) {
14578            // moving a complete application; perform an initial scan on the new install location
14579            scanFlags |= SCAN_INITIAL;
14580        }
14581        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14582            scanFlags |= SCAN_DONT_KILL_APP;
14583        }
14584
14585        // Result object to be returned
14586        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14587
14588        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14589
14590        // Sanity check
14591        if (ephemeral && (forwardLocked || onExternal)) {
14592            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14593                    + " external=" + onExternal);
14594            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14595            return;
14596        }
14597
14598        // Retrieve PackageSettings and parse package
14599        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14600                | PackageParser.PARSE_ENFORCE_CODE
14601                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14602                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14603                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14604                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14605        PackageParser pp = new PackageParser();
14606        pp.setSeparateProcesses(mSeparateProcesses);
14607        pp.setDisplayMetrics(mMetrics);
14608
14609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14610        final PackageParser.Package pkg;
14611        try {
14612            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14613        } catch (PackageParserException e) {
14614            res.setError("Failed parse during installPackageLI", e);
14615            return;
14616        } finally {
14617            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14618        }
14619
14620        // If we are installing a clustered package add results for the children
14621        if (pkg.childPackages != null) {
14622            synchronized (mPackages) {
14623                final int childCount = pkg.childPackages.size();
14624                for (int i = 0; i < childCount; i++) {
14625                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14626                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14627                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14628                    childRes.pkg = childPkg;
14629                    childRes.name = childPkg.packageName;
14630                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14631                    if (childPs != null) {
14632                        childRes.origUsers = childPs.queryInstalledUsers(
14633                                sUserManager.getUserIds(), true);
14634                    }
14635                    if ((mPackages.containsKey(childPkg.packageName))) {
14636                        childRes.removedInfo = new PackageRemovedInfo();
14637                        childRes.removedInfo.removedPackage = childPkg.packageName;
14638                    }
14639                    if (res.addedChildPackages == null) {
14640                        res.addedChildPackages = new ArrayMap<>();
14641                    }
14642                    res.addedChildPackages.put(childPkg.packageName, childRes);
14643                }
14644            }
14645        }
14646
14647        // If package doesn't declare API override, mark that we have an install
14648        // time CPU ABI override.
14649        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14650            pkg.cpuAbiOverride = args.abiOverride;
14651        }
14652
14653        String pkgName = res.name = pkg.packageName;
14654        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14655            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14656                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14657                return;
14658            }
14659        }
14660
14661        try {
14662            // either use what we've been given or parse directly from the APK
14663            if (args.certificates != null) {
14664                try {
14665                    PackageParser.populateCertificates(pkg, args.certificates);
14666                } catch (PackageParserException e) {
14667                    // there was something wrong with the certificates we were given;
14668                    // try to pull them from the APK
14669                    PackageParser.collectCertificates(pkg, parseFlags);
14670                }
14671            } else {
14672                PackageParser.collectCertificates(pkg, parseFlags);
14673            }
14674        } catch (PackageParserException e) {
14675            res.setError("Failed collect during installPackageLI", e);
14676            return;
14677        }
14678
14679        // Get rid of all references to package scan path via parser.
14680        pp = null;
14681        String oldCodePath = null;
14682        boolean systemApp = false;
14683        synchronized (mPackages) {
14684            // Check if installing already existing package
14685            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14686                String oldName = mSettings.mRenamedPackages.get(pkgName);
14687                if (pkg.mOriginalPackages != null
14688                        && pkg.mOriginalPackages.contains(oldName)
14689                        && mPackages.containsKey(oldName)) {
14690                    // This package is derived from an original package,
14691                    // and this device has been updating from that original
14692                    // name.  We must continue using the original name, so
14693                    // rename the new package here.
14694                    pkg.setPackageName(oldName);
14695                    pkgName = pkg.packageName;
14696                    replace = true;
14697                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14698                            + oldName + " pkgName=" + pkgName);
14699                } else if (mPackages.containsKey(pkgName)) {
14700                    // This package, under its official name, already exists
14701                    // on the device; we should replace it.
14702                    replace = true;
14703                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14704                }
14705
14706                // Child packages are installed through the parent package
14707                if (pkg.parentPackage != null) {
14708                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14709                            "Package " + pkg.packageName + " is child of package "
14710                                    + pkg.parentPackage.parentPackage + ". Child packages "
14711                                    + "can be updated only through the parent package.");
14712                    return;
14713                }
14714
14715                if (replace) {
14716                    // Prevent apps opting out from runtime permissions
14717                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14718                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14719                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14720                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14721                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14722                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14723                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14724                                        + " doesn't support runtime permissions but the old"
14725                                        + " target SDK " + oldTargetSdk + " does.");
14726                        return;
14727                    }
14728
14729                    // Prevent installing of child packages
14730                    if (oldPackage.parentPackage != null) {
14731                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14732                                "Package " + pkg.packageName + " is child of package "
14733                                        + oldPackage.parentPackage + ". Child packages "
14734                                        + "can be updated only through the parent package.");
14735                        return;
14736                    }
14737                }
14738            }
14739
14740            PackageSetting ps = mSettings.mPackages.get(pkgName);
14741            if (ps != null) {
14742                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14743
14744                // Quick sanity check that we're signed correctly if updating;
14745                // we'll check this again later when scanning, but we want to
14746                // bail early here before tripping over redefined permissions.
14747                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14748                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14749                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14750                                + pkg.packageName + " upgrade keys do not match the "
14751                                + "previously installed version");
14752                        return;
14753                    }
14754                } else {
14755                    try {
14756                        verifySignaturesLP(ps, pkg);
14757                    } catch (PackageManagerException e) {
14758                        res.setError(e.error, e.getMessage());
14759                        return;
14760                    }
14761                }
14762
14763                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14764                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14765                    systemApp = (ps.pkg.applicationInfo.flags &
14766                            ApplicationInfo.FLAG_SYSTEM) != 0;
14767                }
14768                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14769            }
14770
14771            // Check whether the newly-scanned package wants to define an already-defined perm
14772            int N = pkg.permissions.size();
14773            for (int i = N-1; i >= 0; i--) {
14774                PackageParser.Permission perm = pkg.permissions.get(i);
14775                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14776                if (bp != null) {
14777                    // If the defining package is signed with our cert, it's okay.  This
14778                    // also includes the "updating the same package" case, of course.
14779                    // "updating same package" could also involve key-rotation.
14780                    final boolean sigsOk;
14781                    if (bp.sourcePackage.equals(pkg.packageName)
14782                            && (bp.packageSetting instanceof PackageSetting)
14783                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14784                                    scanFlags))) {
14785                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14786                    } else {
14787                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14788                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14789                    }
14790                    if (!sigsOk) {
14791                        // If the owning package is the system itself, we log but allow
14792                        // install to proceed; we fail the install on all other permission
14793                        // redefinitions.
14794                        if (!bp.sourcePackage.equals("android")) {
14795                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14796                                    + pkg.packageName + " attempting to redeclare permission "
14797                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14798                            res.origPermission = perm.info.name;
14799                            res.origPackage = bp.sourcePackage;
14800                            return;
14801                        } else {
14802                            Slog.w(TAG, "Package " + pkg.packageName
14803                                    + " attempting to redeclare system permission "
14804                                    + perm.info.name + "; ignoring new declaration");
14805                            pkg.permissions.remove(i);
14806                        }
14807                    }
14808                }
14809            }
14810        }
14811
14812        if (systemApp) {
14813            if (onExternal) {
14814                // Abort update; system app can't be replaced with app on sdcard
14815                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14816                        "Cannot install updates to system apps on sdcard");
14817                return;
14818            } else if (ephemeral) {
14819                // Abort update; system app can't be replaced with an ephemeral app
14820                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14821                        "Cannot update a system app with an ephemeral app");
14822                return;
14823            }
14824        }
14825
14826        if (args.move != null) {
14827            // We did an in-place move, so dex is ready to roll
14828            scanFlags |= SCAN_NO_DEX;
14829            scanFlags |= SCAN_MOVE;
14830
14831            synchronized (mPackages) {
14832                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14833                if (ps == null) {
14834                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14835                            "Missing settings for moved package " + pkgName);
14836                }
14837
14838                // We moved the entire application as-is, so bring over the
14839                // previously derived ABI information.
14840                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14841                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14842            }
14843
14844        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14845            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14846            scanFlags |= SCAN_NO_DEX;
14847
14848            try {
14849                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14850                    args.abiOverride : pkg.cpuAbiOverride);
14851                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14852                        true /* extract libs */);
14853            } catch (PackageManagerException pme) {
14854                Slog.e(TAG, "Error deriving application ABI", pme);
14855                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14856                return;
14857            }
14858
14859            // Shared libraries for the package need to be updated.
14860            synchronized (mPackages) {
14861                try {
14862                    updateSharedLibrariesLPw(pkg, null);
14863                } catch (PackageManagerException e) {
14864                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
14865                }
14866            }
14867            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14868            // Do not run PackageDexOptimizer through the local performDexOpt
14869            // method because `pkg` is not in `mPackages` yet.
14870            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
14871                    null /* instructionSets */, false /* checkProfiles */,
14872                    getCompilerFilterForReason(REASON_INSTALL));
14873            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14874            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14875                String msg = "Extracting package failed for " + pkgName;
14876                res.setError(INSTALL_FAILED_DEXOPT, msg);
14877                return;
14878            }
14879
14880            // Notify BackgroundDexOptService that the package has been changed.
14881            // If this is an update of a package which used to fail to compile,
14882            // BDOS will remove it from its blacklist.
14883            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
14884        }
14885
14886        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14887            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14888            return;
14889        }
14890
14891        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14892
14893        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
14894                "installPackageLI")) {
14895            if (replace) {
14896                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14897                        installerPackageName, res);
14898            } else {
14899                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14900                        args.user, installerPackageName, volumeUuid, res);
14901            }
14902        }
14903        synchronized (mPackages) {
14904            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14905            if (ps != null) {
14906                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14907            }
14908
14909            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14910            for (int i = 0; i < childCount; i++) {
14911                PackageParser.Package childPkg = pkg.childPackages.get(i);
14912                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14913                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14914                if (childPs != null) {
14915                    childRes.newUsers = childPs.queryInstalledUsers(
14916                            sUserManager.getUserIds(), true);
14917                }
14918            }
14919        }
14920    }
14921
14922    private void startIntentFilterVerifications(int userId, boolean replacing,
14923            PackageParser.Package pkg) {
14924        if (mIntentFilterVerifierComponent == null) {
14925            Slog.w(TAG, "No IntentFilter verification will not be done as "
14926                    + "there is no IntentFilterVerifier available!");
14927            return;
14928        }
14929
14930        final int verifierUid = getPackageUid(
14931                mIntentFilterVerifierComponent.getPackageName(),
14932                MATCH_DEBUG_TRIAGED_MISSING,
14933                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14934
14935        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14936        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14937        mHandler.sendMessage(msg);
14938
14939        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14940        for (int i = 0; i < childCount; i++) {
14941            PackageParser.Package childPkg = pkg.childPackages.get(i);
14942            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14943            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14944            mHandler.sendMessage(msg);
14945        }
14946    }
14947
14948    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14949            PackageParser.Package pkg) {
14950        int size = pkg.activities.size();
14951        if (size == 0) {
14952            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14953                    "No activity, so no need to verify any IntentFilter!");
14954            return;
14955        }
14956
14957        final boolean hasDomainURLs = hasDomainURLs(pkg);
14958        if (!hasDomainURLs) {
14959            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14960                    "No domain URLs, so no need to verify any IntentFilter!");
14961            return;
14962        }
14963
14964        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14965                + " if any IntentFilter from the " + size
14966                + " Activities needs verification ...");
14967
14968        int count = 0;
14969        final String packageName = pkg.packageName;
14970
14971        synchronized (mPackages) {
14972            // If this is a new install and we see that we've already run verification for this
14973            // package, we have nothing to do: it means the state was restored from backup.
14974            if (!replacing) {
14975                IntentFilterVerificationInfo ivi =
14976                        mSettings.getIntentFilterVerificationLPr(packageName);
14977                if (ivi != null) {
14978                    if (DEBUG_DOMAIN_VERIFICATION) {
14979                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14980                                + ivi.getStatusString());
14981                    }
14982                    return;
14983                }
14984            }
14985
14986            // If any filters need to be verified, then all need to be.
14987            boolean needToVerify = false;
14988            for (PackageParser.Activity a : pkg.activities) {
14989                for (ActivityIntentInfo filter : a.intents) {
14990                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14991                        if (DEBUG_DOMAIN_VERIFICATION) {
14992                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14993                        }
14994                        needToVerify = true;
14995                        break;
14996                    }
14997                }
14998            }
14999
15000            if (needToVerify) {
15001                final int verificationId = mIntentFilterVerificationToken++;
15002                for (PackageParser.Activity a : pkg.activities) {
15003                    for (ActivityIntentInfo filter : a.intents) {
15004                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15005                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15006                                    "Verification needed for IntentFilter:" + filter.toString());
15007                            mIntentFilterVerifier.addOneIntentFilterVerification(
15008                                    verifierUid, userId, verificationId, filter, packageName);
15009                            count++;
15010                        }
15011                    }
15012                }
15013            }
15014        }
15015
15016        if (count > 0) {
15017            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15018                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15019                    +  " for userId:" + userId);
15020            mIntentFilterVerifier.startVerifications(userId);
15021        } else {
15022            if (DEBUG_DOMAIN_VERIFICATION) {
15023                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15024            }
15025        }
15026    }
15027
15028    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15029        final ComponentName cn  = filter.activity.getComponentName();
15030        final String packageName = cn.getPackageName();
15031
15032        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15033                packageName);
15034        if (ivi == null) {
15035            return true;
15036        }
15037        int status = ivi.getStatus();
15038        switch (status) {
15039            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15040            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15041                return true;
15042
15043            default:
15044                // Nothing to do
15045                return false;
15046        }
15047    }
15048
15049    private static boolean isMultiArch(ApplicationInfo info) {
15050        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15051    }
15052
15053    private static boolean isExternal(PackageParser.Package pkg) {
15054        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15055    }
15056
15057    private static boolean isExternal(PackageSetting ps) {
15058        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15059    }
15060
15061    private static boolean isEphemeral(PackageParser.Package pkg) {
15062        return pkg.applicationInfo.isEphemeralApp();
15063    }
15064
15065    private static boolean isEphemeral(PackageSetting ps) {
15066        return ps.pkg != null && isEphemeral(ps.pkg);
15067    }
15068
15069    private static boolean isSystemApp(PackageParser.Package pkg) {
15070        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15071    }
15072
15073    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15074        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15075    }
15076
15077    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15078        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15079    }
15080
15081    private static boolean isSystemApp(PackageSetting ps) {
15082        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15083    }
15084
15085    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15086        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15087    }
15088
15089    private int packageFlagsToInstallFlags(PackageSetting ps) {
15090        int installFlags = 0;
15091        if (isEphemeral(ps)) {
15092            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15093        }
15094        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15095            // This existing package was an external ASEC install when we have
15096            // the external flag without a UUID
15097            installFlags |= PackageManager.INSTALL_EXTERNAL;
15098        }
15099        if (ps.isForwardLocked()) {
15100            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15101        }
15102        return installFlags;
15103    }
15104
15105    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15106        if (isExternal(pkg)) {
15107            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15108                return StorageManager.UUID_PRIMARY_PHYSICAL;
15109            } else {
15110                return pkg.volumeUuid;
15111            }
15112        } else {
15113            return StorageManager.UUID_PRIVATE_INTERNAL;
15114        }
15115    }
15116
15117    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15118        if (isExternal(pkg)) {
15119            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15120                return mSettings.getExternalVersion();
15121            } else {
15122                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15123            }
15124        } else {
15125            return mSettings.getInternalVersion();
15126        }
15127    }
15128
15129    private void deleteTempPackageFiles() {
15130        final FilenameFilter filter = new FilenameFilter() {
15131            public boolean accept(File dir, String name) {
15132                return name.startsWith("vmdl") && name.endsWith(".tmp");
15133            }
15134        };
15135        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15136            file.delete();
15137        }
15138    }
15139
15140    @Override
15141    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15142            int flags) {
15143        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15144                flags);
15145    }
15146
15147    @Override
15148    public void deletePackage(final String packageName,
15149            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15150        mContext.enforceCallingOrSelfPermission(
15151                android.Manifest.permission.DELETE_PACKAGES, null);
15152        Preconditions.checkNotNull(packageName);
15153        Preconditions.checkNotNull(observer);
15154        final int uid = Binder.getCallingUid();
15155        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15156        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15157        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15158            mContext.enforceCallingOrSelfPermission(
15159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15160                    "deletePackage for user " + userId);
15161        }
15162
15163        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15164            try {
15165                observer.onPackageDeleted(packageName,
15166                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15167            } catch (RemoteException re) {
15168            }
15169            return;
15170        }
15171
15172        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15173            try {
15174                observer.onPackageDeleted(packageName,
15175                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15176            } catch (RemoteException re) {
15177            }
15178            return;
15179        }
15180
15181        if (DEBUG_REMOVE) {
15182            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15183                    + " deleteAllUsers: " + deleteAllUsers );
15184        }
15185        // Queue up an async operation since the package deletion may take a little while.
15186        mHandler.post(new Runnable() {
15187            public void run() {
15188                mHandler.removeCallbacks(this);
15189                int returnCode;
15190                if (!deleteAllUsers) {
15191                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15192                } else {
15193                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15194                    // If nobody is blocking uninstall, proceed with delete for all users
15195                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15196                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15197                    } else {
15198                        // Otherwise uninstall individually for users with blockUninstalls=false
15199                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15200                        for (int userId : users) {
15201                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15202                                returnCode = deletePackageX(packageName, userId, userFlags);
15203                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15204                                    Slog.w(TAG, "Package delete failed for user " + userId
15205                                            + ", returnCode " + returnCode);
15206                                }
15207                            }
15208                        }
15209                        // The app has only been marked uninstalled for certain users.
15210                        // We still need to report that delete was blocked
15211                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15212                    }
15213                }
15214                try {
15215                    observer.onPackageDeleted(packageName, returnCode, null);
15216                } catch (RemoteException e) {
15217                    Log.i(TAG, "Observer no longer exists.");
15218                } //end catch
15219            } //end run
15220        });
15221    }
15222
15223    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15224        int[] result = EMPTY_INT_ARRAY;
15225        for (int userId : userIds) {
15226            if (getBlockUninstallForUser(packageName, userId)) {
15227                result = ArrayUtils.appendInt(result, userId);
15228            }
15229        }
15230        return result;
15231    }
15232
15233    @Override
15234    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15235        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15236    }
15237
15238    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15239        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15240                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15241        try {
15242            if (dpm != null) {
15243                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15244                        /* callingUserOnly =*/ false);
15245                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15246                        : deviceOwnerComponentName.getPackageName();
15247                // Does the package contains the device owner?
15248                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15249                // this check is probably not needed, since DO should be registered as a device
15250                // admin on some user too. (Original bug for this: b/17657954)
15251                if (packageName.equals(deviceOwnerPackageName)) {
15252                    return true;
15253                }
15254                // Does it contain a device admin for any user?
15255                int[] users;
15256                if (userId == UserHandle.USER_ALL) {
15257                    users = sUserManager.getUserIds();
15258                } else {
15259                    users = new int[]{userId};
15260                }
15261                for (int i = 0; i < users.length; ++i) {
15262                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15263                        return true;
15264                    }
15265                }
15266            }
15267        } catch (RemoteException e) {
15268        }
15269        return false;
15270    }
15271
15272    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15273        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15274    }
15275
15276    /**
15277     *  This method is an internal method that could be get invoked either
15278     *  to delete an installed package or to clean up a failed installation.
15279     *  After deleting an installed package, a broadcast is sent to notify any
15280     *  listeners that the package has been removed. For cleaning up a failed
15281     *  installation, the broadcast is not necessary since the package's
15282     *  installation wouldn't have sent the initial broadcast either
15283     *  The key steps in deleting a package are
15284     *  deleting the package information in internal structures like mPackages,
15285     *  deleting the packages base directories through installd
15286     *  updating mSettings to reflect current status
15287     *  persisting settings for later use
15288     *  sending a broadcast if necessary
15289     */
15290    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15291        final PackageRemovedInfo info = new PackageRemovedInfo();
15292        final boolean res;
15293
15294        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15295                ? UserHandle.ALL : new UserHandle(userId);
15296
15297        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15298            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15299            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15300        }
15301
15302        PackageSetting uninstalledPs = null;
15303
15304        // for the uninstall-updates case and restricted profiles, remember the per-
15305        // user handle installed state
15306        int[] allUsers;
15307        synchronized (mPackages) {
15308            uninstalledPs = mSettings.mPackages.get(packageName);
15309            if (uninstalledPs == null) {
15310                Slog.w(TAG, "Not removing non-existent package " + packageName);
15311                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15312            }
15313            allUsers = sUserManager.getUserIds();
15314            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15315        }
15316
15317        synchronized (mInstallLock) {
15318            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15319            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15320                    "deletePackageX")) {
15321                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15322                        deleteFlags | REMOVE_CHATTY, info, true, null);
15323            }
15324            synchronized (mPackages) {
15325                if (res) {
15326                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15327                }
15328            }
15329        }
15330
15331        if (res) {
15332            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15333            info.sendPackageRemovedBroadcasts(killApp);
15334            info.sendSystemPackageUpdatedBroadcasts();
15335            info.sendSystemPackageAppearedBroadcasts();
15336        }
15337        // Force a gc here.
15338        Runtime.getRuntime().gc();
15339        // Delete the resources here after sending the broadcast to let
15340        // other processes clean up before deleting resources.
15341        if (info.args != null) {
15342            synchronized (mInstallLock) {
15343                info.args.doPostDeleteLI(true);
15344            }
15345        }
15346
15347        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15348    }
15349
15350    class PackageRemovedInfo {
15351        String removedPackage;
15352        int uid = -1;
15353        int removedAppId = -1;
15354        int[] origUsers;
15355        int[] removedUsers = null;
15356        boolean isRemovedPackageSystemUpdate = false;
15357        boolean isUpdate;
15358        boolean dataRemoved;
15359        boolean removedForAllUsers;
15360        // Clean up resources deleted packages.
15361        InstallArgs args = null;
15362        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15363        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15364
15365        void sendPackageRemovedBroadcasts(boolean killApp) {
15366            sendPackageRemovedBroadcastInternal(killApp);
15367            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15368            for (int i = 0; i < childCount; i++) {
15369                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15370                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15371            }
15372        }
15373
15374        void sendSystemPackageUpdatedBroadcasts() {
15375            if (isRemovedPackageSystemUpdate) {
15376                sendSystemPackageUpdatedBroadcastsInternal();
15377                final int childCount = (removedChildPackages != null)
15378                        ? removedChildPackages.size() : 0;
15379                for (int i = 0; i < childCount; i++) {
15380                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15381                    if (childInfo.isRemovedPackageSystemUpdate) {
15382                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15383                    }
15384                }
15385            }
15386        }
15387
15388        void sendSystemPackageAppearedBroadcasts() {
15389            final int packageCount = (appearedChildPackages != null)
15390                    ? appearedChildPackages.size() : 0;
15391            for (int i = 0; i < packageCount; i++) {
15392                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15393                for (int userId : installedInfo.newUsers) {
15394                    sendPackageAddedForUser(installedInfo.name, true,
15395                            UserHandle.getAppId(installedInfo.uid), userId);
15396                }
15397            }
15398        }
15399
15400        private void sendSystemPackageUpdatedBroadcastsInternal() {
15401            Bundle extras = new Bundle(2);
15402            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15403            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15404            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15405                    extras, 0, null, null, null);
15406            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15407                    extras, 0, null, null, null);
15408            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15409                    null, 0, removedPackage, null, null);
15410        }
15411
15412        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15413            Bundle extras = new Bundle(2);
15414            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15415            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15416            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15417            if (isUpdate || isRemovedPackageSystemUpdate) {
15418                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15419            }
15420            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15421            if (removedPackage != null) {
15422                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15423                        extras, 0, null, null, removedUsers);
15424                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15425                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15426                            removedPackage, extras, 0, null, null, removedUsers);
15427                }
15428            }
15429            if (removedAppId >= 0) {
15430                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15431                        removedUsers);
15432            }
15433        }
15434    }
15435
15436    /*
15437     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15438     * flag is not set, the data directory is removed as well.
15439     * make sure this flag is set for partially installed apps. If not its meaningless to
15440     * delete a partially installed application.
15441     */
15442    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15443            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15444        String packageName = ps.name;
15445        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15446        // Retrieve object to delete permissions for shared user later on
15447        final PackageParser.Package deletedPkg;
15448        final PackageSetting deletedPs;
15449        // reader
15450        synchronized (mPackages) {
15451            deletedPkg = mPackages.get(packageName);
15452            deletedPs = mSettings.mPackages.get(packageName);
15453            if (outInfo != null) {
15454                outInfo.removedPackage = packageName;
15455                outInfo.removedUsers = deletedPs != null
15456                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15457                        : null;
15458            }
15459        }
15460
15461        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15462
15463        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15464            final PackageParser.Package resolvedPkg;
15465            if (deletedPkg != null) {
15466                resolvedPkg = deletedPkg;
15467            } else {
15468                // We don't have a parsed package when it lives on an ejected
15469                // adopted storage device, so fake something together
15470                resolvedPkg = new PackageParser.Package(ps.name);
15471                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15472            }
15473            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15474                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15475            destroyAppProfilesLIF(resolvedPkg);
15476            if (outInfo != null) {
15477                outInfo.dataRemoved = true;
15478            }
15479            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15480        }
15481
15482        // writer
15483        synchronized (mPackages) {
15484            if (deletedPs != null) {
15485                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15486                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15487                    clearDefaultBrowserIfNeeded(packageName);
15488                    if (outInfo != null) {
15489                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15490                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15491                    }
15492                    updatePermissionsLPw(deletedPs.name, null, 0);
15493                    if (deletedPs.sharedUser != null) {
15494                        // Remove permissions associated with package. Since runtime
15495                        // permissions are per user we have to kill the removed package
15496                        // or packages running under the shared user of the removed
15497                        // package if revoking the permissions requested only by the removed
15498                        // package is successful and this causes a change in gids.
15499                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15500                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15501                                    userId);
15502                            if (userIdToKill == UserHandle.USER_ALL
15503                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15504                                // If gids changed for this user, kill all affected packages.
15505                                mHandler.post(new Runnable() {
15506                                    @Override
15507                                    public void run() {
15508                                        // This has to happen with no lock held.
15509                                        killApplication(deletedPs.name, deletedPs.appId,
15510                                                KILL_APP_REASON_GIDS_CHANGED);
15511                                    }
15512                                });
15513                                break;
15514                            }
15515                        }
15516                    }
15517                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15518                }
15519                // make sure to preserve per-user disabled state if this removal was just
15520                // a downgrade of a system app to the factory package
15521                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15522                    if (DEBUG_REMOVE) {
15523                        Slog.d(TAG, "Propagating install state across downgrade");
15524                    }
15525                    for (int userId : allUserHandles) {
15526                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15527                        if (DEBUG_REMOVE) {
15528                            Slog.d(TAG, "    user " + userId + " => " + installed);
15529                        }
15530                        ps.setInstalled(installed, userId);
15531                    }
15532                }
15533            }
15534            // can downgrade to reader
15535            if (writeSettings) {
15536                // Save settings now
15537                mSettings.writeLPr();
15538            }
15539        }
15540        if (outInfo != null) {
15541            // A user ID was deleted here. Go through all users and remove it
15542            // from KeyStore.
15543            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15544        }
15545    }
15546
15547    static boolean locationIsPrivileged(File path) {
15548        try {
15549            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15550                    .getCanonicalPath();
15551            return path.getCanonicalPath().startsWith(privilegedAppDir);
15552        } catch (IOException e) {
15553            Slog.e(TAG, "Unable to access code path " + path);
15554        }
15555        return false;
15556    }
15557
15558    /*
15559     * Tries to delete system package.
15560     */
15561    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15562            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15563            boolean writeSettings) {
15564        if (deletedPs.parentPackageName != null) {
15565            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15566            return false;
15567        }
15568
15569        final boolean applyUserRestrictions
15570                = (allUserHandles != null) && (outInfo.origUsers != null);
15571        final PackageSetting disabledPs;
15572        // Confirm if the system package has been updated
15573        // An updated system app can be deleted. This will also have to restore
15574        // the system pkg from system partition
15575        // reader
15576        synchronized (mPackages) {
15577            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15578        }
15579
15580        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15581                + " disabledPs=" + disabledPs);
15582
15583        if (disabledPs == null) {
15584            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15585            return false;
15586        } else if (DEBUG_REMOVE) {
15587            Slog.d(TAG, "Deleting system pkg from data partition");
15588        }
15589
15590        if (DEBUG_REMOVE) {
15591            if (applyUserRestrictions) {
15592                Slog.d(TAG, "Remembering install states:");
15593                for (int userId : allUserHandles) {
15594                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15595                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15596                }
15597            }
15598        }
15599
15600        // Delete the updated package
15601        outInfo.isRemovedPackageSystemUpdate = true;
15602        if (outInfo.removedChildPackages != null) {
15603            final int childCount = (deletedPs.childPackageNames != null)
15604                    ? deletedPs.childPackageNames.size() : 0;
15605            for (int i = 0; i < childCount; i++) {
15606                String childPackageName = deletedPs.childPackageNames.get(i);
15607                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15608                        .contains(childPackageName)) {
15609                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15610                            childPackageName);
15611                    if (childInfo != null) {
15612                        childInfo.isRemovedPackageSystemUpdate = true;
15613                    }
15614                }
15615            }
15616        }
15617
15618        if (disabledPs.versionCode < deletedPs.versionCode) {
15619            // Delete data for downgrades
15620            flags &= ~PackageManager.DELETE_KEEP_DATA;
15621        } else {
15622            // Preserve data by setting flag
15623            flags |= PackageManager.DELETE_KEEP_DATA;
15624        }
15625
15626        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15627                outInfo, writeSettings, disabledPs.pkg);
15628        if (!ret) {
15629            return false;
15630        }
15631
15632        // writer
15633        synchronized (mPackages) {
15634            // Reinstate the old system package
15635            enableSystemPackageLPw(disabledPs.pkg);
15636            // Remove any native libraries from the upgraded package.
15637            removeNativeBinariesLI(deletedPs);
15638        }
15639
15640        // Install the system package
15641        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15642        int parseFlags = mDefParseFlags
15643                | PackageParser.PARSE_MUST_BE_APK
15644                | PackageParser.PARSE_IS_SYSTEM
15645                | PackageParser.PARSE_IS_SYSTEM_DIR;
15646        if (locationIsPrivileged(disabledPs.codePath)) {
15647            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15648        }
15649
15650        final PackageParser.Package newPkg;
15651        try {
15652            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15653        } catch (PackageManagerException e) {
15654            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15655                    + e.getMessage());
15656            return false;
15657        }
15658
15659        prepareAppDataAfterInstallLIF(newPkg);
15660
15661        // writer
15662        synchronized (mPackages) {
15663            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15664
15665            // Propagate the permissions state as we do not want to drop on the floor
15666            // runtime permissions. The update permissions method below will take
15667            // care of removing obsolete permissions and grant install permissions.
15668            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15669            updatePermissionsLPw(newPkg.packageName, newPkg,
15670                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15671
15672            if (applyUserRestrictions) {
15673                if (DEBUG_REMOVE) {
15674                    Slog.d(TAG, "Propagating install state across reinstall");
15675                }
15676                for (int userId : allUserHandles) {
15677                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15678                    if (DEBUG_REMOVE) {
15679                        Slog.d(TAG, "    user " + userId + " => " + installed);
15680                    }
15681                    ps.setInstalled(installed, userId);
15682
15683                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15684                }
15685                // Regardless of writeSettings we need to ensure that this restriction
15686                // state propagation is persisted
15687                mSettings.writeAllUsersPackageRestrictionsLPr();
15688            }
15689            // can downgrade to reader here
15690            if (writeSettings) {
15691                mSettings.writeLPr();
15692            }
15693        }
15694        return true;
15695    }
15696
15697    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15698            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15699            PackageRemovedInfo outInfo, boolean writeSettings,
15700            PackageParser.Package replacingPackage) {
15701        synchronized (mPackages) {
15702            if (outInfo != null) {
15703                outInfo.uid = ps.appId;
15704            }
15705
15706            if (outInfo != null && outInfo.removedChildPackages != null) {
15707                final int childCount = (ps.childPackageNames != null)
15708                        ? ps.childPackageNames.size() : 0;
15709                for (int i = 0; i < childCount; i++) {
15710                    String childPackageName = ps.childPackageNames.get(i);
15711                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15712                    if (childPs == null) {
15713                        return false;
15714                    }
15715                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15716                            childPackageName);
15717                    if (childInfo != null) {
15718                        childInfo.uid = childPs.appId;
15719                    }
15720                }
15721            }
15722        }
15723
15724        // Delete package data from internal structures and also remove data if flag is set
15725        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15726
15727        // Delete the child packages data
15728        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15729        for (int i = 0; i < childCount; i++) {
15730            PackageSetting childPs;
15731            synchronized (mPackages) {
15732                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15733            }
15734            if (childPs != null) {
15735                PackageRemovedInfo childOutInfo = (outInfo != null
15736                        && outInfo.removedChildPackages != null)
15737                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15738                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15739                        && (replacingPackage != null
15740                        && !replacingPackage.hasChildPackage(childPs.name))
15741                        ? flags & ~DELETE_KEEP_DATA : flags;
15742                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15743                        deleteFlags, writeSettings);
15744            }
15745        }
15746
15747        // Delete application code and resources only for parent packages
15748        if (ps.parentPackageName == null) {
15749            if (deleteCodeAndResources && (outInfo != null)) {
15750                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15751                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15752                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15753            }
15754        }
15755
15756        return true;
15757    }
15758
15759    @Override
15760    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15761            int userId) {
15762        mContext.enforceCallingOrSelfPermission(
15763                android.Manifest.permission.DELETE_PACKAGES, null);
15764        synchronized (mPackages) {
15765            PackageSetting ps = mSettings.mPackages.get(packageName);
15766            if (ps == null) {
15767                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15768                return false;
15769            }
15770            if (!ps.getInstalled(userId)) {
15771                // Can't block uninstall for an app that is not installed or enabled.
15772                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15773                return false;
15774            }
15775            ps.setBlockUninstall(blockUninstall, userId);
15776            mSettings.writePackageRestrictionsLPr(userId);
15777        }
15778        return true;
15779    }
15780
15781    @Override
15782    public boolean getBlockUninstallForUser(String packageName, int userId) {
15783        synchronized (mPackages) {
15784            PackageSetting ps = mSettings.mPackages.get(packageName);
15785            if (ps == null) {
15786                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15787                return false;
15788            }
15789            return ps.getBlockUninstall(userId);
15790        }
15791    }
15792
15793    @Override
15794    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15795        int callingUid = Binder.getCallingUid();
15796        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15797            throw new SecurityException(
15798                    "setRequiredForSystemUser can only be run by the system or root");
15799        }
15800        synchronized (mPackages) {
15801            PackageSetting ps = mSettings.mPackages.get(packageName);
15802            if (ps == null) {
15803                Log.w(TAG, "Package doesn't exist: " + packageName);
15804                return false;
15805            }
15806            if (systemUserApp) {
15807                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15808            } else {
15809                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15810            }
15811            mSettings.writeLPr();
15812        }
15813        return true;
15814    }
15815
15816    /*
15817     * This method handles package deletion in general
15818     */
15819    private boolean deletePackageLIF(String packageName, UserHandle user,
15820            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15821            PackageRemovedInfo outInfo, boolean writeSettings,
15822            PackageParser.Package replacingPackage) {
15823        if (packageName == null) {
15824            Slog.w(TAG, "Attempt to delete null packageName.");
15825            return false;
15826        }
15827
15828        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15829
15830        PackageSetting ps;
15831
15832        synchronized (mPackages) {
15833            ps = mSettings.mPackages.get(packageName);
15834            if (ps == null) {
15835                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15836                return false;
15837            }
15838
15839            if (ps.parentPackageName != null && (!isSystemApp(ps)
15840                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15841                if (DEBUG_REMOVE) {
15842                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15843                            + ((user == null) ? UserHandle.USER_ALL : user));
15844                }
15845                final int removedUserId = (user != null) ? user.getIdentifier()
15846                        : UserHandle.USER_ALL;
15847                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
15848                    return false;
15849                }
15850                markPackageUninstalledForUserLPw(ps, user);
15851                scheduleWritePackageRestrictionsLocked(user);
15852                return true;
15853            }
15854        }
15855
15856        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15857                && user.getIdentifier() != UserHandle.USER_ALL)) {
15858            // The caller is asking that the package only be deleted for a single
15859            // user.  To do this, we just mark its uninstalled state and delete
15860            // its data. If this is a system app, we only allow this to happen if
15861            // they have set the special DELETE_SYSTEM_APP which requests different
15862            // semantics than normal for uninstalling system apps.
15863            markPackageUninstalledForUserLPw(ps, user);
15864
15865            if (!isSystemApp(ps)) {
15866                // Do not uninstall the APK if an app should be cached
15867                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15868                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15869                    // Other user still have this package installed, so all
15870                    // we need to do is clear this user's data and save that
15871                    // it is uninstalled.
15872                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15873                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15874                        return false;
15875                    }
15876                    scheduleWritePackageRestrictionsLocked(user);
15877                    return true;
15878                } else {
15879                    // We need to set it back to 'installed' so the uninstall
15880                    // broadcasts will be sent correctly.
15881                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15882                    ps.setInstalled(true, user.getIdentifier());
15883                }
15884            } else {
15885                // This is a system app, so we assume that the
15886                // other users still have this package installed, so all
15887                // we need to do is clear this user's data and save that
15888                // it is uninstalled.
15889                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15890                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
15891                    return false;
15892                }
15893                scheduleWritePackageRestrictionsLocked(user);
15894                return true;
15895            }
15896        }
15897
15898        // If we are deleting a composite package for all users, keep track
15899        // of result for each child.
15900        if (ps.childPackageNames != null && outInfo != null) {
15901            synchronized (mPackages) {
15902                final int childCount = ps.childPackageNames.size();
15903                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15904                for (int i = 0; i < childCount; i++) {
15905                    String childPackageName = ps.childPackageNames.get(i);
15906                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15907                    childInfo.removedPackage = childPackageName;
15908                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15909                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15910                    if (childPs != null) {
15911                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15912                    }
15913                }
15914            }
15915        }
15916
15917        boolean ret = false;
15918        if (isSystemApp(ps)) {
15919            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15920            // When an updated system application is deleted we delete the existing resources
15921            // as well and fall back to existing code in system partition
15922            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15923        } else {
15924            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15925            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
15926                    outInfo, writeSettings, replacingPackage);
15927        }
15928
15929        // Take a note whether we deleted the package for all users
15930        if (outInfo != null) {
15931            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15932            if (outInfo.removedChildPackages != null) {
15933                synchronized (mPackages) {
15934                    final int childCount = outInfo.removedChildPackages.size();
15935                    for (int i = 0; i < childCount; i++) {
15936                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15937                        if (childInfo != null) {
15938                            childInfo.removedForAllUsers = mPackages.get(
15939                                    childInfo.removedPackage) == null;
15940                        }
15941                    }
15942                }
15943            }
15944            // If we uninstalled an update to a system app there may be some
15945            // child packages that appeared as they are declared in the system
15946            // app but were not declared in the update.
15947            if (isSystemApp(ps)) {
15948                synchronized (mPackages) {
15949                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15950                    final int childCount = (updatedPs.childPackageNames != null)
15951                            ? updatedPs.childPackageNames.size() : 0;
15952                    for (int i = 0; i < childCount; i++) {
15953                        String childPackageName = updatedPs.childPackageNames.get(i);
15954                        if (outInfo.removedChildPackages == null
15955                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15956                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15957                            if (childPs == null) {
15958                                continue;
15959                            }
15960                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15961                            installRes.name = childPackageName;
15962                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15963                            installRes.pkg = mPackages.get(childPackageName);
15964                            installRes.uid = childPs.pkg.applicationInfo.uid;
15965                            if (outInfo.appearedChildPackages == null) {
15966                                outInfo.appearedChildPackages = new ArrayMap<>();
15967                            }
15968                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15969                        }
15970                    }
15971                }
15972            }
15973        }
15974
15975        return ret;
15976    }
15977
15978    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15979        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15980                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15981        for (int nextUserId : userIds) {
15982            if (DEBUG_REMOVE) {
15983                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15984            }
15985            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
15986                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15987                    false /*hidden*/, false /*suspended*/, null, null, null,
15988                    false /*blockUninstall*/,
15989                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15990        }
15991    }
15992
15993    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
15994            PackageRemovedInfo outInfo) {
15995        final PackageParser.Package pkg;
15996        synchronized (mPackages) {
15997            pkg = mPackages.get(ps.name);
15998        }
15999
16000        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16001                : new int[] {userId};
16002        for (int nextUserId : userIds) {
16003            if (DEBUG_REMOVE) {
16004                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16005                        + nextUserId);
16006            }
16007
16008            destroyAppDataLIF(pkg, userId,
16009                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16010            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16011            schedulePackageCleaning(ps.name, nextUserId, false);
16012            synchronized (mPackages) {
16013                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16014                    scheduleWritePackageRestrictionsLocked(nextUserId);
16015                }
16016                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16017            }
16018        }
16019
16020        if (outInfo != null) {
16021            outInfo.removedPackage = ps.name;
16022            outInfo.removedAppId = ps.appId;
16023            outInfo.removedUsers = userIds;
16024        }
16025
16026        return true;
16027    }
16028
16029    private final class ClearStorageConnection implements ServiceConnection {
16030        IMediaContainerService mContainerService;
16031
16032        @Override
16033        public void onServiceConnected(ComponentName name, IBinder service) {
16034            synchronized (this) {
16035                mContainerService = IMediaContainerService.Stub.asInterface(service);
16036                notifyAll();
16037            }
16038        }
16039
16040        @Override
16041        public void onServiceDisconnected(ComponentName name) {
16042        }
16043    }
16044
16045    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16046        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16047
16048        final boolean mounted;
16049        if (Environment.isExternalStorageEmulated()) {
16050            mounted = true;
16051        } else {
16052            final String status = Environment.getExternalStorageState();
16053
16054            mounted = status.equals(Environment.MEDIA_MOUNTED)
16055                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16056        }
16057
16058        if (!mounted) {
16059            return;
16060        }
16061
16062        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16063        int[] users;
16064        if (userId == UserHandle.USER_ALL) {
16065            users = sUserManager.getUserIds();
16066        } else {
16067            users = new int[] { userId };
16068        }
16069        final ClearStorageConnection conn = new ClearStorageConnection();
16070        if (mContext.bindServiceAsUser(
16071                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16072            try {
16073                for (int curUser : users) {
16074                    long timeout = SystemClock.uptimeMillis() + 5000;
16075                    synchronized (conn) {
16076                        long now = SystemClock.uptimeMillis();
16077                        while (conn.mContainerService == null && now < timeout) {
16078                            try {
16079                                conn.wait(timeout - now);
16080                            } catch (InterruptedException e) {
16081                            }
16082                        }
16083                    }
16084                    if (conn.mContainerService == null) {
16085                        return;
16086                    }
16087
16088                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16089                    clearDirectory(conn.mContainerService,
16090                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16091                    if (allData) {
16092                        clearDirectory(conn.mContainerService,
16093                                userEnv.buildExternalStorageAppDataDirs(packageName));
16094                        clearDirectory(conn.mContainerService,
16095                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16096                    }
16097                }
16098            } finally {
16099                mContext.unbindService(conn);
16100            }
16101        }
16102    }
16103
16104    @Override
16105    public void clearApplicationProfileData(String packageName) {
16106        enforceSystemOrRoot("Only the system can clear all profile data");
16107
16108        final PackageParser.Package pkg;
16109        synchronized (mPackages) {
16110            pkg = mPackages.get(packageName);
16111        }
16112
16113        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16114            synchronized (mInstallLock) {
16115                clearAppProfilesLIF(pkg);
16116            }
16117        }
16118    }
16119
16120    @Override
16121    public void clearApplicationUserData(final String packageName,
16122            final IPackageDataObserver observer, final int userId) {
16123        mContext.enforceCallingOrSelfPermission(
16124                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16125
16126        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16127                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16128
16129        final DevicePolicyManagerInternal dpmi = LocalServices
16130                .getService(DevicePolicyManagerInternal.class);
16131        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16132            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16133        }
16134        // Queue up an async operation since the package deletion may take a little while.
16135        mHandler.post(new Runnable() {
16136            public void run() {
16137                mHandler.removeCallbacks(this);
16138                final boolean succeeded;
16139                try (PackageFreezer freezer = freezePackage(packageName,
16140                        "clearApplicationUserData")) {
16141                    synchronized (mInstallLock) {
16142                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16143                    }
16144                    clearExternalStorageDataSync(packageName, userId, true);
16145                }
16146                if (succeeded) {
16147                    // invoke DeviceStorageMonitor's update method to clear any notifications
16148                    DeviceStorageMonitorInternal dsm = LocalServices
16149                            .getService(DeviceStorageMonitorInternal.class);
16150                    if (dsm != null) {
16151                        dsm.checkMemory();
16152                    }
16153                }
16154                if(observer != null) {
16155                    try {
16156                        observer.onRemoveCompleted(packageName, succeeded);
16157                    } catch (RemoteException e) {
16158                        Log.i(TAG, "Observer no longer exists.");
16159                    }
16160                } //end if observer
16161            } //end run
16162        });
16163    }
16164
16165    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16166        if (packageName == null) {
16167            Slog.w(TAG, "Attempt to delete null packageName.");
16168            return false;
16169        }
16170
16171        // Try finding details about the requested package
16172        PackageParser.Package pkg;
16173        synchronized (mPackages) {
16174            pkg = mPackages.get(packageName);
16175            if (pkg == null) {
16176                final PackageSetting ps = mSettings.mPackages.get(packageName);
16177                if (ps != null) {
16178                    pkg = ps.pkg;
16179                }
16180            }
16181
16182            if (pkg == null) {
16183                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16184                return false;
16185            }
16186
16187            PackageSetting ps = (PackageSetting) pkg.mExtras;
16188            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16189        }
16190
16191        clearAppDataLIF(pkg, userId,
16192                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16193
16194        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16195        removeKeystoreDataIfNeeded(userId, appId);
16196
16197        final UserManager um = mContext.getSystemService(UserManager.class);
16198        final int flags;
16199        if (um.isUserUnlockingOrUnlocked(userId)) {
16200            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16201        } else if (um.isUserRunning(userId)) {
16202            flags = StorageManager.FLAG_STORAGE_DE;
16203        } else {
16204            flags = 0;
16205        }
16206        prepareAppDataContentsLIF(pkg, userId, flags);
16207
16208        return true;
16209    }
16210
16211    /**
16212     * Reverts user permission state changes (permissions and flags) in
16213     * all packages for a given user.
16214     *
16215     * @param userId The device user for which to do a reset.
16216     */
16217    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16218        final int packageCount = mPackages.size();
16219        for (int i = 0; i < packageCount; i++) {
16220            PackageParser.Package pkg = mPackages.valueAt(i);
16221            PackageSetting ps = (PackageSetting) pkg.mExtras;
16222            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16223        }
16224    }
16225
16226    private void resetNetworkPolicies(int userId) {
16227        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16228    }
16229
16230    /**
16231     * Reverts user permission state changes (permissions and flags).
16232     *
16233     * @param ps The package for which to reset.
16234     * @param userId The device user for which to do a reset.
16235     */
16236    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16237            final PackageSetting ps, final int userId) {
16238        if (ps.pkg == null) {
16239            return;
16240        }
16241
16242        // These are flags that can change base on user actions.
16243        final int userSettableMask = FLAG_PERMISSION_USER_SET
16244                | FLAG_PERMISSION_USER_FIXED
16245                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16246                | FLAG_PERMISSION_REVIEW_REQUIRED;
16247
16248        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16249                | FLAG_PERMISSION_POLICY_FIXED;
16250
16251        boolean writeInstallPermissions = false;
16252        boolean writeRuntimePermissions = false;
16253
16254        final int permissionCount = ps.pkg.requestedPermissions.size();
16255        for (int i = 0; i < permissionCount; i++) {
16256            String permission = ps.pkg.requestedPermissions.get(i);
16257
16258            BasePermission bp = mSettings.mPermissions.get(permission);
16259            if (bp == null) {
16260                continue;
16261            }
16262
16263            // If shared user we just reset the state to which only this app contributed.
16264            if (ps.sharedUser != null) {
16265                boolean used = false;
16266                final int packageCount = ps.sharedUser.packages.size();
16267                for (int j = 0; j < packageCount; j++) {
16268                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16269                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16270                            && pkg.pkg.requestedPermissions.contains(permission)) {
16271                        used = true;
16272                        break;
16273                    }
16274                }
16275                if (used) {
16276                    continue;
16277                }
16278            }
16279
16280            PermissionsState permissionsState = ps.getPermissionsState();
16281
16282            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16283
16284            // Always clear the user settable flags.
16285            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16286                    bp.name) != null;
16287            // If permission review is enabled and this is a legacy app, mark the
16288            // permission as requiring a review as this is the initial state.
16289            int flags = 0;
16290            if (Build.PERMISSIONS_REVIEW_REQUIRED
16291                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16292                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16293            }
16294            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16295                if (hasInstallState) {
16296                    writeInstallPermissions = true;
16297                } else {
16298                    writeRuntimePermissions = true;
16299                }
16300            }
16301
16302            // Below is only runtime permission handling.
16303            if (!bp.isRuntime()) {
16304                continue;
16305            }
16306
16307            // Never clobber system or policy.
16308            if ((oldFlags & policyOrSystemFlags) != 0) {
16309                continue;
16310            }
16311
16312            // If this permission was granted by default, make sure it is.
16313            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16314                if (permissionsState.grantRuntimePermission(bp, userId)
16315                        != PERMISSION_OPERATION_FAILURE) {
16316                    writeRuntimePermissions = true;
16317                }
16318            // If permission review is enabled the permissions for a legacy apps
16319            // are represented as constantly granted runtime ones, so don't revoke.
16320            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16321                // Otherwise, reset the permission.
16322                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16323                switch (revokeResult) {
16324                    case PERMISSION_OPERATION_SUCCESS:
16325                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16326                        writeRuntimePermissions = true;
16327                        final int appId = ps.appId;
16328                        mHandler.post(new Runnable() {
16329                            @Override
16330                            public void run() {
16331                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16332                            }
16333                        });
16334                    } break;
16335                }
16336            }
16337        }
16338
16339        // Synchronously write as we are taking permissions away.
16340        if (writeRuntimePermissions) {
16341            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16342        }
16343
16344        // Synchronously write as we are taking permissions away.
16345        if (writeInstallPermissions) {
16346            mSettings.writeLPr();
16347        }
16348    }
16349
16350    /**
16351     * Remove entries from the keystore daemon. Will only remove it if the
16352     * {@code appId} is valid.
16353     */
16354    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16355        if (appId < 0) {
16356            return;
16357        }
16358
16359        final KeyStore keyStore = KeyStore.getInstance();
16360        if (keyStore != null) {
16361            if (userId == UserHandle.USER_ALL) {
16362                for (final int individual : sUserManager.getUserIds()) {
16363                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16364                }
16365            } else {
16366                keyStore.clearUid(UserHandle.getUid(userId, appId));
16367            }
16368        } else {
16369            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16370        }
16371    }
16372
16373    @Override
16374    public void deleteApplicationCacheFiles(final String packageName,
16375            final IPackageDataObserver observer) {
16376        final int userId = UserHandle.getCallingUserId();
16377        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16378    }
16379
16380    @Override
16381    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16382            final IPackageDataObserver observer) {
16383        mContext.enforceCallingOrSelfPermission(
16384                android.Manifest.permission.DELETE_CACHE_FILES, null);
16385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16386                /* requireFullPermission= */ true, /* checkShell= */ false,
16387                "delete application cache files");
16388
16389        final PackageParser.Package pkg;
16390        synchronized (mPackages) {
16391            pkg = mPackages.get(packageName);
16392        }
16393
16394        // Queue up an async operation since the package deletion may take a little while.
16395        mHandler.post(new Runnable() {
16396            public void run() {
16397                synchronized (mInstallLock) {
16398                    final int flags = StorageManager.FLAG_STORAGE_DE
16399                            | StorageManager.FLAG_STORAGE_CE;
16400                    // We're only clearing cache files, so we don't care if the
16401                    // app is unfrozen and still able to run
16402                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16403                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16404                }
16405                clearExternalStorageDataSync(packageName, userId, false);
16406                if (observer != null) {
16407                    try {
16408                        observer.onRemoveCompleted(packageName, true);
16409                    } catch (RemoteException e) {
16410                        Log.i(TAG, "Observer no longer exists.");
16411                    }
16412                }
16413            }
16414        });
16415    }
16416
16417    @Override
16418    public void getPackageSizeInfo(final String packageName, int userHandle,
16419            final IPackageStatsObserver observer) {
16420        mContext.enforceCallingOrSelfPermission(
16421                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16422        if (packageName == null) {
16423            throw new IllegalArgumentException("Attempt to get size of null packageName");
16424        }
16425
16426        PackageStats stats = new PackageStats(packageName, userHandle);
16427
16428        /*
16429         * Queue up an async operation since the package measurement may take a
16430         * little while.
16431         */
16432        Message msg = mHandler.obtainMessage(INIT_COPY);
16433        msg.obj = new MeasureParams(stats, observer);
16434        mHandler.sendMessage(msg);
16435    }
16436
16437    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16438        final PackageSetting ps;
16439        synchronized (mPackages) {
16440            ps = mSettings.mPackages.get(packageName);
16441            if (ps == null) {
16442                Slog.w(TAG, "Failed to find settings for " + packageName);
16443                return false;
16444            }
16445        }
16446        try {
16447            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16448                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16449                    ps.getCeDataInode(userId), ps.codePathString, stats);
16450        } catch (InstallerException e) {
16451            Slog.w(TAG, String.valueOf(e));
16452            return false;
16453        }
16454
16455        // For now, ignore code size of packages on system partition
16456        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16457            stats.codeSize = 0;
16458        }
16459
16460        return true;
16461    }
16462
16463    private int getUidTargetSdkVersionLockedLPr(int uid) {
16464        Object obj = mSettings.getUserIdLPr(uid);
16465        if (obj instanceof SharedUserSetting) {
16466            final SharedUserSetting sus = (SharedUserSetting) obj;
16467            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16468            final Iterator<PackageSetting> it = sus.packages.iterator();
16469            while (it.hasNext()) {
16470                final PackageSetting ps = it.next();
16471                if (ps.pkg != null) {
16472                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16473                    if (v < vers) vers = v;
16474                }
16475            }
16476            return vers;
16477        } else if (obj instanceof PackageSetting) {
16478            final PackageSetting ps = (PackageSetting) obj;
16479            if (ps.pkg != null) {
16480                return ps.pkg.applicationInfo.targetSdkVersion;
16481            }
16482        }
16483        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16484    }
16485
16486    @Override
16487    public void addPreferredActivity(IntentFilter filter, int match,
16488            ComponentName[] set, ComponentName activity, int userId) {
16489        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16490                "Adding preferred");
16491    }
16492
16493    private void addPreferredActivityInternal(IntentFilter filter, int match,
16494            ComponentName[] set, ComponentName activity, boolean always, int userId,
16495            String opname) {
16496        // writer
16497        int callingUid = Binder.getCallingUid();
16498        enforceCrossUserPermission(callingUid, userId,
16499                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16500        if (filter.countActions() == 0) {
16501            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16502            return;
16503        }
16504        synchronized (mPackages) {
16505            if (mContext.checkCallingOrSelfPermission(
16506                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16507                    != PackageManager.PERMISSION_GRANTED) {
16508                if (getUidTargetSdkVersionLockedLPr(callingUid)
16509                        < Build.VERSION_CODES.FROYO) {
16510                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16511                            + callingUid);
16512                    return;
16513                }
16514                mContext.enforceCallingOrSelfPermission(
16515                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16516            }
16517
16518            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16519            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16520                    + userId + ":");
16521            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16522            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16523            scheduleWritePackageRestrictionsLocked(userId);
16524        }
16525    }
16526
16527    @Override
16528    public void replacePreferredActivity(IntentFilter filter, int match,
16529            ComponentName[] set, ComponentName activity, int userId) {
16530        if (filter.countActions() != 1) {
16531            throw new IllegalArgumentException(
16532                    "replacePreferredActivity expects filter to have only 1 action.");
16533        }
16534        if (filter.countDataAuthorities() != 0
16535                || filter.countDataPaths() != 0
16536                || filter.countDataSchemes() > 1
16537                || filter.countDataTypes() != 0) {
16538            throw new IllegalArgumentException(
16539                    "replacePreferredActivity expects filter to have no data authorities, " +
16540                    "paths, or types; and at most one scheme.");
16541        }
16542
16543        final int callingUid = Binder.getCallingUid();
16544        enforceCrossUserPermission(callingUid, userId,
16545                true /* requireFullPermission */, false /* checkShell */,
16546                "replace preferred activity");
16547        synchronized (mPackages) {
16548            if (mContext.checkCallingOrSelfPermission(
16549                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16550                    != PackageManager.PERMISSION_GRANTED) {
16551                if (getUidTargetSdkVersionLockedLPr(callingUid)
16552                        < Build.VERSION_CODES.FROYO) {
16553                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16554                            + Binder.getCallingUid());
16555                    return;
16556                }
16557                mContext.enforceCallingOrSelfPermission(
16558                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16559            }
16560
16561            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16562            if (pir != null) {
16563                // Get all of the existing entries that exactly match this filter.
16564                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16565                if (existing != null && existing.size() == 1) {
16566                    PreferredActivity cur = existing.get(0);
16567                    if (DEBUG_PREFERRED) {
16568                        Slog.i(TAG, "Checking replace of preferred:");
16569                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16570                        if (!cur.mPref.mAlways) {
16571                            Slog.i(TAG, "  -- CUR; not mAlways!");
16572                        } else {
16573                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16574                            Slog.i(TAG, "  -- CUR: mSet="
16575                                    + Arrays.toString(cur.mPref.mSetComponents));
16576                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16577                            Slog.i(TAG, "  -- NEW: mMatch="
16578                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16579                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16580                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16581                        }
16582                    }
16583                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16584                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16585                            && cur.mPref.sameSet(set)) {
16586                        // Setting the preferred activity to what it happens to be already
16587                        if (DEBUG_PREFERRED) {
16588                            Slog.i(TAG, "Replacing with same preferred activity "
16589                                    + cur.mPref.mShortComponent + " for user "
16590                                    + userId + ":");
16591                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16592                        }
16593                        return;
16594                    }
16595                }
16596
16597                if (existing != null) {
16598                    if (DEBUG_PREFERRED) {
16599                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16600                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16601                    }
16602                    for (int i = 0; i < existing.size(); i++) {
16603                        PreferredActivity pa = existing.get(i);
16604                        if (DEBUG_PREFERRED) {
16605                            Slog.i(TAG, "Removing existing preferred activity "
16606                                    + pa.mPref.mComponent + ":");
16607                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16608                        }
16609                        pir.removeFilter(pa);
16610                    }
16611                }
16612            }
16613            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16614                    "Replacing preferred");
16615        }
16616    }
16617
16618    @Override
16619    public void clearPackagePreferredActivities(String packageName) {
16620        final int uid = Binder.getCallingUid();
16621        // writer
16622        synchronized (mPackages) {
16623            PackageParser.Package pkg = mPackages.get(packageName);
16624            if (pkg == null || pkg.applicationInfo.uid != uid) {
16625                if (mContext.checkCallingOrSelfPermission(
16626                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16627                        != PackageManager.PERMISSION_GRANTED) {
16628                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16629                            < Build.VERSION_CODES.FROYO) {
16630                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16631                                + Binder.getCallingUid());
16632                        return;
16633                    }
16634                    mContext.enforceCallingOrSelfPermission(
16635                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16636                }
16637            }
16638
16639            int user = UserHandle.getCallingUserId();
16640            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16641                scheduleWritePackageRestrictionsLocked(user);
16642            }
16643        }
16644    }
16645
16646    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16647    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16648        ArrayList<PreferredActivity> removed = null;
16649        boolean changed = false;
16650        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16651            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16652            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16653            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16654                continue;
16655            }
16656            Iterator<PreferredActivity> it = pir.filterIterator();
16657            while (it.hasNext()) {
16658                PreferredActivity pa = it.next();
16659                // Mark entry for removal only if it matches the package name
16660                // and the entry is of type "always".
16661                if (packageName == null ||
16662                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16663                                && pa.mPref.mAlways)) {
16664                    if (removed == null) {
16665                        removed = new ArrayList<PreferredActivity>();
16666                    }
16667                    removed.add(pa);
16668                }
16669            }
16670            if (removed != null) {
16671                for (int j=0; j<removed.size(); j++) {
16672                    PreferredActivity pa = removed.get(j);
16673                    pir.removeFilter(pa);
16674                }
16675                changed = true;
16676            }
16677        }
16678        return changed;
16679    }
16680
16681    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16682    private void clearIntentFilterVerificationsLPw(int userId) {
16683        final int packageCount = mPackages.size();
16684        for (int i = 0; i < packageCount; i++) {
16685            PackageParser.Package pkg = mPackages.valueAt(i);
16686            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16687        }
16688    }
16689
16690    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16691    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16692        if (userId == UserHandle.USER_ALL) {
16693            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16694                    sUserManager.getUserIds())) {
16695                for (int oneUserId : sUserManager.getUserIds()) {
16696                    scheduleWritePackageRestrictionsLocked(oneUserId);
16697                }
16698            }
16699        } else {
16700            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16701                scheduleWritePackageRestrictionsLocked(userId);
16702            }
16703        }
16704    }
16705
16706    void clearDefaultBrowserIfNeeded(String packageName) {
16707        for (int oneUserId : sUserManager.getUserIds()) {
16708            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16709            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16710            if (packageName.equals(defaultBrowserPackageName)) {
16711                setDefaultBrowserPackageName(null, oneUserId);
16712            }
16713        }
16714    }
16715
16716    @Override
16717    public void resetApplicationPreferences(int userId) {
16718        mContext.enforceCallingOrSelfPermission(
16719                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16720        final long identity = Binder.clearCallingIdentity();
16721        // writer
16722        try {
16723            synchronized (mPackages) {
16724                clearPackagePreferredActivitiesLPw(null, userId);
16725                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16726                // TODO: We have to reset the default SMS and Phone. This requires
16727                // significant refactoring to keep all default apps in the package
16728                // manager (cleaner but more work) or have the services provide
16729                // callbacks to the package manager to request a default app reset.
16730                applyFactoryDefaultBrowserLPw(userId);
16731                clearIntentFilterVerificationsLPw(userId);
16732                primeDomainVerificationsLPw(userId);
16733                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16734                scheduleWritePackageRestrictionsLocked(userId);
16735            }
16736            resetNetworkPolicies(userId);
16737        } finally {
16738            Binder.restoreCallingIdentity(identity);
16739        }
16740    }
16741
16742    @Override
16743    public int getPreferredActivities(List<IntentFilter> outFilters,
16744            List<ComponentName> outActivities, String packageName) {
16745
16746        int num = 0;
16747        final int userId = UserHandle.getCallingUserId();
16748        // reader
16749        synchronized (mPackages) {
16750            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16751            if (pir != null) {
16752                final Iterator<PreferredActivity> it = pir.filterIterator();
16753                while (it.hasNext()) {
16754                    final PreferredActivity pa = it.next();
16755                    if (packageName == null
16756                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16757                                    && pa.mPref.mAlways)) {
16758                        if (outFilters != null) {
16759                            outFilters.add(new IntentFilter(pa));
16760                        }
16761                        if (outActivities != null) {
16762                            outActivities.add(pa.mPref.mComponent);
16763                        }
16764                    }
16765                }
16766            }
16767        }
16768
16769        return num;
16770    }
16771
16772    @Override
16773    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16774            int userId) {
16775        int callingUid = Binder.getCallingUid();
16776        if (callingUid != Process.SYSTEM_UID) {
16777            throw new SecurityException(
16778                    "addPersistentPreferredActivity can only be run by the system");
16779        }
16780        if (filter.countActions() == 0) {
16781            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16782            return;
16783        }
16784        synchronized (mPackages) {
16785            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16786                    ":");
16787            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16788            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16789                    new PersistentPreferredActivity(filter, activity));
16790            scheduleWritePackageRestrictionsLocked(userId);
16791        }
16792    }
16793
16794    @Override
16795    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16796        int callingUid = Binder.getCallingUid();
16797        if (callingUid != Process.SYSTEM_UID) {
16798            throw new SecurityException(
16799                    "clearPackagePersistentPreferredActivities can only be run by the system");
16800        }
16801        ArrayList<PersistentPreferredActivity> removed = null;
16802        boolean changed = false;
16803        synchronized (mPackages) {
16804            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16805                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16806                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16807                        .valueAt(i);
16808                if (userId != thisUserId) {
16809                    continue;
16810                }
16811                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16812                while (it.hasNext()) {
16813                    PersistentPreferredActivity ppa = it.next();
16814                    // Mark entry for removal only if it matches the package name.
16815                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16816                        if (removed == null) {
16817                            removed = new ArrayList<PersistentPreferredActivity>();
16818                        }
16819                        removed.add(ppa);
16820                    }
16821                }
16822                if (removed != null) {
16823                    for (int j=0; j<removed.size(); j++) {
16824                        PersistentPreferredActivity ppa = removed.get(j);
16825                        ppir.removeFilter(ppa);
16826                    }
16827                    changed = true;
16828                }
16829            }
16830
16831            if (changed) {
16832                scheduleWritePackageRestrictionsLocked(userId);
16833            }
16834        }
16835    }
16836
16837    /**
16838     * Common machinery for picking apart a restored XML blob and passing
16839     * it to a caller-supplied functor to be applied to the running system.
16840     */
16841    private void restoreFromXml(XmlPullParser parser, int userId,
16842            String expectedStartTag, BlobXmlRestorer functor)
16843            throws IOException, XmlPullParserException {
16844        int type;
16845        while ((type = parser.next()) != XmlPullParser.START_TAG
16846                && type != XmlPullParser.END_DOCUMENT) {
16847        }
16848        if (type != XmlPullParser.START_TAG) {
16849            // oops didn't find a start tag?!
16850            if (DEBUG_BACKUP) {
16851                Slog.e(TAG, "Didn't find start tag during restore");
16852            }
16853            return;
16854        }
16855Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16856        // this is supposed to be TAG_PREFERRED_BACKUP
16857        if (!expectedStartTag.equals(parser.getName())) {
16858            if (DEBUG_BACKUP) {
16859                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16860            }
16861            return;
16862        }
16863
16864        // skip interfering stuff, then we're aligned with the backing implementation
16865        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16866Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16867        functor.apply(parser, userId);
16868    }
16869
16870    private interface BlobXmlRestorer {
16871        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16872    }
16873
16874    /**
16875     * Non-Binder method, support for the backup/restore mechanism: write the
16876     * full set of preferred activities in its canonical XML format.  Returns the
16877     * XML output as a byte array, or null if there is none.
16878     */
16879    @Override
16880    public byte[] getPreferredActivityBackup(int userId) {
16881        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16882            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16883        }
16884
16885        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16886        try {
16887            final XmlSerializer serializer = new FastXmlSerializer();
16888            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16889            serializer.startDocument(null, true);
16890            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16891
16892            synchronized (mPackages) {
16893                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16894            }
16895
16896            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16897            serializer.endDocument();
16898            serializer.flush();
16899        } catch (Exception e) {
16900            if (DEBUG_BACKUP) {
16901                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16902            }
16903            return null;
16904        }
16905
16906        return dataStream.toByteArray();
16907    }
16908
16909    @Override
16910    public void restorePreferredActivities(byte[] backup, int userId) {
16911        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16912            throw new SecurityException("Only the system may call restorePreferredActivities()");
16913        }
16914
16915        try {
16916            final XmlPullParser parser = Xml.newPullParser();
16917            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16918            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16919                    new BlobXmlRestorer() {
16920                        @Override
16921                        public void apply(XmlPullParser parser, int userId)
16922                                throws XmlPullParserException, IOException {
16923                            synchronized (mPackages) {
16924                                mSettings.readPreferredActivitiesLPw(parser, userId);
16925                            }
16926                        }
16927                    } );
16928        } catch (Exception e) {
16929            if (DEBUG_BACKUP) {
16930                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16931            }
16932        }
16933    }
16934
16935    /**
16936     * Non-Binder method, support for the backup/restore mechanism: write the
16937     * default browser (etc) settings in its canonical XML format.  Returns the default
16938     * browser XML representation as a byte array, or null if there is none.
16939     */
16940    @Override
16941    public byte[] getDefaultAppsBackup(int userId) {
16942        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16943            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16944        }
16945
16946        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16947        try {
16948            final XmlSerializer serializer = new FastXmlSerializer();
16949            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16950            serializer.startDocument(null, true);
16951            serializer.startTag(null, TAG_DEFAULT_APPS);
16952
16953            synchronized (mPackages) {
16954                mSettings.writeDefaultAppsLPr(serializer, userId);
16955            }
16956
16957            serializer.endTag(null, TAG_DEFAULT_APPS);
16958            serializer.endDocument();
16959            serializer.flush();
16960        } catch (Exception e) {
16961            if (DEBUG_BACKUP) {
16962                Slog.e(TAG, "Unable to write default apps for backup", e);
16963            }
16964            return null;
16965        }
16966
16967        return dataStream.toByteArray();
16968    }
16969
16970    @Override
16971    public void restoreDefaultApps(byte[] backup, int userId) {
16972        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16973            throw new SecurityException("Only the system may call restoreDefaultApps()");
16974        }
16975
16976        try {
16977            final XmlPullParser parser = Xml.newPullParser();
16978            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16979            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16980                    new BlobXmlRestorer() {
16981                        @Override
16982                        public void apply(XmlPullParser parser, int userId)
16983                                throws XmlPullParserException, IOException {
16984                            synchronized (mPackages) {
16985                                mSettings.readDefaultAppsLPw(parser, userId);
16986                            }
16987                        }
16988                    } );
16989        } catch (Exception e) {
16990            if (DEBUG_BACKUP) {
16991                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16992            }
16993        }
16994    }
16995
16996    @Override
16997    public byte[] getIntentFilterVerificationBackup(int userId) {
16998        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16999            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17000        }
17001
17002        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17003        try {
17004            final XmlSerializer serializer = new FastXmlSerializer();
17005            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17006            serializer.startDocument(null, true);
17007            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17008
17009            synchronized (mPackages) {
17010                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17011            }
17012
17013            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17014            serializer.endDocument();
17015            serializer.flush();
17016        } catch (Exception e) {
17017            if (DEBUG_BACKUP) {
17018                Slog.e(TAG, "Unable to write default apps for backup", e);
17019            }
17020            return null;
17021        }
17022
17023        return dataStream.toByteArray();
17024    }
17025
17026    @Override
17027    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17028        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17029            throw new SecurityException("Only the system may call restorePreferredActivities()");
17030        }
17031
17032        try {
17033            final XmlPullParser parser = Xml.newPullParser();
17034            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17035            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17036                    new BlobXmlRestorer() {
17037                        @Override
17038                        public void apply(XmlPullParser parser, int userId)
17039                                throws XmlPullParserException, IOException {
17040                            synchronized (mPackages) {
17041                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17042                                mSettings.writeLPr();
17043                            }
17044                        }
17045                    } );
17046        } catch (Exception e) {
17047            if (DEBUG_BACKUP) {
17048                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17049            }
17050        }
17051    }
17052
17053    @Override
17054    public byte[] getPermissionGrantBackup(int userId) {
17055        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17056            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17057        }
17058
17059        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17060        try {
17061            final XmlSerializer serializer = new FastXmlSerializer();
17062            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17063            serializer.startDocument(null, true);
17064            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17065
17066            synchronized (mPackages) {
17067                serializeRuntimePermissionGrantsLPr(serializer, userId);
17068            }
17069
17070            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17071            serializer.endDocument();
17072            serializer.flush();
17073        } catch (Exception e) {
17074            if (DEBUG_BACKUP) {
17075                Slog.e(TAG, "Unable to write default apps for backup", e);
17076            }
17077            return null;
17078        }
17079
17080        return dataStream.toByteArray();
17081    }
17082
17083    @Override
17084    public void restorePermissionGrants(byte[] backup, int userId) {
17085        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17086            throw new SecurityException("Only the system may call restorePermissionGrants()");
17087        }
17088
17089        try {
17090            final XmlPullParser parser = Xml.newPullParser();
17091            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17092            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17093                    new BlobXmlRestorer() {
17094                        @Override
17095                        public void apply(XmlPullParser parser, int userId)
17096                                throws XmlPullParserException, IOException {
17097                            synchronized (mPackages) {
17098                                processRestoredPermissionGrantsLPr(parser, userId);
17099                            }
17100                        }
17101                    } );
17102        } catch (Exception e) {
17103            if (DEBUG_BACKUP) {
17104                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17105            }
17106        }
17107    }
17108
17109    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17110            throws IOException {
17111        serializer.startTag(null, TAG_ALL_GRANTS);
17112
17113        final int N = mSettings.mPackages.size();
17114        for (int i = 0; i < N; i++) {
17115            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17116            boolean pkgGrantsKnown = false;
17117
17118            PermissionsState packagePerms = ps.getPermissionsState();
17119
17120            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17121                final int grantFlags = state.getFlags();
17122                // only look at grants that are not system/policy fixed
17123                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17124                    final boolean isGranted = state.isGranted();
17125                    // And only back up the user-twiddled state bits
17126                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17127                        final String packageName = mSettings.mPackages.keyAt(i);
17128                        if (!pkgGrantsKnown) {
17129                            serializer.startTag(null, TAG_GRANT);
17130                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17131                            pkgGrantsKnown = true;
17132                        }
17133
17134                        final boolean userSet =
17135                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17136                        final boolean userFixed =
17137                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17138                        final boolean revoke =
17139                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17140
17141                        serializer.startTag(null, TAG_PERMISSION);
17142                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17143                        if (isGranted) {
17144                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17145                        }
17146                        if (userSet) {
17147                            serializer.attribute(null, ATTR_USER_SET, "true");
17148                        }
17149                        if (userFixed) {
17150                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17151                        }
17152                        if (revoke) {
17153                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17154                        }
17155                        serializer.endTag(null, TAG_PERMISSION);
17156                    }
17157                }
17158            }
17159
17160            if (pkgGrantsKnown) {
17161                serializer.endTag(null, TAG_GRANT);
17162            }
17163        }
17164
17165        serializer.endTag(null, TAG_ALL_GRANTS);
17166    }
17167
17168    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17169            throws XmlPullParserException, IOException {
17170        String pkgName = null;
17171        int outerDepth = parser.getDepth();
17172        int type;
17173        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17174                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17175            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17176                continue;
17177            }
17178
17179            final String tagName = parser.getName();
17180            if (tagName.equals(TAG_GRANT)) {
17181                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17182                if (DEBUG_BACKUP) {
17183                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17184                }
17185            } else if (tagName.equals(TAG_PERMISSION)) {
17186
17187                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17188                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17189
17190                int newFlagSet = 0;
17191                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17192                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17193                }
17194                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17195                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17196                }
17197                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17198                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17199                }
17200                if (DEBUG_BACKUP) {
17201                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17202                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17203                }
17204                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17205                if (ps != null) {
17206                    // Already installed so we apply the grant immediately
17207                    if (DEBUG_BACKUP) {
17208                        Slog.v(TAG, "        + already installed; applying");
17209                    }
17210                    PermissionsState perms = ps.getPermissionsState();
17211                    BasePermission bp = mSettings.mPermissions.get(permName);
17212                    if (bp != null) {
17213                        if (isGranted) {
17214                            perms.grantRuntimePermission(bp, userId);
17215                        }
17216                        if (newFlagSet != 0) {
17217                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17218                        }
17219                    }
17220                } else {
17221                    // Need to wait for post-restore install to apply the grant
17222                    if (DEBUG_BACKUP) {
17223                        Slog.v(TAG, "        - not yet installed; saving for later");
17224                    }
17225                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17226                            isGranted, newFlagSet, userId);
17227                }
17228            } else {
17229                PackageManagerService.reportSettingsProblem(Log.WARN,
17230                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17231                XmlUtils.skipCurrentTag(parser);
17232            }
17233        }
17234
17235        scheduleWriteSettingsLocked();
17236        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17237    }
17238
17239    @Override
17240    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17241            int sourceUserId, int targetUserId, int flags) {
17242        mContext.enforceCallingOrSelfPermission(
17243                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17244        int callingUid = Binder.getCallingUid();
17245        enforceOwnerRights(ownerPackage, callingUid);
17246        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17247        if (intentFilter.countActions() == 0) {
17248            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17249            return;
17250        }
17251        synchronized (mPackages) {
17252            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17253                    ownerPackage, targetUserId, flags);
17254            CrossProfileIntentResolver resolver =
17255                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17256            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17257            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17258            if (existing != null) {
17259                int size = existing.size();
17260                for (int i = 0; i < size; i++) {
17261                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17262                        return;
17263                    }
17264                }
17265            }
17266            resolver.addFilter(newFilter);
17267            scheduleWritePackageRestrictionsLocked(sourceUserId);
17268        }
17269    }
17270
17271    @Override
17272    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17273        mContext.enforceCallingOrSelfPermission(
17274                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17275        int callingUid = Binder.getCallingUid();
17276        enforceOwnerRights(ownerPackage, callingUid);
17277        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17278        synchronized (mPackages) {
17279            CrossProfileIntentResolver resolver =
17280                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17281            ArraySet<CrossProfileIntentFilter> set =
17282                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17283            for (CrossProfileIntentFilter filter : set) {
17284                if (filter.getOwnerPackage().equals(ownerPackage)) {
17285                    resolver.removeFilter(filter);
17286                }
17287            }
17288            scheduleWritePackageRestrictionsLocked(sourceUserId);
17289        }
17290    }
17291
17292    // Enforcing that callingUid is owning pkg on userId
17293    private void enforceOwnerRights(String pkg, int callingUid) {
17294        // The system owns everything.
17295        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17296            return;
17297        }
17298        int callingUserId = UserHandle.getUserId(callingUid);
17299        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17300        if (pi == null) {
17301            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17302                    + callingUserId);
17303        }
17304        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17305            throw new SecurityException("Calling uid " + callingUid
17306                    + " does not own package " + pkg);
17307        }
17308    }
17309
17310    @Override
17311    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17312        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17313    }
17314
17315    private Intent getHomeIntent() {
17316        Intent intent = new Intent(Intent.ACTION_MAIN);
17317        intent.addCategory(Intent.CATEGORY_HOME);
17318        return intent;
17319    }
17320
17321    private IntentFilter getHomeFilter() {
17322        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17323        filter.addCategory(Intent.CATEGORY_HOME);
17324        filter.addCategory(Intent.CATEGORY_DEFAULT);
17325        return filter;
17326    }
17327
17328    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17329            int userId) {
17330        Intent intent  = getHomeIntent();
17331        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17332                PackageManager.GET_META_DATA, userId);
17333        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17334                true, false, false, userId);
17335
17336        allHomeCandidates.clear();
17337        if (list != null) {
17338            for (ResolveInfo ri : list) {
17339                allHomeCandidates.add(ri);
17340            }
17341        }
17342        return (preferred == null || preferred.activityInfo == null)
17343                ? null
17344                : new ComponentName(preferred.activityInfo.packageName,
17345                        preferred.activityInfo.name);
17346    }
17347
17348    @Override
17349    public void setHomeActivity(ComponentName comp, int userId) {
17350        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17351        getHomeActivitiesAsUser(homeActivities, userId);
17352
17353        boolean found = false;
17354
17355        final int size = homeActivities.size();
17356        final ComponentName[] set = new ComponentName[size];
17357        for (int i = 0; i < size; i++) {
17358            final ResolveInfo candidate = homeActivities.get(i);
17359            final ActivityInfo info = candidate.activityInfo;
17360            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17361            set[i] = activityName;
17362            if (!found && activityName.equals(comp)) {
17363                found = true;
17364            }
17365        }
17366        if (!found) {
17367            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17368                    + userId);
17369        }
17370        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17371                set, comp, userId);
17372    }
17373
17374    private @Nullable String getSetupWizardPackageName() {
17375        final Intent intent = new Intent(Intent.ACTION_MAIN);
17376        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17377
17378        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17379                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17380                        | MATCH_DISABLED_COMPONENTS,
17381                UserHandle.myUserId());
17382        if (matches.size() == 1) {
17383            return matches.get(0).getComponentInfo().packageName;
17384        } else {
17385            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17386                    + ": matches=" + matches);
17387            return null;
17388        }
17389    }
17390
17391    @Override
17392    public void setApplicationEnabledSetting(String appPackageName,
17393            int newState, int flags, int userId, String callingPackage) {
17394        if (!sUserManager.exists(userId)) return;
17395        if (callingPackage == null) {
17396            callingPackage = Integer.toString(Binder.getCallingUid());
17397        }
17398        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17399    }
17400
17401    @Override
17402    public void setComponentEnabledSetting(ComponentName componentName,
17403            int newState, int flags, int userId) {
17404        if (!sUserManager.exists(userId)) return;
17405        setEnabledSetting(componentName.getPackageName(),
17406                componentName.getClassName(), newState, flags, userId, null);
17407    }
17408
17409    private void setEnabledSetting(final String packageName, String className, int newState,
17410            final int flags, int userId, String callingPackage) {
17411        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17412              || newState == COMPONENT_ENABLED_STATE_ENABLED
17413              || newState == COMPONENT_ENABLED_STATE_DISABLED
17414              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17415              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17416            throw new IllegalArgumentException("Invalid new component state: "
17417                    + newState);
17418        }
17419        PackageSetting pkgSetting;
17420        final int uid = Binder.getCallingUid();
17421        final int permission;
17422        if (uid == Process.SYSTEM_UID) {
17423            permission = PackageManager.PERMISSION_GRANTED;
17424        } else {
17425            permission = mContext.checkCallingOrSelfPermission(
17426                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17427        }
17428        enforceCrossUserPermission(uid, userId,
17429                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17430        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17431        boolean sendNow = false;
17432        boolean isApp = (className == null);
17433        String componentName = isApp ? packageName : className;
17434        int packageUid = -1;
17435        ArrayList<String> components;
17436
17437        // writer
17438        synchronized (mPackages) {
17439            pkgSetting = mSettings.mPackages.get(packageName);
17440            if (pkgSetting == null) {
17441                if (className == null) {
17442                    throw new IllegalArgumentException("Unknown package: " + packageName);
17443                }
17444                throw new IllegalArgumentException(
17445                        "Unknown component: " + packageName + "/" + className);
17446            }
17447            // Allow root and verify that userId is not being specified by a different user
17448            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17449                throw new SecurityException(
17450                        "Permission Denial: attempt to change component state from pid="
17451                        + Binder.getCallingPid()
17452                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17453            }
17454            if (className == null) {
17455                // We're dealing with an application/package level state change
17456                if (pkgSetting.getEnabled(userId) == newState) {
17457                    // Nothing to do
17458                    return;
17459                }
17460                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17461                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17462                    // Don't care about who enables an app.
17463                    callingPackage = null;
17464                }
17465                pkgSetting.setEnabled(newState, userId, callingPackage);
17466                // pkgSetting.pkg.mSetEnabled = newState;
17467            } else {
17468                // We're dealing with a component level state change
17469                // First, verify that this is a valid class name.
17470                PackageParser.Package pkg = pkgSetting.pkg;
17471                if (pkg == null || !pkg.hasComponentClassName(className)) {
17472                    if (pkg != null &&
17473                            pkg.applicationInfo.targetSdkVersion >=
17474                                    Build.VERSION_CODES.JELLY_BEAN) {
17475                        throw new IllegalArgumentException("Component class " + className
17476                                + " does not exist in " + packageName);
17477                    } else {
17478                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17479                                + className + " does not exist in " + packageName);
17480                    }
17481                }
17482                switch (newState) {
17483                case COMPONENT_ENABLED_STATE_ENABLED:
17484                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17485                        return;
17486                    }
17487                    break;
17488                case COMPONENT_ENABLED_STATE_DISABLED:
17489                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17490                        return;
17491                    }
17492                    break;
17493                case COMPONENT_ENABLED_STATE_DEFAULT:
17494                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17495                        return;
17496                    }
17497                    break;
17498                default:
17499                    Slog.e(TAG, "Invalid new component state: " + newState);
17500                    return;
17501                }
17502            }
17503            scheduleWritePackageRestrictionsLocked(userId);
17504            components = mPendingBroadcasts.get(userId, packageName);
17505            final boolean newPackage = components == null;
17506            if (newPackage) {
17507                components = new ArrayList<String>();
17508            }
17509            if (!components.contains(componentName)) {
17510                components.add(componentName);
17511            }
17512            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17513                sendNow = true;
17514                // Purge entry from pending broadcast list if another one exists already
17515                // since we are sending one right away.
17516                mPendingBroadcasts.remove(userId, packageName);
17517            } else {
17518                if (newPackage) {
17519                    mPendingBroadcasts.put(userId, packageName, components);
17520                }
17521                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17522                    // Schedule a message
17523                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17524                }
17525            }
17526        }
17527
17528        long callingId = Binder.clearCallingIdentity();
17529        try {
17530            if (sendNow) {
17531                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17532                sendPackageChangedBroadcast(packageName,
17533                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17534            }
17535        } finally {
17536            Binder.restoreCallingIdentity(callingId);
17537        }
17538    }
17539
17540    @Override
17541    public void flushPackageRestrictionsAsUser(int userId) {
17542        if (!sUserManager.exists(userId)) {
17543            return;
17544        }
17545        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17546                false /* checkShell */, "flushPackageRestrictions");
17547        synchronized (mPackages) {
17548            mSettings.writePackageRestrictionsLPr(userId);
17549            mDirtyUsers.remove(userId);
17550            if (mDirtyUsers.isEmpty()) {
17551                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17552            }
17553        }
17554    }
17555
17556    private void sendPackageChangedBroadcast(String packageName,
17557            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17558        if (DEBUG_INSTALL)
17559            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17560                    + componentNames);
17561        Bundle extras = new Bundle(4);
17562        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17563        String nameList[] = new String[componentNames.size()];
17564        componentNames.toArray(nameList);
17565        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17566        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17567        extras.putInt(Intent.EXTRA_UID, packageUid);
17568        // If this is not reporting a change of the overall package, then only send it
17569        // to registered receivers.  We don't want to launch a swath of apps for every
17570        // little component state change.
17571        final int flags = !componentNames.contains(packageName)
17572                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17573        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17574                new int[] {UserHandle.getUserId(packageUid)});
17575    }
17576
17577    @Override
17578    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17579        if (!sUserManager.exists(userId)) return;
17580        final int uid = Binder.getCallingUid();
17581        final int permission = mContext.checkCallingOrSelfPermission(
17582                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17583        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17584        enforceCrossUserPermission(uid, userId,
17585                true /* requireFullPermission */, true /* checkShell */, "stop package");
17586        // writer
17587        synchronized (mPackages) {
17588            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17589                    allowedByPermission, uid, userId)) {
17590                scheduleWritePackageRestrictionsLocked(userId);
17591            }
17592        }
17593    }
17594
17595    @Override
17596    public String getInstallerPackageName(String packageName) {
17597        // reader
17598        synchronized (mPackages) {
17599            return mSettings.getInstallerPackageNameLPr(packageName);
17600        }
17601    }
17602
17603    public boolean isOrphaned(String packageName) {
17604        // reader
17605        synchronized (mPackages) {
17606            return mSettings.isOrphaned(packageName);
17607        }
17608    }
17609
17610    @Override
17611    public int getApplicationEnabledSetting(String packageName, int userId) {
17612        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17613        int uid = Binder.getCallingUid();
17614        enforceCrossUserPermission(uid, userId,
17615                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17616        // reader
17617        synchronized (mPackages) {
17618            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17619        }
17620    }
17621
17622    @Override
17623    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17624        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17625        int uid = Binder.getCallingUid();
17626        enforceCrossUserPermission(uid, userId,
17627                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17628        // reader
17629        synchronized (mPackages) {
17630            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17631        }
17632    }
17633
17634    @Override
17635    public void enterSafeMode() {
17636        enforceSystemOrRoot("Only the system can request entering safe mode");
17637
17638        if (!mSystemReady) {
17639            mSafeMode = true;
17640        }
17641    }
17642
17643    @Override
17644    public void systemReady() {
17645        mSystemReady = true;
17646
17647        // Read the compatibilty setting when the system is ready.
17648        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17649                mContext.getContentResolver(),
17650                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17651        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17652        if (DEBUG_SETTINGS) {
17653            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17654        }
17655
17656        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17657
17658        synchronized (mPackages) {
17659            // Verify that all of the preferred activity components actually
17660            // exist.  It is possible for applications to be updated and at
17661            // that point remove a previously declared activity component that
17662            // had been set as a preferred activity.  We try to clean this up
17663            // the next time we encounter that preferred activity, but it is
17664            // possible for the user flow to never be able to return to that
17665            // situation so here we do a sanity check to make sure we haven't
17666            // left any junk around.
17667            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17668            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17669                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17670                removed.clear();
17671                for (PreferredActivity pa : pir.filterSet()) {
17672                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17673                        removed.add(pa);
17674                    }
17675                }
17676                if (removed.size() > 0) {
17677                    for (int r=0; r<removed.size(); r++) {
17678                        PreferredActivity pa = removed.get(r);
17679                        Slog.w(TAG, "Removing dangling preferred activity: "
17680                                + pa.mPref.mComponent);
17681                        pir.removeFilter(pa);
17682                    }
17683                    mSettings.writePackageRestrictionsLPr(
17684                            mSettings.mPreferredActivities.keyAt(i));
17685                }
17686            }
17687
17688            for (int userId : UserManagerService.getInstance().getUserIds()) {
17689                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17690                    grantPermissionsUserIds = ArrayUtils.appendInt(
17691                            grantPermissionsUserIds, userId);
17692                }
17693            }
17694        }
17695        sUserManager.systemReady();
17696
17697        // If we upgraded grant all default permissions before kicking off.
17698        for (int userId : grantPermissionsUserIds) {
17699            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17700        }
17701
17702        // Kick off any messages waiting for system ready
17703        if (mPostSystemReadyMessages != null) {
17704            for (Message msg : mPostSystemReadyMessages) {
17705                msg.sendToTarget();
17706            }
17707            mPostSystemReadyMessages = null;
17708        }
17709
17710        // Watch for external volumes that come and go over time
17711        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17712        storage.registerListener(mStorageListener);
17713
17714        mInstallerService.systemReady();
17715        mPackageDexOptimizer.systemReady();
17716
17717        MountServiceInternal mountServiceInternal = LocalServices.getService(
17718                MountServiceInternal.class);
17719        mountServiceInternal.addExternalStoragePolicy(
17720                new MountServiceInternal.ExternalStorageMountPolicy() {
17721            @Override
17722            public int getMountMode(int uid, String packageName) {
17723                if (Process.isIsolated(uid)) {
17724                    return Zygote.MOUNT_EXTERNAL_NONE;
17725                }
17726                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17727                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17728                }
17729                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17730                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17731                }
17732                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17733                    return Zygote.MOUNT_EXTERNAL_READ;
17734                }
17735                return Zygote.MOUNT_EXTERNAL_WRITE;
17736            }
17737
17738            @Override
17739            public boolean hasExternalStorage(int uid, String packageName) {
17740                return true;
17741            }
17742        });
17743
17744        // Now that we're mostly running, clean up stale users and apps
17745        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17746        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17747    }
17748
17749    @Override
17750    public boolean isSafeMode() {
17751        return mSafeMode;
17752    }
17753
17754    @Override
17755    public boolean hasSystemUidErrors() {
17756        return mHasSystemUidErrors;
17757    }
17758
17759    static String arrayToString(int[] array) {
17760        StringBuffer buf = new StringBuffer(128);
17761        buf.append('[');
17762        if (array != null) {
17763            for (int i=0; i<array.length; i++) {
17764                if (i > 0) buf.append(", ");
17765                buf.append(array[i]);
17766            }
17767        }
17768        buf.append(']');
17769        return buf.toString();
17770    }
17771
17772    static class DumpState {
17773        public static final int DUMP_LIBS = 1 << 0;
17774        public static final int DUMP_FEATURES = 1 << 1;
17775        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17776        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17777        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17778        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17779        public static final int DUMP_PERMISSIONS = 1 << 6;
17780        public static final int DUMP_PACKAGES = 1 << 7;
17781        public static final int DUMP_SHARED_USERS = 1 << 8;
17782        public static final int DUMP_MESSAGES = 1 << 9;
17783        public static final int DUMP_PROVIDERS = 1 << 10;
17784        public static final int DUMP_VERIFIERS = 1 << 11;
17785        public static final int DUMP_PREFERRED = 1 << 12;
17786        public static final int DUMP_PREFERRED_XML = 1 << 13;
17787        public static final int DUMP_KEYSETS = 1 << 14;
17788        public static final int DUMP_VERSION = 1 << 15;
17789        public static final int DUMP_INSTALLS = 1 << 16;
17790        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17791        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17792        public static final int DUMP_FROZEN = 1 << 19;
17793        public static final int DUMP_DEXOPT = 1 << 20;
17794
17795        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17796
17797        private int mTypes;
17798
17799        private int mOptions;
17800
17801        private boolean mTitlePrinted;
17802
17803        private SharedUserSetting mSharedUser;
17804
17805        public boolean isDumping(int type) {
17806            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17807                return true;
17808            }
17809
17810            return (mTypes & type) != 0;
17811        }
17812
17813        public void setDump(int type) {
17814            mTypes |= type;
17815        }
17816
17817        public boolean isOptionEnabled(int option) {
17818            return (mOptions & option) != 0;
17819        }
17820
17821        public void setOptionEnabled(int option) {
17822            mOptions |= option;
17823        }
17824
17825        public boolean onTitlePrinted() {
17826            final boolean printed = mTitlePrinted;
17827            mTitlePrinted = true;
17828            return printed;
17829        }
17830
17831        public boolean getTitlePrinted() {
17832            return mTitlePrinted;
17833        }
17834
17835        public void setTitlePrinted(boolean enabled) {
17836            mTitlePrinted = enabled;
17837        }
17838
17839        public SharedUserSetting getSharedUser() {
17840            return mSharedUser;
17841        }
17842
17843        public void setSharedUser(SharedUserSetting user) {
17844            mSharedUser = user;
17845        }
17846    }
17847
17848    @Override
17849    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17850            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17851        (new PackageManagerShellCommand(this)).exec(
17852                this, in, out, err, args, resultReceiver);
17853    }
17854
17855    @Override
17856    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17857        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17858                != PackageManager.PERMISSION_GRANTED) {
17859            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17860                    + Binder.getCallingPid()
17861                    + ", uid=" + Binder.getCallingUid()
17862                    + " without permission "
17863                    + android.Manifest.permission.DUMP);
17864            return;
17865        }
17866
17867        DumpState dumpState = new DumpState();
17868        boolean fullPreferred = false;
17869        boolean checkin = false;
17870
17871        String packageName = null;
17872        ArraySet<String> permissionNames = null;
17873
17874        int opti = 0;
17875        while (opti < args.length) {
17876            String opt = args[opti];
17877            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17878                break;
17879            }
17880            opti++;
17881
17882            if ("-a".equals(opt)) {
17883                // Right now we only know how to print all.
17884            } else if ("-h".equals(opt)) {
17885                pw.println("Package manager dump options:");
17886                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17887                pw.println("    --checkin: dump for a checkin");
17888                pw.println("    -f: print details of intent filters");
17889                pw.println("    -h: print this help");
17890                pw.println("  cmd may be one of:");
17891                pw.println("    l[ibraries]: list known shared libraries");
17892                pw.println("    f[eatures]: list device features");
17893                pw.println("    k[eysets]: print known keysets");
17894                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17895                pw.println("    perm[issions]: dump permissions");
17896                pw.println("    permission [name ...]: dump declaration and use of given permission");
17897                pw.println("    pref[erred]: print preferred package settings");
17898                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17899                pw.println("    prov[iders]: dump content providers");
17900                pw.println("    p[ackages]: dump installed packages");
17901                pw.println("    s[hared-users]: dump shared user IDs");
17902                pw.println("    m[essages]: print collected runtime messages");
17903                pw.println("    v[erifiers]: print package verifier info");
17904                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17905                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17906                pw.println("    version: print database version info");
17907                pw.println("    write: write current settings now");
17908                pw.println("    installs: details about install sessions");
17909                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17910                pw.println("    dexopt: dump dexopt state");
17911                pw.println("    <package.name>: info about given package");
17912                return;
17913            } else if ("--checkin".equals(opt)) {
17914                checkin = true;
17915            } else if ("-f".equals(opt)) {
17916                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17917            } else {
17918                pw.println("Unknown argument: " + opt + "; use -h for help");
17919            }
17920        }
17921
17922        // Is the caller requesting to dump a particular piece of data?
17923        if (opti < args.length) {
17924            String cmd = args[opti];
17925            opti++;
17926            // Is this a package name?
17927            if ("android".equals(cmd) || cmd.contains(".")) {
17928                packageName = cmd;
17929                // When dumping a single package, we always dump all of its
17930                // filter information since the amount of data will be reasonable.
17931                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17932            } else if ("check-permission".equals(cmd)) {
17933                if (opti >= args.length) {
17934                    pw.println("Error: check-permission missing permission argument");
17935                    return;
17936                }
17937                String perm = args[opti];
17938                opti++;
17939                if (opti >= args.length) {
17940                    pw.println("Error: check-permission missing package argument");
17941                    return;
17942                }
17943                String pkg = args[opti];
17944                opti++;
17945                int user = UserHandle.getUserId(Binder.getCallingUid());
17946                if (opti < args.length) {
17947                    try {
17948                        user = Integer.parseInt(args[opti]);
17949                    } catch (NumberFormatException e) {
17950                        pw.println("Error: check-permission user argument is not a number: "
17951                                + args[opti]);
17952                        return;
17953                    }
17954                }
17955                pw.println(checkPermission(perm, pkg, user));
17956                return;
17957            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17958                dumpState.setDump(DumpState.DUMP_LIBS);
17959            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17960                dumpState.setDump(DumpState.DUMP_FEATURES);
17961            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17962                if (opti >= args.length) {
17963                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17964                            | DumpState.DUMP_SERVICE_RESOLVERS
17965                            | DumpState.DUMP_RECEIVER_RESOLVERS
17966                            | DumpState.DUMP_CONTENT_RESOLVERS);
17967                } else {
17968                    while (opti < args.length) {
17969                        String name = args[opti];
17970                        if ("a".equals(name) || "activity".equals(name)) {
17971                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17972                        } else if ("s".equals(name) || "service".equals(name)) {
17973                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17974                        } else if ("r".equals(name) || "receiver".equals(name)) {
17975                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17976                        } else if ("c".equals(name) || "content".equals(name)) {
17977                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17978                        } else {
17979                            pw.println("Error: unknown resolver table type: " + name);
17980                            return;
17981                        }
17982                        opti++;
17983                    }
17984                }
17985            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17986                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17987            } else if ("permission".equals(cmd)) {
17988                if (opti >= args.length) {
17989                    pw.println("Error: permission requires permission name");
17990                    return;
17991                }
17992                permissionNames = new ArraySet<>();
17993                while (opti < args.length) {
17994                    permissionNames.add(args[opti]);
17995                    opti++;
17996                }
17997                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17998                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17999            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18000                dumpState.setDump(DumpState.DUMP_PREFERRED);
18001            } else if ("preferred-xml".equals(cmd)) {
18002                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18003                if (opti < args.length && "--full".equals(args[opti])) {
18004                    fullPreferred = true;
18005                    opti++;
18006                }
18007            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18008                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18009            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18010                dumpState.setDump(DumpState.DUMP_PACKAGES);
18011            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18012                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18013            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18014                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18015            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18016                dumpState.setDump(DumpState.DUMP_MESSAGES);
18017            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18018                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18019            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18020                    || "intent-filter-verifiers".equals(cmd)) {
18021                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18022            } else if ("version".equals(cmd)) {
18023                dumpState.setDump(DumpState.DUMP_VERSION);
18024            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18025                dumpState.setDump(DumpState.DUMP_KEYSETS);
18026            } else if ("installs".equals(cmd)) {
18027                dumpState.setDump(DumpState.DUMP_INSTALLS);
18028            } else if ("frozen".equals(cmd)) {
18029                dumpState.setDump(DumpState.DUMP_FROZEN);
18030            } else if ("dexopt".equals(cmd)) {
18031                dumpState.setDump(DumpState.DUMP_DEXOPT);
18032            } else if ("write".equals(cmd)) {
18033                synchronized (mPackages) {
18034                    mSettings.writeLPr();
18035                    pw.println("Settings written.");
18036                    return;
18037                }
18038            }
18039        }
18040
18041        if (checkin) {
18042            pw.println("vers,1");
18043        }
18044
18045        // reader
18046        synchronized (mPackages) {
18047            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18048                if (!checkin) {
18049                    if (dumpState.onTitlePrinted())
18050                        pw.println();
18051                    pw.println("Database versions:");
18052                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18053                }
18054            }
18055
18056            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18057                if (!checkin) {
18058                    if (dumpState.onTitlePrinted())
18059                        pw.println();
18060                    pw.println("Verifiers:");
18061                    pw.print("  Required: ");
18062                    pw.print(mRequiredVerifierPackage);
18063                    pw.print(" (uid=");
18064                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18065                            UserHandle.USER_SYSTEM));
18066                    pw.println(")");
18067                } else if (mRequiredVerifierPackage != null) {
18068                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18069                    pw.print(",");
18070                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18071                            UserHandle.USER_SYSTEM));
18072                }
18073            }
18074
18075            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18076                    packageName == null) {
18077                if (mIntentFilterVerifierComponent != null) {
18078                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18079                    if (!checkin) {
18080                        if (dumpState.onTitlePrinted())
18081                            pw.println();
18082                        pw.println("Intent Filter Verifier:");
18083                        pw.print("  Using: ");
18084                        pw.print(verifierPackageName);
18085                        pw.print(" (uid=");
18086                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18087                                UserHandle.USER_SYSTEM));
18088                        pw.println(")");
18089                    } else if (verifierPackageName != null) {
18090                        pw.print("ifv,"); pw.print(verifierPackageName);
18091                        pw.print(",");
18092                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18093                                UserHandle.USER_SYSTEM));
18094                    }
18095                } else {
18096                    pw.println();
18097                    pw.println("No Intent Filter Verifier available!");
18098                }
18099            }
18100
18101            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18102                boolean printedHeader = false;
18103                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18104                while (it.hasNext()) {
18105                    String name = it.next();
18106                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18107                    if (!checkin) {
18108                        if (!printedHeader) {
18109                            if (dumpState.onTitlePrinted())
18110                                pw.println();
18111                            pw.println("Libraries:");
18112                            printedHeader = true;
18113                        }
18114                        pw.print("  ");
18115                    } else {
18116                        pw.print("lib,");
18117                    }
18118                    pw.print(name);
18119                    if (!checkin) {
18120                        pw.print(" -> ");
18121                    }
18122                    if (ent.path != null) {
18123                        if (!checkin) {
18124                            pw.print("(jar) ");
18125                            pw.print(ent.path);
18126                        } else {
18127                            pw.print(",jar,");
18128                            pw.print(ent.path);
18129                        }
18130                    } else {
18131                        if (!checkin) {
18132                            pw.print("(apk) ");
18133                            pw.print(ent.apk);
18134                        } else {
18135                            pw.print(",apk,");
18136                            pw.print(ent.apk);
18137                        }
18138                    }
18139                    pw.println();
18140                }
18141            }
18142
18143            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18144                if (dumpState.onTitlePrinted())
18145                    pw.println();
18146                if (!checkin) {
18147                    pw.println("Features:");
18148                }
18149
18150                for (FeatureInfo feat : mAvailableFeatures.values()) {
18151                    if (checkin) {
18152                        pw.print("feat,");
18153                        pw.print(feat.name);
18154                        pw.print(",");
18155                        pw.println(feat.version);
18156                    } else {
18157                        pw.print("  ");
18158                        pw.print(feat.name);
18159                        if (feat.version > 0) {
18160                            pw.print(" version=");
18161                            pw.print(feat.version);
18162                        }
18163                        pw.println();
18164                    }
18165                }
18166            }
18167
18168            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18169                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18170                        : "Activity Resolver Table:", "  ", packageName,
18171                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18172                    dumpState.setTitlePrinted(true);
18173                }
18174            }
18175            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18176                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18177                        : "Receiver Resolver Table:", "  ", packageName,
18178                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18179                    dumpState.setTitlePrinted(true);
18180                }
18181            }
18182            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18183                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18184                        : "Service Resolver Table:", "  ", packageName,
18185                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18186                    dumpState.setTitlePrinted(true);
18187                }
18188            }
18189            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18190                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18191                        : "Provider Resolver Table:", "  ", packageName,
18192                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18193                    dumpState.setTitlePrinted(true);
18194                }
18195            }
18196
18197            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18198                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18199                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18200                    int user = mSettings.mPreferredActivities.keyAt(i);
18201                    if (pir.dump(pw,
18202                            dumpState.getTitlePrinted()
18203                                ? "\nPreferred Activities User " + user + ":"
18204                                : "Preferred Activities User " + user + ":", "  ",
18205                            packageName, true, false)) {
18206                        dumpState.setTitlePrinted(true);
18207                    }
18208                }
18209            }
18210
18211            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18212                pw.flush();
18213                FileOutputStream fout = new FileOutputStream(fd);
18214                BufferedOutputStream str = new BufferedOutputStream(fout);
18215                XmlSerializer serializer = new FastXmlSerializer();
18216                try {
18217                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18218                    serializer.startDocument(null, true);
18219                    serializer.setFeature(
18220                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18221                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18222                    serializer.endDocument();
18223                    serializer.flush();
18224                } catch (IllegalArgumentException e) {
18225                    pw.println("Failed writing: " + e);
18226                } catch (IllegalStateException e) {
18227                    pw.println("Failed writing: " + e);
18228                } catch (IOException e) {
18229                    pw.println("Failed writing: " + e);
18230                }
18231            }
18232
18233            if (!checkin
18234                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18235                    && packageName == null) {
18236                pw.println();
18237                int count = mSettings.mPackages.size();
18238                if (count == 0) {
18239                    pw.println("No applications!");
18240                    pw.println();
18241                } else {
18242                    final String prefix = "  ";
18243                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18244                    if (allPackageSettings.size() == 0) {
18245                        pw.println("No domain preferred apps!");
18246                        pw.println();
18247                    } else {
18248                        pw.println("App verification status:");
18249                        pw.println();
18250                        count = 0;
18251                        for (PackageSetting ps : allPackageSettings) {
18252                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18253                            if (ivi == null || ivi.getPackageName() == null) continue;
18254                            pw.println(prefix + "Package: " + ivi.getPackageName());
18255                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18256                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18257                            pw.println();
18258                            count++;
18259                        }
18260                        if (count == 0) {
18261                            pw.println(prefix + "No app verification established.");
18262                            pw.println();
18263                        }
18264                        for (int userId : sUserManager.getUserIds()) {
18265                            pw.println("App linkages for user " + userId + ":");
18266                            pw.println();
18267                            count = 0;
18268                            for (PackageSetting ps : allPackageSettings) {
18269                                final long status = ps.getDomainVerificationStatusForUser(userId);
18270                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18271                                    continue;
18272                                }
18273                                pw.println(prefix + "Package: " + ps.name);
18274                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18275                                String statusStr = IntentFilterVerificationInfo.
18276                                        getStatusStringFromValue(status);
18277                                pw.println(prefix + "Status:  " + statusStr);
18278                                pw.println();
18279                                count++;
18280                            }
18281                            if (count == 0) {
18282                                pw.println(prefix + "No configured app linkages.");
18283                                pw.println();
18284                            }
18285                        }
18286                    }
18287                }
18288            }
18289
18290            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18291                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18292                if (packageName == null && permissionNames == null) {
18293                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18294                        if (iperm == 0) {
18295                            if (dumpState.onTitlePrinted())
18296                                pw.println();
18297                            pw.println("AppOp Permissions:");
18298                        }
18299                        pw.print("  AppOp Permission ");
18300                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18301                        pw.println(":");
18302                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18303                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18304                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18305                        }
18306                    }
18307                }
18308            }
18309
18310            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18311                boolean printedSomething = false;
18312                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18313                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18314                        continue;
18315                    }
18316                    if (!printedSomething) {
18317                        if (dumpState.onTitlePrinted())
18318                            pw.println();
18319                        pw.println("Registered ContentProviders:");
18320                        printedSomething = true;
18321                    }
18322                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18323                    pw.print("    "); pw.println(p.toString());
18324                }
18325                printedSomething = false;
18326                for (Map.Entry<String, PackageParser.Provider> entry :
18327                        mProvidersByAuthority.entrySet()) {
18328                    PackageParser.Provider p = entry.getValue();
18329                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18330                        continue;
18331                    }
18332                    if (!printedSomething) {
18333                        if (dumpState.onTitlePrinted())
18334                            pw.println();
18335                        pw.println("ContentProvider Authorities:");
18336                        printedSomething = true;
18337                    }
18338                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18339                    pw.print("    "); pw.println(p.toString());
18340                    if (p.info != null && p.info.applicationInfo != null) {
18341                        final String appInfo = p.info.applicationInfo.toString();
18342                        pw.print("      applicationInfo="); pw.println(appInfo);
18343                    }
18344                }
18345            }
18346
18347            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18348                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18349            }
18350
18351            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18352                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18353            }
18354
18355            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18356                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18357            }
18358
18359            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18360                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18361            }
18362
18363            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18364                // XXX should handle packageName != null by dumping only install data that
18365                // the given package is involved with.
18366                if (dumpState.onTitlePrinted()) pw.println();
18367                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18368            }
18369
18370            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18371                // XXX should handle packageName != null by dumping only install data that
18372                // the given package is involved with.
18373                if (dumpState.onTitlePrinted()) pw.println();
18374
18375                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18376                ipw.println();
18377                ipw.println("Frozen packages:");
18378                ipw.increaseIndent();
18379                if (mFrozenPackages.size() == 0) {
18380                    ipw.println("(none)");
18381                } else {
18382                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18383                        ipw.println(mFrozenPackages.valueAt(i));
18384                    }
18385                }
18386                ipw.decreaseIndent();
18387            }
18388
18389            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18390                if (dumpState.onTitlePrinted()) pw.println();
18391                dumpDexoptStateLPr(pw, packageName);
18392            }
18393
18394            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18395                if (dumpState.onTitlePrinted()) pw.println();
18396                mSettings.dumpReadMessagesLPr(pw, dumpState);
18397
18398                pw.println();
18399                pw.println("Package warning messages:");
18400                BufferedReader in = null;
18401                String line = null;
18402                try {
18403                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18404                    while ((line = in.readLine()) != null) {
18405                        if (line.contains("ignored: updated version")) continue;
18406                        pw.println(line);
18407                    }
18408                } catch (IOException ignored) {
18409                } finally {
18410                    IoUtils.closeQuietly(in);
18411                }
18412            }
18413
18414            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18415                BufferedReader in = null;
18416                String line = null;
18417                try {
18418                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18419                    while ((line = in.readLine()) != null) {
18420                        if (line.contains("ignored: updated version")) continue;
18421                        pw.print("msg,");
18422                        pw.println(line);
18423                    }
18424                } catch (IOException ignored) {
18425                } finally {
18426                    IoUtils.closeQuietly(in);
18427                }
18428            }
18429        }
18430    }
18431
18432    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18433        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18434        ipw.println();
18435        ipw.println("Dexopt state:");
18436        ipw.increaseIndent();
18437        Collection<PackageParser.Package> packages = null;
18438        if (packageName != null) {
18439            PackageParser.Package targetPackage = mPackages.get(packageName);
18440            if (targetPackage != null) {
18441                packages = Collections.singletonList(targetPackage);
18442            } else {
18443                ipw.println("Unable to find package: " + packageName);
18444                return;
18445            }
18446        } else {
18447            packages = mPackages.values();
18448        }
18449
18450        for (PackageParser.Package pkg : packages) {
18451            ipw.println("[" + pkg.packageName + "]");
18452            ipw.increaseIndent();
18453            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18454            ipw.decreaseIndent();
18455        }
18456    }
18457
18458    private String dumpDomainString(String packageName) {
18459        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18460                .getList();
18461        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18462
18463        ArraySet<String> result = new ArraySet<>();
18464        if (iviList.size() > 0) {
18465            for (IntentFilterVerificationInfo ivi : iviList) {
18466                for (String host : ivi.getDomains()) {
18467                    result.add(host);
18468                }
18469            }
18470        }
18471        if (filters != null && filters.size() > 0) {
18472            for (IntentFilter filter : filters) {
18473                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18474                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18475                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18476                    result.addAll(filter.getHostsList());
18477                }
18478            }
18479        }
18480
18481        StringBuilder sb = new StringBuilder(result.size() * 16);
18482        for (String domain : result) {
18483            if (sb.length() > 0) sb.append(" ");
18484            sb.append(domain);
18485        }
18486        return sb.toString();
18487    }
18488
18489    // ------- apps on sdcard specific code -------
18490    static final boolean DEBUG_SD_INSTALL = false;
18491
18492    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18493
18494    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18495
18496    private boolean mMediaMounted = false;
18497
18498    static String getEncryptKey() {
18499        try {
18500            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18501                    SD_ENCRYPTION_KEYSTORE_NAME);
18502            if (sdEncKey == null) {
18503                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18504                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18505                if (sdEncKey == null) {
18506                    Slog.e(TAG, "Failed to create encryption keys");
18507                    return null;
18508                }
18509            }
18510            return sdEncKey;
18511        } catch (NoSuchAlgorithmException nsae) {
18512            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18513            return null;
18514        } catch (IOException ioe) {
18515            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18516            return null;
18517        }
18518    }
18519
18520    /*
18521     * Update media status on PackageManager.
18522     */
18523    @Override
18524    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18525        int callingUid = Binder.getCallingUid();
18526        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18527            throw new SecurityException("Media status can only be updated by the system");
18528        }
18529        // reader; this apparently protects mMediaMounted, but should probably
18530        // be a different lock in that case.
18531        synchronized (mPackages) {
18532            Log.i(TAG, "Updating external media status from "
18533                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18534                    + (mediaStatus ? "mounted" : "unmounted"));
18535            if (DEBUG_SD_INSTALL)
18536                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18537                        + ", mMediaMounted=" + mMediaMounted);
18538            if (mediaStatus == mMediaMounted) {
18539                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18540                        : 0, -1);
18541                mHandler.sendMessage(msg);
18542                return;
18543            }
18544            mMediaMounted = mediaStatus;
18545        }
18546        // Queue up an async operation since the package installation may take a
18547        // little while.
18548        mHandler.post(new Runnable() {
18549            public void run() {
18550                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18551            }
18552        });
18553    }
18554
18555    /**
18556     * Called by MountService when the initial ASECs to scan are available.
18557     * Should block until all the ASEC containers are finished being scanned.
18558     */
18559    public void scanAvailableAsecs() {
18560        updateExternalMediaStatusInner(true, false, false);
18561    }
18562
18563    /*
18564     * Collect information of applications on external media, map them against
18565     * existing containers and update information based on current mount status.
18566     * Please note that we always have to report status if reportStatus has been
18567     * set to true especially when unloading packages.
18568     */
18569    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18570            boolean externalStorage) {
18571        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18572        int[] uidArr = EmptyArray.INT;
18573
18574        final String[] list = PackageHelper.getSecureContainerList();
18575        if (ArrayUtils.isEmpty(list)) {
18576            Log.i(TAG, "No secure containers found");
18577        } else {
18578            // Process list of secure containers and categorize them
18579            // as active or stale based on their package internal state.
18580
18581            // reader
18582            synchronized (mPackages) {
18583                for (String cid : list) {
18584                    // Leave stages untouched for now; installer service owns them
18585                    if (PackageInstallerService.isStageName(cid)) continue;
18586
18587                    if (DEBUG_SD_INSTALL)
18588                        Log.i(TAG, "Processing container " + cid);
18589                    String pkgName = getAsecPackageName(cid);
18590                    if (pkgName == null) {
18591                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18592                        continue;
18593                    }
18594                    if (DEBUG_SD_INSTALL)
18595                        Log.i(TAG, "Looking for pkg : " + pkgName);
18596
18597                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18598                    if (ps == null) {
18599                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18600                        continue;
18601                    }
18602
18603                    /*
18604                     * Skip packages that are not external if we're unmounting
18605                     * external storage.
18606                     */
18607                    if (externalStorage && !isMounted && !isExternal(ps)) {
18608                        continue;
18609                    }
18610
18611                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18612                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18613                    // The package status is changed only if the code path
18614                    // matches between settings and the container id.
18615                    if (ps.codePathString != null
18616                            && ps.codePathString.startsWith(args.getCodePath())) {
18617                        if (DEBUG_SD_INSTALL) {
18618                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18619                                    + " at code path: " + ps.codePathString);
18620                        }
18621
18622                        // We do have a valid package installed on sdcard
18623                        processCids.put(args, ps.codePathString);
18624                        final int uid = ps.appId;
18625                        if (uid != -1) {
18626                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18627                        }
18628                    } else {
18629                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18630                                + ps.codePathString);
18631                    }
18632                }
18633            }
18634
18635            Arrays.sort(uidArr);
18636        }
18637
18638        // Process packages with valid entries.
18639        if (isMounted) {
18640            if (DEBUG_SD_INSTALL)
18641                Log.i(TAG, "Loading packages");
18642            loadMediaPackages(processCids, uidArr, externalStorage);
18643            startCleaningPackages();
18644            mInstallerService.onSecureContainersAvailable();
18645        } else {
18646            if (DEBUG_SD_INSTALL)
18647                Log.i(TAG, "Unloading packages");
18648            unloadMediaPackages(processCids, uidArr, reportStatus);
18649        }
18650    }
18651
18652    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18653            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18654        final int size = infos.size();
18655        final String[] packageNames = new String[size];
18656        final int[] packageUids = new int[size];
18657        for (int i = 0; i < size; i++) {
18658            final ApplicationInfo info = infos.get(i);
18659            packageNames[i] = info.packageName;
18660            packageUids[i] = info.uid;
18661        }
18662        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18663                finishedReceiver);
18664    }
18665
18666    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18667            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18668        sendResourcesChangedBroadcast(mediaStatus, replacing,
18669                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18670    }
18671
18672    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18673            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18674        int size = pkgList.length;
18675        if (size > 0) {
18676            // Send broadcasts here
18677            Bundle extras = new Bundle();
18678            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18679            if (uidArr != null) {
18680                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18681            }
18682            if (replacing) {
18683                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18684            }
18685            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18686                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18687            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18688        }
18689    }
18690
18691   /*
18692     * Look at potentially valid container ids from processCids If package
18693     * information doesn't match the one on record or package scanning fails,
18694     * the cid is added to list of removeCids. We currently don't delete stale
18695     * containers.
18696     */
18697    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18698            boolean externalStorage) {
18699        ArrayList<String> pkgList = new ArrayList<String>();
18700        Set<AsecInstallArgs> keys = processCids.keySet();
18701
18702        for (AsecInstallArgs args : keys) {
18703            String codePath = processCids.get(args);
18704            if (DEBUG_SD_INSTALL)
18705                Log.i(TAG, "Loading container : " + args.cid);
18706            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18707            try {
18708                // Make sure there are no container errors first.
18709                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18710                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18711                            + " when installing from sdcard");
18712                    continue;
18713                }
18714                // Check code path here.
18715                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18716                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18717                            + " does not match one in settings " + codePath);
18718                    continue;
18719                }
18720                // Parse package
18721                int parseFlags = mDefParseFlags;
18722                if (args.isExternalAsec()) {
18723                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18724                }
18725                if (args.isFwdLocked()) {
18726                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18727                }
18728
18729                synchronized (mInstallLock) {
18730                    PackageParser.Package pkg = null;
18731                    try {
18732                        // Sadly we don't know the package name yet to freeze it
18733                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18734                                SCAN_IGNORE_FROZEN, 0, null);
18735                    } catch (PackageManagerException e) {
18736                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18737                    }
18738                    // Scan the package
18739                    if (pkg != null) {
18740                        /*
18741                         * TODO why is the lock being held? doPostInstall is
18742                         * called in other places without the lock. This needs
18743                         * to be straightened out.
18744                         */
18745                        // writer
18746                        synchronized (mPackages) {
18747                            retCode = PackageManager.INSTALL_SUCCEEDED;
18748                            pkgList.add(pkg.packageName);
18749                            // Post process args
18750                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18751                                    pkg.applicationInfo.uid);
18752                        }
18753                    } else {
18754                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18755                    }
18756                }
18757
18758            } finally {
18759                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18760                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18761                }
18762            }
18763        }
18764        // writer
18765        synchronized (mPackages) {
18766            // If the platform SDK has changed since the last time we booted,
18767            // we need to re-grant app permission to catch any new ones that
18768            // appear. This is really a hack, and means that apps can in some
18769            // cases get permissions that the user didn't initially explicitly
18770            // allow... it would be nice to have some better way to handle
18771            // this situation.
18772            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18773                    : mSettings.getInternalVersion();
18774            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18775                    : StorageManager.UUID_PRIVATE_INTERNAL;
18776
18777            int updateFlags = UPDATE_PERMISSIONS_ALL;
18778            if (ver.sdkVersion != mSdkVersion) {
18779                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18780                        + mSdkVersion + "; regranting permissions for external");
18781                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18782            }
18783            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18784
18785            // Yay, everything is now upgraded
18786            ver.forceCurrent();
18787
18788            // can downgrade to reader
18789            // Persist settings
18790            mSettings.writeLPr();
18791        }
18792        // Send a broadcast to let everyone know we are done processing
18793        if (pkgList.size() > 0) {
18794            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18795        }
18796    }
18797
18798   /*
18799     * Utility method to unload a list of specified containers
18800     */
18801    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18802        // Just unmount all valid containers.
18803        for (AsecInstallArgs arg : cidArgs) {
18804            synchronized (mInstallLock) {
18805                arg.doPostDeleteLI(false);
18806           }
18807       }
18808   }
18809
18810    /*
18811     * Unload packages mounted on external media. This involves deleting package
18812     * data from internal structures, sending broadcasts about disabled packages,
18813     * gc'ing to free up references, unmounting all secure containers
18814     * corresponding to packages on external media, and posting a
18815     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18816     * that we always have to post this message if status has been requested no
18817     * matter what.
18818     */
18819    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18820            final boolean reportStatus) {
18821        if (DEBUG_SD_INSTALL)
18822            Log.i(TAG, "unloading media packages");
18823        ArrayList<String> pkgList = new ArrayList<String>();
18824        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18825        final Set<AsecInstallArgs> keys = processCids.keySet();
18826        for (AsecInstallArgs args : keys) {
18827            String pkgName = args.getPackageName();
18828            if (DEBUG_SD_INSTALL)
18829                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18830            // Delete package internally
18831            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18832            synchronized (mInstallLock) {
18833                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18834                final boolean res;
18835                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
18836                        "unloadMediaPackages")) {
18837                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
18838                            null);
18839                }
18840                if (res) {
18841                    pkgList.add(pkgName);
18842                } else {
18843                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18844                    failedList.add(args);
18845                }
18846            }
18847        }
18848
18849        // reader
18850        synchronized (mPackages) {
18851            // We didn't update the settings after removing each package;
18852            // write them now for all packages.
18853            mSettings.writeLPr();
18854        }
18855
18856        // We have to absolutely send UPDATED_MEDIA_STATUS only
18857        // after confirming that all the receivers processed the ordered
18858        // broadcast when packages get disabled, force a gc to clean things up.
18859        // and unload all the containers.
18860        if (pkgList.size() > 0) {
18861            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18862                    new IIntentReceiver.Stub() {
18863                public void performReceive(Intent intent, int resultCode, String data,
18864                        Bundle extras, boolean ordered, boolean sticky,
18865                        int sendingUser) throws RemoteException {
18866                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18867                            reportStatus ? 1 : 0, 1, keys);
18868                    mHandler.sendMessage(msg);
18869                }
18870            });
18871        } else {
18872            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18873                    keys);
18874            mHandler.sendMessage(msg);
18875        }
18876    }
18877
18878    private void loadPrivatePackages(final VolumeInfo vol) {
18879        mHandler.post(new Runnable() {
18880            @Override
18881            public void run() {
18882                loadPrivatePackagesInner(vol);
18883            }
18884        });
18885    }
18886
18887    private void loadPrivatePackagesInner(VolumeInfo vol) {
18888        final String volumeUuid = vol.fsUuid;
18889        if (TextUtils.isEmpty(volumeUuid)) {
18890            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18891            return;
18892        }
18893
18894        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
18895        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18896        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18897
18898        final VersionInfo ver;
18899        final List<PackageSetting> packages;
18900        synchronized (mPackages) {
18901            ver = mSettings.findOrCreateVersion(volumeUuid);
18902            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18903        }
18904
18905        for (PackageSetting ps : packages) {
18906            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
18907            synchronized (mInstallLock) {
18908                final PackageParser.Package pkg;
18909                try {
18910                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18911                    loaded.add(pkg.applicationInfo);
18912
18913                } catch (PackageManagerException e) {
18914                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18915                }
18916
18917                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18918                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
18919                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
18920                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18921                }
18922            }
18923        }
18924
18925        // Reconcile app data for all started/unlocked users
18926        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18927        final UserManager um = mContext.getSystemService(UserManager.class);
18928        for (UserInfo user : um.getUsers()) {
18929            final int flags;
18930            if (um.isUserUnlockingOrUnlocked(user.id)) {
18931                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18932            } else if (um.isUserRunning(user.id)) {
18933                flags = StorageManager.FLAG_STORAGE_DE;
18934            } else {
18935                continue;
18936            }
18937
18938            try {
18939                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18940                synchronized (mInstallLock) {
18941                    reconcileAppsDataLI(volumeUuid, user.id, flags);
18942                }
18943            } catch (IllegalStateException e) {
18944                // Device was probably ejected, and we'll process that event momentarily
18945                Slog.w(TAG, "Failed to prepare storage: " + e);
18946            }
18947        }
18948
18949        synchronized (mPackages) {
18950            int updateFlags = UPDATE_PERMISSIONS_ALL;
18951            if (ver.sdkVersion != mSdkVersion) {
18952                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18953                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18954                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18955            }
18956            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18957
18958            // Yay, everything is now upgraded
18959            ver.forceCurrent();
18960
18961            mSettings.writeLPr();
18962        }
18963
18964        for (PackageFreezer freezer : freezers) {
18965            freezer.close();
18966        }
18967
18968        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18969        sendResourcesChangedBroadcast(true, false, loaded, null);
18970    }
18971
18972    private void unloadPrivatePackages(final VolumeInfo vol) {
18973        mHandler.post(new Runnable() {
18974            @Override
18975            public void run() {
18976                unloadPrivatePackagesInner(vol);
18977            }
18978        });
18979    }
18980
18981    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18982        final String volumeUuid = vol.fsUuid;
18983        if (TextUtils.isEmpty(volumeUuid)) {
18984            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18985            return;
18986        }
18987
18988        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18989        synchronized (mInstallLock) {
18990        synchronized (mPackages) {
18991            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18992            for (PackageSetting ps : packages) {
18993                if (ps.pkg == null) continue;
18994
18995                final ApplicationInfo info = ps.pkg.applicationInfo;
18996                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
18997                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18998
18999                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19000                        "unloadPrivatePackagesInner")) {
19001                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19002                            false, null)) {
19003                        unloaded.add(info);
19004                    } else {
19005                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19006                    }
19007                }
19008            }
19009
19010            mSettings.writeLPr();
19011        }
19012        }
19013
19014        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19015        sendResourcesChangedBroadcast(false, false, unloaded, null);
19016    }
19017
19018    /**
19019     * Prepare storage areas for given user on all mounted devices.
19020     */
19021    void prepareUserData(int userId, int userSerial, int flags) {
19022        synchronized (mInstallLock) {
19023            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19024            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19025                final String volumeUuid = vol.getFsUuid();
19026                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19027            }
19028        }
19029    }
19030
19031    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19032            boolean allowRecover) {
19033        // Prepare storage and verify that serial numbers are consistent; if
19034        // there's a mismatch we need to destroy to avoid leaking data
19035        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19036        try {
19037            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19038
19039            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19040                UserManagerService.enforceSerialNumber(
19041                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19042            }
19043            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19044                UserManagerService.enforceSerialNumber(
19045                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19046            }
19047
19048            synchronized (mInstallLock) {
19049                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19050            }
19051        } catch (Exception e) {
19052            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19053                    + " because we failed to prepare: " + e);
19054            destroyUserDataLI(volumeUuid, userId,
19055                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19056
19057            if (allowRecover) {
19058                // Try one last time; if we fail again we're really in trouble
19059                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19060            }
19061        }
19062    }
19063
19064    /**
19065     * Destroy storage areas for given user on all mounted devices.
19066     */
19067    void destroyUserData(int userId, int flags) {
19068        synchronized (mInstallLock) {
19069            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19070            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19071                final String volumeUuid = vol.getFsUuid();
19072                destroyUserDataLI(volumeUuid, userId, flags);
19073            }
19074        }
19075    }
19076
19077    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19078        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19079        try {
19080            // Clean up app data, profile data, and media data
19081            mInstaller.destroyUserData(volumeUuid, userId, flags);
19082
19083            // Clean up system data
19084            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19085                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19086                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19087                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19088                }
19089                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19090                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19091                }
19092            }
19093
19094            // Data with special labels is now gone, so finish the job
19095            storage.destroyUserStorage(volumeUuid, userId, flags);
19096
19097        } catch (Exception e) {
19098            logCriticalInfo(Log.WARN,
19099                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19100        }
19101    }
19102
19103    /**
19104     * Examine all users present on given mounted volume, and destroy data
19105     * belonging to users that are no longer valid, or whose user ID has been
19106     * recycled.
19107     */
19108    private void reconcileUsers(String volumeUuid) {
19109        final List<File> files = new ArrayList<>();
19110        Collections.addAll(files, FileUtils
19111                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19112        Collections.addAll(files, FileUtils
19113                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19114        for (File file : files) {
19115            if (!file.isDirectory()) continue;
19116
19117            final int userId;
19118            final UserInfo info;
19119            try {
19120                userId = Integer.parseInt(file.getName());
19121                info = sUserManager.getUserInfo(userId);
19122            } catch (NumberFormatException e) {
19123                Slog.w(TAG, "Invalid user directory " + file);
19124                continue;
19125            }
19126
19127            boolean destroyUser = false;
19128            if (info == null) {
19129                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19130                        + " because no matching user was found");
19131                destroyUser = true;
19132            } else if (!mOnlyCore) {
19133                try {
19134                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19135                } catch (IOException e) {
19136                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19137                            + " because we failed to enforce serial number: " + e);
19138                    destroyUser = true;
19139                }
19140            }
19141
19142            if (destroyUser) {
19143                synchronized (mInstallLock) {
19144                    destroyUserDataLI(volumeUuid, userId,
19145                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19146                }
19147            }
19148        }
19149    }
19150
19151    private void assertPackageKnown(String volumeUuid, String packageName)
19152            throws PackageManagerException {
19153        synchronized (mPackages) {
19154            final PackageSetting ps = mSettings.mPackages.get(packageName);
19155            if (ps == null) {
19156                throw new PackageManagerException("Package " + packageName + " is unknown");
19157            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19158                throw new PackageManagerException(
19159                        "Package " + packageName + " found on unknown volume " + volumeUuid
19160                                + "; expected volume " + ps.volumeUuid);
19161            }
19162        }
19163    }
19164
19165    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19166            throws PackageManagerException {
19167        synchronized (mPackages) {
19168            final PackageSetting ps = mSettings.mPackages.get(packageName);
19169            if (ps == null) {
19170                throw new PackageManagerException("Package " + packageName + " is unknown");
19171            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19172                throw new PackageManagerException(
19173                        "Package " + packageName + " found on unknown volume " + volumeUuid
19174                                + "; expected volume " + ps.volumeUuid);
19175            } else if (!ps.getInstalled(userId)) {
19176                throw new PackageManagerException(
19177                        "Package " + packageName + " not installed for user " + userId);
19178            }
19179        }
19180    }
19181
19182    /**
19183     * Examine all apps present on given mounted volume, and destroy apps that
19184     * aren't expected, either due to uninstallation or reinstallation on
19185     * another volume.
19186     */
19187    private void reconcileApps(String volumeUuid) {
19188        final File[] files = FileUtils
19189                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19190        for (File file : files) {
19191            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19192                    && !PackageInstallerService.isStageName(file.getName());
19193            if (!isPackage) {
19194                // Ignore entries which are not packages
19195                continue;
19196            }
19197
19198            try {
19199                final PackageLite pkg = PackageParser.parsePackageLite(file,
19200                        PackageParser.PARSE_MUST_BE_APK);
19201                assertPackageKnown(volumeUuid, pkg.packageName);
19202
19203            } catch (PackageParserException | PackageManagerException e) {
19204                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19205                synchronized (mInstallLock) {
19206                    removeCodePathLI(file);
19207                }
19208            }
19209        }
19210    }
19211
19212    /**
19213     * Reconcile all app data for the given user.
19214     * <p>
19215     * Verifies that directories exist and that ownership and labeling is
19216     * correct for all installed apps on all mounted volumes.
19217     */
19218    void reconcileAppsData(int userId, int flags) {
19219        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19220        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19221            final String volumeUuid = vol.getFsUuid();
19222            synchronized (mInstallLock) {
19223                reconcileAppsDataLI(volumeUuid, userId, flags);
19224            }
19225        }
19226    }
19227
19228    /**
19229     * Reconcile all app data on given mounted volume.
19230     * <p>
19231     * Destroys app data that isn't expected, either due to uninstallation or
19232     * reinstallation on another volume.
19233     * <p>
19234     * Verifies that directories exist and that ownership and labeling is
19235     * correct for all installed apps.
19236     */
19237    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19238        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19239                + Integer.toHexString(flags));
19240
19241        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19242        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19243
19244        boolean restoreconNeeded = false;
19245
19246        // First look for stale data that doesn't belong, and check if things
19247        // have changed since we did our last restorecon
19248        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19249            if (StorageManager.isFileEncryptedNativeOrEmulated()
19250                    && !StorageManager.isUserKeyUnlocked(userId)) {
19251                throw new RuntimeException(
19252                        "Yikes, someone asked us to reconcile CE storage while " + userId
19253                                + " was still locked; this would have caused massive data loss!");
19254            }
19255
19256            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19257
19258            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19259            for (File file : files) {
19260                final String packageName = file.getName();
19261                try {
19262                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19263                } catch (PackageManagerException e) {
19264                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19265                    try {
19266                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19267                                StorageManager.FLAG_STORAGE_CE, 0);
19268                    } catch (InstallerException e2) {
19269                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19270                    }
19271                }
19272            }
19273        }
19274        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19275            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19276
19277            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19278            for (File file : files) {
19279                final String packageName = file.getName();
19280                try {
19281                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19282                } catch (PackageManagerException e) {
19283                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19284                    try {
19285                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19286                                StorageManager.FLAG_STORAGE_DE, 0);
19287                    } catch (InstallerException e2) {
19288                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19289                    }
19290                }
19291            }
19292        }
19293
19294        // Ensure that data directories are ready to roll for all packages
19295        // installed for this volume and user
19296        final List<PackageSetting> packages;
19297        synchronized (mPackages) {
19298            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19299        }
19300        int preparedCount = 0;
19301        for (PackageSetting ps : packages) {
19302            final String packageName = ps.name;
19303            if (ps.pkg == null) {
19304                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19305                // TODO: might be due to legacy ASEC apps; we should circle back
19306                // and reconcile again once they're scanned
19307                continue;
19308            }
19309
19310            if (ps.getInstalled(userId)) {
19311                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19312
19313                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19314                    // We may have just shuffled around app data directories, so
19315                    // prepare them one more time
19316                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19317                }
19318
19319                preparedCount++;
19320            }
19321        }
19322
19323        if (restoreconNeeded) {
19324            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19325                SELinuxMMAC.setRestoreconDone(ceDir);
19326            }
19327            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19328                SELinuxMMAC.setRestoreconDone(deDir);
19329            }
19330        }
19331
19332        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19333                + " packages; restoreconNeeded was " + restoreconNeeded);
19334    }
19335
19336    /**
19337     * Prepare app data for the given app just after it was installed or
19338     * upgraded. This method carefully only touches users that it's installed
19339     * for, and it forces a restorecon to handle any seinfo changes.
19340     * <p>
19341     * Verifies that directories exist and that ownership and labeling is
19342     * correct for all installed apps. If there is an ownership mismatch, it
19343     * will try recovering system apps by wiping data; third-party app data is
19344     * left intact.
19345     * <p>
19346     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19347     */
19348    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19349        final PackageSetting ps;
19350        synchronized (mPackages) {
19351            ps = mSettings.mPackages.get(pkg.packageName);
19352            mSettings.writeKernelMappingLPr(ps);
19353        }
19354
19355        final UserManager um = mContext.getSystemService(UserManager.class);
19356        for (UserInfo user : um.getUsers()) {
19357            final int flags;
19358            if (um.isUserUnlockingOrUnlocked(user.id)) {
19359                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19360            } else if (um.isUserRunning(user.id)) {
19361                flags = StorageManager.FLAG_STORAGE_DE;
19362            } else {
19363                continue;
19364            }
19365
19366            if (ps.getInstalled(user.id)) {
19367                // Whenever an app changes, force a restorecon of its data
19368                // TODO: when user data is locked, mark that we're still dirty
19369                prepareAppDataLIF(pkg, user.id, flags, true);
19370            }
19371        }
19372    }
19373
19374    /**
19375     * Prepare app data for the given app.
19376     * <p>
19377     * Verifies that directories exist and that ownership and labeling is
19378     * correct for all installed apps. If there is an ownership mismatch, this
19379     * will try recovering system apps by wiping data; third-party app data is
19380     * left intact.
19381     */
19382    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19383            boolean restoreconNeeded) {
19384        if (pkg == null) {
19385            Slog.wtf(TAG, "Package was null!", new Throwable());
19386            return;
19387        }
19388        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19389        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19390        for (int i = 0; i < childCount; i++) {
19391            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19392        }
19393    }
19394
19395    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19396            boolean restoreconNeeded) {
19397        if (DEBUG_APP_DATA) {
19398            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19399                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19400        }
19401
19402        final String volumeUuid = pkg.volumeUuid;
19403        final String packageName = pkg.packageName;
19404        final ApplicationInfo app = pkg.applicationInfo;
19405        final int appId = UserHandle.getAppId(app.uid);
19406
19407        Preconditions.checkNotNull(app.seinfo);
19408
19409        try {
19410            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19411                    appId, app.seinfo, app.targetSdkVersion);
19412        } catch (InstallerException e) {
19413            if (app.isSystemApp()) {
19414                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19415                        + ", but trying to recover: " + e);
19416                destroyAppDataLeafLIF(pkg, userId, flags);
19417                try {
19418                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19419                            appId, app.seinfo, app.targetSdkVersion);
19420                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19421                } catch (InstallerException e2) {
19422                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19423                }
19424            } else {
19425                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19426            }
19427        }
19428
19429        if (restoreconNeeded) {
19430            try {
19431                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19432                        app.seinfo);
19433            } catch (InstallerException e) {
19434                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19435            }
19436        }
19437
19438        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19439            try {
19440                // CE storage is unlocked right now, so read out the inode and
19441                // remember for use later when it's locked
19442                // TODO: mark this structure as dirty so we persist it!
19443                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19444                        StorageManager.FLAG_STORAGE_CE);
19445                synchronized (mPackages) {
19446                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19447                    if (ps != null) {
19448                        ps.setCeDataInode(ceDataInode, userId);
19449                    }
19450                }
19451            } catch (InstallerException e) {
19452                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19453            }
19454        }
19455
19456        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19457    }
19458
19459    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19460        if (pkg == null) {
19461            Slog.wtf(TAG, "Package was null!", new Throwable());
19462            return;
19463        }
19464        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19465        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19466        for (int i = 0; i < childCount; i++) {
19467            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19468        }
19469    }
19470
19471    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19472        final String volumeUuid = pkg.volumeUuid;
19473        final String packageName = pkg.packageName;
19474        final ApplicationInfo app = pkg.applicationInfo;
19475
19476        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19477            // Create a native library symlink only if we have native libraries
19478            // and if the native libraries are 32 bit libraries. We do not provide
19479            // this symlink for 64 bit libraries.
19480            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19481                final String nativeLibPath = app.nativeLibraryDir;
19482                try {
19483                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19484                            nativeLibPath, userId);
19485                } catch (InstallerException e) {
19486                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19487                }
19488            }
19489        }
19490    }
19491
19492    /**
19493     * For system apps on non-FBE devices, this method migrates any existing
19494     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19495     * requested by the app.
19496     */
19497    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19498        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19499                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19500            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19501                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19502            try {
19503                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19504                        storageTarget);
19505            } catch (InstallerException e) {
19506                logCriticalInfo(Log.WARN,
19507                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19508            }
19509            return true;
19510        } else {
19511            return false;
19512        }
19513    }
19514
19515    public PackageFreezer freezePackage(String packageName, String killReason) {
19516        return new PackageFreezer(packageName, killReason);
19517    }
19518
19519    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19520            String killReason) {
19521        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19522            return new PackageFreezer();
19523        } else {
19524            return freezePackage(packageName, killReason);
19525        }
19526    }
19527
19528    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19529            String killReason) {
19530        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19531            return new PackageFreezer();
19532        } else {
19533            return freezePackage(packageName, killReason);
19534        }
19535    }
19536
19537    /**
19538     * Class that freezes and kills the given package upon creation, and
19539     * unfreezes it upon closing. This is typically used when doing surgery on
19540     * app code/data to prevent the app from running while you're working.
19541     */
19542    private class PackageFreezer implements AutoCloseable {
19543        private final String mPackageName;
19544        private final PackageFreezer[] mChildren;
19545
19546        private final boolean mWeFroze;
19547
19548        private final AtomicBoolean mClosed = new AtomicBoolean();
19549        private final CloseGuard mCloseGuard = CloseGuard.get();
19550
19551        /**
19552         * Create and return a stub freezer that doesn't actually do anything,
19553         * typically used when someone requested
19554         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19555         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19556         */
19557        public PackageFreezer() {
19558            mPackageName = null;
19559            mChildren = null;
19560            mWeFroze = false;
19561            mCloseGuard.open("close");
19562        }
19563
19564        public PackageFreezer(String packageName, String killReason) {
19565            synchronized (mPackages) {
19566                mPackageName = packageName;
19567                mWeFroze = mFrozenPackages.add(mPackageName);
19568
19569                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19570                if (ps != null) {
19571                    killApplication(ps.name, ps.appId, killReason);
19572                }
19573
19574                final PackageParser.Package p = mPackages.get(packageName);
19575                if (p != null && p.childPackages != null) {
19576                    final int N = p.childPackages.size();
19577                    mChildren = new PackageFreezer[N];
19578                    for (int i = 0; i < N; i++) {
19579                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19580                                killReason);
19581                    }
19582                } else {
19583                    mChildren = null;
19584                }
19585            }
19586            mCloseGuard.open("close");
19587        }
19588
19589        @Override
19590        protected void finalize() throws Throwable {
19591            try {
19592                mCloseGuard.warnIfOpen();
19593                close();
19594            } finally {
19595                super.finalize();
19596            }
19597        }
19598
19599        @Override
19600        public void close() {
19601            mCloseGuard.close();
19602            if (mClosed.compareAndSet(false, true)) {
19603                synchronized (mPackages) {
19604                    if (mWeFroze) {
19605                        mFrozenPackages.remove(mPackageName);
19606                    }
19607
19608                    if (mChildren != null) {
19609                        for (PackageFreezer freezer : mChildren) {
19610                            freezer.close();
19611                        }
19612                    }
19613                }
19614            }
19615        }
19616    }
19617
19618    /**
19619     * Verify that given package is currently frozen.
19620     */
19621    private void checkPackageFrozen(String packageName) {
19622        synchronized (mPackages) {
19623            if (!mFrozenPackages.contains(packageName)) {
19624                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19625            }
19626        }
19627    }
19628
19629    @Override
19630    public int movePackage(final String packageName, final String volumeUuid) {
19631        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19632
19633        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19634        final int moveId = mNextMoveId.getAndIncrement();
19635        mHandler.post(new Runnable() {
19636            @Override
19637            public void run() {
19638                try {
19639                    movePackageInternal(packageName, volumeUuid, moveId, user);
19640                } catch (PackageManagerException e) {
19641                    Slog.w(TAG, "Failed to move " + packageName, e);
19642                    mMoveCallbacks.notifyStatusChanged(moveId,
19643                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19644                }
19645            }
19646        });
19647        return moveId;
19648    }
19649
19650    private void movePackageInternal(final String packageName, final String volumeUuid,
19651            final int moveId, UserHandle user) throws PackageManagerException {
19652        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19653        final PackageManager pm = mContext.getPackageManager();
19654
19655        final boolean currentAsec;
19656        final String currentVolumeUuid;
19657        final File codeFile;
19658        final String installerPackageName;
19659        final String packageAbiOverride;
19660        final int appId;
19661        final String seinfo;
19662        final String label;
19663        final int targetSdkVersion;
19664        final PackageFreezer freezer;
19665        final int[] installedUserIds;
19666
19667        // reader
19668        synchronized (mPackages) {
19669            final PackageParser.Package pkg = mPackages.get(packageName);
19670            final PackageSetting ps = mSettings.mPackages.get(packageName);
19671            if (pkg == null || ps == null) {
19672                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19673            }
19674
19675            if (pkg.applicationInfo.isSystemApp()) {
19676                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19677                        "Cannot move system application");
19678            }
19679
19680            if (pkg.applicationInfo.isExternalAsec()) {
19681                currentAsec = true;
19682                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19683            } else if (pkg.applicationInfo.isForwardLocked()) {
19684                currentAsec = true;
19685                currentVolumeUuid = "forward_locked";
19686            } else {
19687                currentAsec = false;
19688                currentVolumeUuid = ps.volumeUuid;
19689
19690                final File probe = new File(pkg.codePath);
19691                final File probeOat = new File(probe, "oat");
19692                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19693                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19694                            "Move only supported for modern cluster style installs");
19695                }
19696            }
19697
19698            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19699                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19700                        "Package already moved to " + volumeUuid);
19701            }
19702            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19703                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19704                        "Device admin cannot be moved");
19705            }
19706
19707            if (mFrozenPackages.contains(packageName)) {
19708                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19709                        "Failed to move already frozen package");
19710            }
19711
19712            codeFile = new File(pkg.codePath);
19713            installerPackageName = ps.installerPackageName;
19714            packageAbiOverride = ps.cpuAbiOverrideString;
19715            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19716            seinfo = pkg.applicationInfo.seinfo;
19717            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19718            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19719            freezer = new PackageFreezer(packageName, "movePackageInternal");
19720            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19721        }
19722
19723        final Bundle extras = new Bundle();
19724        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19725        extras.putString(Intent.EXTRA_TITLE, label);
19726        mMoveCallbacks.notifyCreated(moveId, extras);
19727
19728        int installFlags;
19729        final boolean moveCompleteApp;
19730        final File measurePath;
19731
19732        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19733            installFlags = INSTALL_INTERNAL;
19734            moveCompleteApp = !currentAsec;
19735            measurePath = Environment.getDataAppDirectory(volumeUuid);
19736        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19737            installFlags = INSTALL_EXTERNAL;
19738            moveCompleteApp = false;
19739            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19740        } else {
19741            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19742            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19743                    || !volume.isMountedWritable()) {
19744                freezer.close();
19745                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19746                        "Move location not mounted private volume");
19747            }
19748
19749            Preconditions.checkState(!currentAsec);
19750
19751            installFlags = INSTALL_INTERNAL;
19752            moveCompleteApp = true;
19753            measurePath = Environment.getDataAppDirectory(volumeUuid);
19754        }
19755
19756        final PackageStats stats = new PackageStats(null, -1);
19757        synchronized (mInstaller) {
19758            for (int userId : installedUserIds) {
19759                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
19760                    freezer.close();
19761                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19762                            "Failed to measure package size");
19763                }
19764            }
19765        }
19766
19767        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19768                + stats.dataSize);
19769
19770        final long startFreeBytes = measurePath.getFreeSpace();
19771        final long sizeBytes;
19772        if (moveCompleteApp) {
19773            sizeBytes = stats.codeSize + stats.dataSize;
19774        } else {
19775            sizeBytes = stats.codeSize;
19776        }
19777
19778        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19779            freezer.close();
19780            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19781                    "Not enough free space to move");
19782        }
19783
19784        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19785
19786        final CountDownLatch installedLatch = new CountDownLatch(1);
19787        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19788            @Override
19789            public void onUserActionRequired(Intent intent) throws RemoteException {
19790                throw new IllegalStateException();
19791            }
19792
19793            @Override
19794            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19795                    Bundle extras) throws RemoteException {
19796                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19797                        + PackageManager.installStatusToString(returnCode, msg));
19798
19799                installedLatch.countDown();
19800                freezer.close();
19801
19802                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19803                switch (status) {
19804                    case PackageInstaller.STATUS_SUCCESS:
19805                        mMoveCallbacks.notifyStatusChanged(moveId,
19806                                PackageManager.MOVE_SUCCEEDED);
19807                        break;
19808                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19809                        mMoveCallbacks.notifyStatusChanged(moveId,
19810                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19811                        break;
19812                    default:
19813                        mMoveCallbacks.notifyStatusChanged(moveId,
19814                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19815                        break;
19816                }
19817            }
19818        };
19819
19820        final MoveInfo move;
19821        if (moveCompleteApp) {
19822            // Kick off a thread to report progress estimates
19823            new Thread() {
19824                @Override
19825                public void run() {
19826                    while (true) {
19827                        try {
19828                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19829                                break;
19830                            }
19831                        } catch (InterruptedException ignored) {
19832                        }
19833
19834                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19835                        final int progress = 10 + (int) MathUtils.constrain(
19836                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19837                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19838                    }
19839                }
19840            }.start();
19841
19842            final String dataAppName = codeFile.getName();
19843            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19844                    dataAppName, appId, seinfo, targetSdkVersion);
19845        } else {
19846            move = null;
19847        }
19848
19849        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19850
19851        final Message msg = mHandler.obtainMessage(INIT_COPY);
19852        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19853        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19854                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19855                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
19856        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19857        msg.obj = params;
19858
19859        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19860                System.identityHashCode(msg.obj));
19861        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19862                System.identityHashCode(msg.obj));
19863
19864        mHandler.sendMessage(msg);
19865    }
19866
19867    @Override
19868    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19869        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19870
19871        final int realMoveId = mNextMoveId.getAndIncrement();
19872        final Bundle extras = new Bundle();
19873        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19874        mMoveCallbacks.notifyCreated(realMoveId, extras);
19875
19876        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19877            @Override
19878            public void onCreated(int moveId, Bundle extras) {
19879                // Ignored
19880            }
19881
19882            @Override
19883            public void onStatusChanged(int moveId, int status, long estMillis) {
19884                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19885            }
19886        };
19887
19888        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19889        storage.setPrimaryStorageUuid(volumeUuid, callback);
19890        return realMoveId;
19891    }
19892
19893    @Override
19894    public int getMoveStatus(int moveId) {
19895        mContext.enforceCallingOrSelfPermission(
19896                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19897        return mMoveCallbacks.mLastStatus.get(moveId);
19898    }
19899
19900    @Override
19901    public void registerMoveCallback(IPackageMoveObserver callback) {
19902        mContext.enforceCallingOrSelfPermission(
19903                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19904        mMoveCallbacks.register(callback);
19905    }
19906
19907    @Override
19908    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19909        mContext.enforceCallingOrSelfPermission(
19910                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19911        mMoveCallbacks.unregister(callback);
19912    }
19913
19914    @Override
19915    public boolean setInstallLocation(int loc) {
19916        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19917                null);
19918        if (getInstallLocation() == loc) {
19919            return true;
19920        }
19921        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19922                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19923            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19924                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19925            return true;
19926        }
19927        return false;
19928   }
19929
19930    @Override
19931    public int getInstallLocation() {
19932        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19933                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19934                PackageHelper.APP_INSTALL_AUTO);
19935    }
19936
19937    /** Called by UserManagerService */
19938    void cleanUpUser(UserManagerService userManager, int userHandle) {
19939        synchronized (mPackages) {
19940            mDirtyUsers.remove(userHandle);
19941            mUserNeedsBadging.delete(userHandle);
19942            mSettings.removeUserLPw(userHandle);
19943            mPendingBroadcasts.remove(userHandle);
19944            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19945            removeUnusedPackagesLPw(userManager, userHandle);
19946        }
19947    }
19948
19949    /**
19950     * We're removing userHandle and would like to remove any downloaded packages
19951     * that are no longer in use by any other user.
19952     * @param userHandle the user being removed
19953     */
19954    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
19955        final boolean DEBUG_CLEAN_APKS = false;
19956        int [] users = userManager.getUserIds();
19957        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19958        while (psit.hasNext()) {
19959            PackageSetting ps = psit.next();
19960            if (ps.pkg == null) {
19961                continue;
19962            }
19963            final String packageName = ps.pkg.packageName;
19964            // Skip over if system app
19965            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19966                continue;
19967            }
19968            if (DEBUG_CLEAN_APKS) {
19969                Slog.i(TAG, "Checking package " + packageName);
19970            }
19971            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19972            if (keep) {
19973                if (DEBUG_CLEAN_APKS) {
19974                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19975                }
19976            } else {
19977                for (int i = 0; i < users.length; i++) {
19978                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19979                        keep = true;
19980                        if (DEBUG_CLEAN_APKS) {
19981                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19982                                    + users[i]);
19983                        }
19984                        break;
19985                    }
19986                }
19987            }
19988            if (!keep) {
19989                if (DEBUG_CLEAN_APKS) {
19990                    Slog.i(TAG, "  Removing package " + packageName);
19991                }
19992                mHandler.post(new Runnable() {
19993                    public void run() {
19994                        deletePackageX(packageName, userHandle, 0);
19995                    } //end run
19996                });
19997            }
19998        }
19999    }
20000
20001    /** Called by UserManagerService */
20002    void createNewUser(int userHandle) {
20003        synchronized (mInstallLock) {
20004            mSettings.createNewUserLI(this, mInstaller, userHandle);
20005        }
20006        synchronized (mPackages) {
20007            applyFactoryDefaultBrowserLPw(userHandle);
20008            primeDomainVerificationsLPw(userHandle);
20009        }
20010    }
20011
20012    void newUserCreated(final int userHandle) {
20013        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
20014        // If permission review for legacy apps is required, we represent
20015        // dagerous permissions for such apps as always granted runtime
20016        // permissions to keep per user flag state whether review is needed.
20017        // Hence, if a new user is added we have to propagate dangerous
20018        // permission grants for these legacy apps.
20019        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20020            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20021                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20022        }
20023    }
20024
20025    @Override
20026    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20027        mContext.enforceCallingOrSelfPermission(
20028                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20029                "Only package verification agents can read the verifier device identity");
20030
20031        synchronized (mPackages) {
20032            return mSettings.getVerifierDeviceIdentityLPw();
20033        }
20034    }
20035
20036    @Override
20037    public void setPermissionEnforced(String permission, boolean enforced) {
20038        // TODO: Now that we no longer change GID for storage, this should to away.
20039        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20040                "setPermissionEnforced");
20041        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20042            synchronized (mPackages) {
20043                if (mSettings.mReadExternalStorageEnforced == null
20044                        || mSettings.mReadExternalStorageEnforced != enforced) {
20045                    mSettings.mReadExternalStorageEnforced = enforced;
20046                    mSettings.writeLPr();
20047                }
20048            }
20049            // kill any non-foreground processes so we restart them and
20050            // grant/revoke the GID.
20051            final IActivityManager am = ActivityManagerNative.getDefault();
20052            if (am != null) {
20053                final long token = Binder.clearCallingIdentity();
20054                try {
20055                    am.killProcessesBelowForeground("setPermissionEnforcement");
20056                } catch (RemoteException e) {
20057                } finally {
20058                    Binder.restoreCallingIdentity(token);
20059                }
20060            }
20061        } else {
20062            throw new IllegalArgumentException("No selective enforcement for " + permission);
20063        }
20064    }
20065
20066    @Override
20067    @Deprecated
20068    public boolean isPermissionEnforced(String permission) {
20069        return true;
20070    }
20071
20072    @Override
20073    public boolean isStorageLow() {
20074        final long token = Binder.clearCallingIdentity();
20075        try {
20076            final DeviceStorageMonitorInternal
20077                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20078            if (dsm != null) {
20079                return dsm.isMemoryLow();
20080            } else {
20081                return false;
20082            }
20083        } finally {
20084            Binder.restoreCallingIdentity(token);
20085        }
20086    }
20087
20088    @Override
20089    public IPackageInstaller getPackageInstaller() {
20090        return mInstallerService;
20091    }
20092
20093    private boolean userNeedsBadging(int userId) {
20094        int index = mUserNeedsBadging.indexOfKey(userId);
20095        if (index < 0) {
20096            final UserInfo userInfo;
20097            final long token = Binder.clearCallingIdentity();
20098            try {
20099                userInfo = sUserManager.getUserInfo(userId);
20100            } finally {
20101                Binder.restoreCallingIdentity(token);
20102            }
20103            final boolean b;
20104            if (userInfo != null && userInfo.isManagedProfile()) {
20105                b = true;
20106            } else {
20107                b = false;
20108            }
20109            mUserNeedsBadging.put(userId, b);
20110            return b;
20111        }
20112        return mUserNeedsBadging.valueAt(index);
20113    }
20114
20115    @Override
20116    public KeySet getKeySetByAlias(String packageName, String alias) {
20117        if (packageName == null || alias == null) {
20118            return null;
20119        }
20120        synchronized(mPackages) {
20121            final PackageParser.Package pkg = mPackages.get(packageName);
20122            if (pkg == null) {
20123                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20124                throw new IllegalArgumentException("Unknown package: " + packageName);
20125            }
20126            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20127            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20128        }
20129    }
20130
20131    @Override
20132    public KeySet getSigningKeySet(String packageName) {
20133        if (packageName == null) {
20134            return null;
20135        }
20136        synchronized(mPackages) {
20137            final PackageParser.Package pkg = mPackages.get(packageName);
20138            if (pkg == null) {
20139                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20140                throw new IllegalArgumentException("Unknown package: " + packageName);
20141            }
20142            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20143                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20144                throw new SecurityException("May not access signing KeySet of other apps.");
20145            }
20146            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20147            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20148        }
20149    }
20150
20151    @Override
20152    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20153        if (packageName == null || ks == null) {
20154            return false;
20155        }
20156        synchronized(mPackages) {
20157            final PackageParser.Package pkg = mPackages.get(packageName);
20158            if (pkg == null) {
20159                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20160                throw new IllegalArgumentException("Unknown package: " + packageName);
20161            }
20162            IBinder ksh = ks.getToken();
20163            if (ksh instanceof KeySetHandle) {
20164                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20165                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20166            }
20167            return false;
20168        }
20169    }
20170
20171    @Override
20172    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20173        if (packageName == null || ks == null) {
20174            return false;
20175        }
20176        synchronized(mPackages) {
20177            final PackageParser.Package pkg = mPackages.get(packageName);
20178            if (pkg == null) {
20179                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20180                throw new IllegalArgumentException("Unknown package: " + packageName);
20181            }
20182            IBinder ksh = ks.getToken();
20183            if (ksh instanceof KeySetHandle) {
20184                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20185                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20186            }
20187            return false;
20188        }
20189    }
20190
20191    private void deletePackageIfUnusedLPr(final String packageName) {
20192        PackageSetting ps = mSettings.mPackages.get(packageName);
20193        if (ps == null) {
20194            return;
20195        }
20196        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20197            // TODO Implement atomic delete if package is unused
20198            // It is currently possible that the package will be deleted even if it is installed
20199            // after this method returns.
20200            mHandler.post(new Runnable() {
20201                public void run() {
20202                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20203                }
20204            });
20205        }
20206    }
20207
20208    /**
20209     * Check and throw if the given before/after packages would be considered a
20210     * downgrade.
20211     */
20212    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20213            throws PackageManagerException {
20214        if (after.versionCode < before.mVersionCode) {
20215            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20216                    "Update version code " + after.versionCode + " is older than current "
20217                    + before.mVersionCode);
20218        } else if (after.versionCode == before.mVersionCode) {
20219            if (after.baseRevisionCode < before.baseRevisionCode) {
20220                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20221                        "Update base revision code " + after.baseRevisionCode
20222                        + " is older than current " + before.baseRevisionCode);
20223            }
20224
20225            if (!ArrayUtils.isEmpty(after.splitNames)) {
20226                for (int i = 0; i < after.splitNames.length; i++) {
20227                    final String splitName = after.splitNames[i];
20228                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20229                    if (j != -1) {
20230                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20231                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20232                                    "Update split " + splitName + " revision code "
20233                                    + after.splitRevisionCodes[i] + " is older than current "
20234                                    + before.splitRevisionCodes[j]);
20235                        }
20236                    }
20237                }
20238            }
20239        }
20240    }
20241
20242    private static class MoveCallbacks extends Handler {
20243        private static final int MSG_CREATED = 1;
20244        private static final int MSG_STATUS_CHANGED = 2;
20245
20246        private final RemoteCallbackList<IPackageMoveObserver>
20247                mCallbacks = new RemoteCallbackList<>();
20248
20249        private final SparseIntArray mLastStatus = new SparseIntArray();
20250
20251        public MoveCallbacks(Looper looper) {
20252            super(looper);
20253        }
20254
20255        public void register(IPackageMoveObserver callback) {
20256            mCallbacks.register(callback);
20257        }
20258
20259        public void unregister(IPackageMoveObserver callback) {
20260            mCallbacks.unregister(callback);
20261        }
20262
20263        @Override
20264        public void handleMessage(Message msg) {
20265            final SomeArgs args = (SomeArgs) msg.obj;
20266            final int n = mCallbacks.beginBroadcast();
20267            for (int i = 0; i < n; i++) {
20268                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20269                try {
20270                    invokeCallback(callback, msg.what, args);
20271                } catch (RemoteException ignored) {
20272                }
20273            }
20274            mCallbacks.finishBroadcast();
20275            args.recycle();
20276        }
20277
20278        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20279                throws RemoteException {
20280            switch (what) {
20281                case MSG_CREATED: {
20282                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20283                    break;
20284                }
20285                case MSG_STATUS_CHANGED: {
20286                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20287                    break;
20288                }
20289            }
20290        }
20291
20292        private void notifyCreated(int moveId, Bundle extras) {
20293            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20294
20295            final SomeArgs args = SomeArgs.obtain();
20296            args.argi1 = moveId;
20297            args.arg2 = extras;
20298            obtainMessage(MSG_CREATED, args).sendToTarget();
20299        }
20300
20301        private void notifyStatusChanged(int moveId, int status) {
20302            notifyStatusChanged(moveId, status, -1);
20303        }
20304
20305        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20306            Slog.v(TAG, "Move " + moveId + " status " + status);
20307
20308            final SomeArgs args = SomeArgs.obtain();
20309            args.argi1 = moveId;
20310            args.argi2 = status;
20311            args.arg3 = estMillis;
20312            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20313
20314            synchronized (mLastStatus) {
20315                mLastStatus.put(moveId, status);
20316            }
20317        }
20318    }
20319
20320    private final static class OnPermissionChangeListeners extends Handler {
20321        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20322
20323        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20324                new RemoteCallbackList<>();
20325
20326        public OnPermissionChangeListeners(Looper looper) {
20327            super(looper);
20328        }
20329
20330        @Override
20331        public void handleMessage(Message msg) {
20332            switch (msg.what) {
20333                case MSG_ON_PERMISSIONS_CHANGED: {
20334                    final int uid = msg.arg1;
20335                    handleOnPermissionsChanged(uid);
20336                } break;
20337            }
20338        }
20339
20340        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20341            mPermissionListeners.register(listener);
20342
20343        }
20344
20345        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20346            mPermissionListeners.unregister(listener);
20347        }
20348
20349        public void onPermissionsChanged(int uid) {
20350            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20351                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20352            }
20353        }
20354
20355        private void handleOnPermissionsChanged(int uid) {
20356            final int count = mPermissionListeners.beginBroadcast();
20357            try {
20358                for (int i = 0; i < count; i++) {
20359                    IOnPermissionsChangeListener callback = mPermissionListeners
20360                            .getBroadcastItem(i);
20361                    try {
20362                        callback.onPermissionsChanged(uid);
20363                    } catch (RemoteException e) {
20364                        Log.e(TAG, "Permission listener is dead", e);
20365                    }
20366                }
20367            } finally {
20368                mPermissionListeners.finishBroadcast();
20369            }
20370        }
20371    }
20372
20373    private class PackageManagerInternalImpl extends PackageManagerInternal {
20374        @Override
20375        public void setLocationPackagesProvider(PackagesProvider provider) {
20376            synchronized (mPackages) {
20377                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20378            }
20379        }
20380
20381        @Override
20382        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20383            synchronized (mPackages) {
20384                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20385            }
20386        }
20387
20388        @Override
20389        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20390            synchronized (mPackages) {
20391                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20392            }
20393        }
20394
20395        @Override
20396        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20397            synchronized (mPackages) {
20398                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20399            }
20400        }
20401
20402        @Override
20403        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20404            synchronized (mPackages) {
20405                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20406            }
20407        }
20408
20409        @Override
20410        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20411            synchronized (mPackages) {
20412                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20413            }
20414        }
20415
20416        @Override
20417        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20418            synchronized (mPackages) {
20419                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20420                        packageName, userId);
20421            }
20422        }
20423
20424        @Override
20425        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20426            synchronized (mPackages) {
20427                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20428                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20429                        packageName, userId);
20430            }
20431        }
20432
20433        @Override
20434        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20435            synchronized (mPackages) {
20436                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20437                        packageName, userId);
20438            }
20439        }
20440
20441        @Override
20442        public void setKeepUninstalledPackages(final List<String> packageList) {
20443            Preconditions.checkNotNull(packageList);
20444            List<String> removedFromList = null;
20445            synchronized (mPackages) {
20446                if (mKeepUninstalledPackages != null) {
20447                    final int packagesCount = mKeepUninstalledPackages.size();
20448                    for (int i = 0; i < packagesCount; i++) {
20449                        String oldPackage = mKeepUninstalledPackages.get(i);
20450                        if (packageList != null && packageList.contains(oldPackage)) {
20451                            continue;
20452                        }
20453                        if (removedFromList == null) {
20454                            removedFromList = new ArrayList<>();
20455                        }
20456                        removedFromList.add(oldPackage);
20457                    }
20458                }
20459                mKeepUninstalledPackages = new ArrayList<>(packageList);
20460                if (removedFromList != null) {
20461                    final int removedCount = removedFromList.size();
20462                    for (int i = 0; i < removedCount; i++) {
20463                        deletePackageIfUnusedLPr(removedFromList.get(i));
20464                    }
20465                }
20466            }
20467        }
20468
20469        @Override
20470        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20471            synchronized (mPackages) {
20472                // If we do not support permission review, done.
20473                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20474                    return false;
20475                }
20476
20477                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20478                if (packageSetting == null) {
20479                    return false;
20480                }
20481
20482                // Permission review applies only to apps not supporting the new permission model.
20483                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20484                    return false;
20485                }
20486
20487                // Legacy apps have the permission and get user consent on launch.
20488                PermissionsState permissionsState = packageSetting.getPermissionsState();
20489                return permissionsState.isPermissionReviewRequired(userId);
20490            }
20491        }
20492
20493        @Override
20494        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20495            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20496        }
20497
20498        @Override
20499        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20500                int userId) {
20501            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20502        }
20503    }
20504
20505    @Override
20506    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20507        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20508        synchronized (mPackages) {
20509            final long identity = Binder.clearCallingIdentity();
20510            try {
20511                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20512                        packageNames, userId);
20513            } finally {
20514                Binder.restoreCallingIdentity(identity);
20515            }
20516        }
20517    }
20518
20519    private static void enforceSystemOrPhoneCaller(String tag) {
20520        int callingUid = Binder.getCallingUid();
20521        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20522            throw new SecurityException(
20523                    "Cannot call " + tag + " from UID " + callingUid);
20524        }
20525    }
20526
20527    boolean isHistoricalPackageUsageAvailable() {
20528        return mPackageUsage.isHistoricalPackageUsageAvailable();
20529    }
20530
20531    /**
20532     * Return a <b>copy</b> of the collection of packages known to the package manager.
20533     * @return A copy of the values of mPackages.
20534     */
20535    Collection<PackageParser.Package> getPackages() {
20536        synchronized (mPackages) {
20537            return new ArrayList<>(mPackages.values());
20538        }
20539    }
20540
20541    /**
20542     * Logs process start information (including base APK hash) to the security log.
20543     * @hide
20544     */
20545    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20546            String apkFile, int pid) {
20547        if (!SecurityLog.isLoggingEnabled()) {
20548            return;
20549        }
20550        Bundle data = new Bundle();
20551        data.putLong("startTimestamp", System.currentTimeMillis());
20552        data.putString("processName", processName);
20553        data.putInt("uid", uid);
20554        data.putString("seinfo", seinfo);
20555        data.putString("apkFile", apkFile);
20556        data.putInt("pid", pid);
20557        Message msg = mProcessLoggingHandler.obtainMessage(
20558                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20559        msg.setData(data);
20560        mProcessLoggingHandler.sendMessage(msg);
20561    }
20562}
20563