PackageManagerService.java revision 258aa3e56b02b95e8e855ef949a29babe178b4a5
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.ResourcesManager;
109import android.app.admin.DevicePolicyManagerInternal;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralResolveInfo;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
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.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedInputStream;
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.InputStream;
281import java.io.PrintWriter;
282import java.nio.charset.StandardCharsets;
283import java.security.DigestInputStream;
284import java.security.MessageDigest;
285import java.security.NoSuchAlgorithmException;
286import java.security.PublicKey;
287import java.security.cert.Certificate;
288import java.security.cert.CertificateEncodingException;
289import java.security.cert.CertificateException;
290import java.text.SimpleDateFormat;
291import java.util.ArrayList;
292import java.util.Arrays;
293import java.util.Collection;
294import java.util.Collections;
295import java.util.Comparator;
296import java.util.Date;
297import java.util.HashSet;
298import java.util.Iterator;
299import java.util.List;
300import java.util.Map;
301import java.util.Objects;
302import java.util.Set;
303import java.util.concurrent.CountDownLatch;
304import java.util.concurrent.TimeUnit;
305import java.util.concurrent.atomic.AtomicBoolean;
306import java.util.concurrent.atomic.AtomicInteger;
307import java.util.concurrent.atomic.AtomicLong;
308
309/**
310 * Keep track of all those APKs everywhere.
311 * <p>
312 * Internally there are two important locks:
313 * <ul>
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
323 * </ul>
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
326 * <ul>
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332 * </ul>
333 * <p>
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
336 *
337 * <pre>
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340 * </pre>
341 */
342public class PackageManagerService extends IPackageManager.Stub {
343    static final String TAG = "PackageManager";
344    static final boolean DEBUG_SETTINGS = false;
345    static final boolean DEBUG_PREFERRED = false;
346    static final boolean DEBUG_UPGRADE = false;
347    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348    private static final boolean DEBUG_BACKUP = false;
349    private static final boolean DEBUG_INSTALL = false;
350    private static final boolean DEBUG_REMOVE = false;
351    private static final boolean DEBUG_BROADCASTS = false;
352    private static final boolean DEBUG_SHOW_INFO = false;
353    private static final boolean DEBUG_PACKAGE_INFO = false;
354    private static final boolean DEBUG_INTENT_MATCHING = false;
355    private static final boolean DEBUG_PACKAGE_SCANNING = false;
356    private static final boolean DEBUG_VERIFY = false;
357    private static final boolean DEBUG_FILTERS = false;
358
359    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361    // user, but by default initialize to this.
362    static final boolean DEBUG_DEXOPT = false;
363
364    private static final boolean DEBUG_ABI_SELECTION = false;
365    private static final boolean DEBUG_EPHEMERAL = false;
366    private static final boolean DEBUG_TRIAGED_MISSING = false;
367    private static final boolean DEBUG_APP_DATA = false;
368
369    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
370
371    private static final boolean DISABLE_EPHEMERAL_APPS = true;
372
373    private static final int RADIO_UID = Process.PHONE_UID;
374    private static final int LOG_UID = Process.LOG_UID;
375    private static final int NFC_UID = Process.NFC_UID;
376    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377    private static final int SHELL_UID = Process.SHELL_UID;
378
379    // Cap the size of permission trees that 3rd party apps can define
380    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
381
382    // Suffix used during package installation when copying/moving
383    // package apks to install directory.
384    private static final String INSTALL_PACKAGE_SUFFIX = "-";
385
386    static final int SCAN_NO_DEX = 1<<1;
387    static final int SCAN_FORCE_DEX = 1<<2;
388    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389    static final int SCAN_NEW_INSTALL = 1<<4;
390    static final int SCAN_NO_PATHS = 1<<5;
391    static final int SCAN_UPDATE_TIME = 1<<6;
392    static final int SCAN_DEFER_DEX = 1<<7;
393    static final int SCAN_BOOTING = 1<<8;
394    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396    static final int SCAN_REPLACING = 1<<11;
397    static final int SCAN_REQUIRE_KNOWN = 1<<12;
398    static final int SCAN_MOVE = 1<<13;
399    static final int SCAN_INITIAL = 1<<14;
400    static final int SCAN_CHECK_ONLY = 1<<15;
401    static final int SCAN_DONT_KILL_APP = 1<<17;
402    static final int SCAN_IGNORE_FROZEN = 1<<18;
403
404    static final int REMOVE_CHATTY = 1<<16;
405
406    private static final int[] EMPTY_INT_ARRAY = new int[0];
407
408    /**
409     * Timeout (in milliseconds) after which the watchdog should declare that
410     * our handler thread is wedged.  The usual default for such things is one
411     * minute but we sometimes do very lengthy I/O operations on this thread,
412     * such as installing multi-gigabyte applications, so ours needs to be longer.
413     */
414    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
415
416    /**
417     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419     * settings entry if available, otherwise we use the hardcoded default.  If it's been
420     * more than this long since the last fstrim, we force one during the boot sequence.
421     *
422     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
423     * one gets run at the next available charging+idle time.  This final mandatory
424     * no-fstrim check kicks in only of the other scheduling criteria is never met.
425     */
426    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
427
428    /**
429     * Whether verification is enabled by default.
430     */
431    private static final boolean DEFAULT_VERIFY_ENABLE = true;
432
433    /**
434     * The default maximum time to wait for the verification agent to return in
435     * milliseconds.
436     */
437    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
438
439    /**
440     * The default response for package verification timeout.
441     *
442     * This can be either PackageManager.VERIFICATION_ALLOW or
443     * PackageManager.VERIFICATION_REJECT.
444     */
445    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
446
447    static final String PLATFORM_PACKAGE_NAME = "android";
448
449    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
450
451    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452            DEFAULT_CONTAINER_PACKAGE,
453            "com.android.defcontainer.DefaultContainerService");
454
455    private static final String KILL_APP_REASON_GIDS_CHANGED =
456            "permission grant or revoke changed gids";
457
458    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459            "permissions revoked";
460
461    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
462
463    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536
537    /** The location for ASEC container files on internal storage. */
538    final String mAsecInternalPath;
539
540    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541    // LOCK HELD.  Can be called with mInstallLock held.
542    @GuardedBy("mInstallLock")
543    final Installer mInstaller;
544
545    /** Directory where installed third-party apps stored */
546    final File mAppInstallDir;
547    final File mEphemeralInstallDir;
548
549    /**
550     * Directory to which applications installed internally have their
551     * 32 bit native libraries copied.
552     */
553    private File mAppLib32InstallDir;
554
555    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556    // apps.
557    final File mDrmAppPrivateInstallDir;
558
559    // ----------------------------------------------------------------
560
561    // Lock for state used when installing and doing other long running
562    // operations.  Methods that must be called with this lock held have
563    // the suffix "LI".
564    final Object mInstallLock = new Object();
565
566    // ----------------------------------------------------------------
567
568    // Keys are String (package name), values are Package.  This also serves
569    // as the lock for the global state.  Methods that must be called with
570    // this lock held have the prefix "LP".
571    @GuardedBy("mPackages")
572    final ArrayMap<String, PackageParser.Package> mPackages =
573            new ArrayMap<String, PackageParser.Package>();
574
575    final ArrayMap<String, Set<String>> mKnownCodebase =
576            new ArrayMap<String, Set<String>>();
577
578    // Tracks available target package names -> overlay package paths.
579    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582    /**
583     * Tracks new system packages [received in an OTA] that we expect to
584     * find updated user-installed versions. Keys are package name, values
585     * are package location.
586     */
587    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588    /**
589     * Tracks high priority intent filters for protected actions. During boot, certain
590     * filter actions are protected and should never be allowed to have a high priority
591     * intent filter for them. However, there is one, and only one exception -- the
592     * setup wizard. It must be able to define a high priority intent filter for these
593     * actions to ensure there are no escapes from the wizard. We need to delay processing
594     * of these during boot as we need to look at all of the system packages in order
595     * to know which component is the setup wizard.
596     */
597    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598    /**
599     * Whether or not processing protected filters should be deferred.
600     */
601    private boolean mDeferProtectedFilters = true;
602
603    /**
604     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605     */
606    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607    /**
608     * Whether or not system app permissions should be promoted from install to runtime.
609     */
610    boolean mPromoteSystemApps;
611
612    @GuardedBy("mPackages")
613    final Settings mSettings;
614
615    /**
616     * Set of package names that are currently "frozen", which means active
617     * surgery is being done on the code/data for that package. The platform
618     * will refuse to launch frozen packages to avoid race conditions.
619     *
620     * @see PackageFreezer
621     */
622    @GuardedBy("mPackages")
623    final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625    boolean mRestoredSettings;
626
627    // System configuration read by SystemConfig.
628    final int[] mGlobalGids;
629    final SparseArray<ArraySet<String>> mSystemPermissions;
630    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
631
632    // If mac_permissions.xml was found for seinfo labeling.
633    boolean mFoundPolicyFile;
634
635    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
636
637    public static final class SharedLibraryEntry {
638        public final String path;
639        public final String apk;
640
641        SharedLibraryEntry(String _path, String _apk) {
642            path = _path;
643            apk = _apk;
644        }
645    }
646
647    // Currently known shared libraries.
648    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
649            new ArrayMap<String, SharedLibraryEntry>();
650
651    // All available activities, for your resolving pleasure.
652    final ActivityIntentResolver mActivities =
653            new ActivityIntentResolver();
654
655    // All available receivers, for your resolving pleasure.
656    final ActivityIntentResolver mReceivers =
657            new ActivityIntentResolver();
658
659    // All available services, for your resolving pleasure.
660    final ServiceIntentResolver mServices = new ServiceIntentResolver();
661
662    // All available providers, for your resolving pleasure.
663    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
664
665    // Mapping from provider base names (first directory in content URI codePath)
666    // to the provider information.
667    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
668            new ArrayMap<String, PackageParser.Provider>();
669
670    // Mapping from instrumentation class names to info about them.
671    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
672            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
673
674    // Mapping from permission names to info about them.
675    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
676            new ArrayMap<String, PackageParser.PermissionGroup>();
677
678    // Packages whose data we have transfered into another package, thus
679    // should no longer exist.
680    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
681
682    // Broadcast actions that are only available to the system.
683    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
684
685    /** List of packages waiting for verification. */
686    final SparseArray<PackageVerificationState> mPendingVerification
687            = new SparseArray<PackageVerificationState>();
688
689    /** Set of packages associated with each app op permission. */
690    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
691
692    final PackageInstallerService mInstallerService;
693
694    private final PackageDexOptimizer mPackageDexOptimizer;
695
696    private AtomicInteger mNextMoveId = new AtomicInteger();
697    private final MoveCallbacks mMoveCallbacks;
698
699    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
700
701    // Cache of users who need badging.
702    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
703
704    /** Token for keys in mPendingVerification. */
705    private int mPendingVerificationToken = 0;
706
707    volatile boolean mSystemReady;
708    volatile boolean mSafeMode;
709    volatile boolean mHasSystemUidErrors;
710
711    ApplicationInfo mAndroidApplication;
712    final ActivityInfo mResolveActivity = new ActivityInfo();
713    final ResolveInfo mResolveInfo = new ResolveInfo();
714    ComponentName mResolveComponentName;
715    PackageParser.Package mPlatformPackage;
716    ComponentName mCustomResolverComponentName;
717
718    boolean mResolverReplaced = false;
719
720    private final @Nullable ComponentName mIntentFilterVerifierComponent;
721    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
722
723    private int mIntentFilterVerificationToken = 0;
724
725    /** Component that knows whether or not an ephemeral application exists */
726    final ComponentName mEphemeralResolverComponent;
727    /** The service connection to the ephemeral resolver */
728    final EphemeralResolverConnection mEphemeralResolverConnection;
729
730    /** Component used to install ephemeral applications */
731    final ComponentName mEphemeralInstallerComponent;
732    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
733    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
734
735    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
736            = new SparseArray<IntentFilterVerificationState>();
737
738    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
739            new DefaultPermissionGrantPolicy(this);
740
741    // List of packages names to keep cached, even if they are uninstalled for all users
742    private List<String> mKeepUninstalledPackages;
743
744    private UserManagerInternal mUserManagerInternal;
745
746    private static class IFVerificationParams {
747        PackageParser.Package pkg;
748        boolean replacing;
749        int userId;
750        int verifierUid;
751
752        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
753                int _userId, int _verifierUid) {
754            pkg = _pkg;
755            replacing = _replacing;
756            userId = _userId;
757            replacing = _replacing;
758            verifierUid = _verifierUid;
759        }
760    }
761
762    private interface IntentFilterVerifier<T extends IntentFilter> {
763        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
764                                               T filter, String packageName);
765        void startVerifications(int userId);
766        void receiveVerificationResponse(int verificationId);
767    }
768
769    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
770        private Context mContext;
771        private ComponentName mIntentFilterVerifierComponent;
772        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
773
774        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
775            mContext = context;
776            mIntentFilterVerifierComponent = verifierComponent;
777        }
778
779        private String getDefaultScheme() {
780            return IntentFilter.SCHEME_HTTPS;
781        }
782
783        @Override
784        public void startVerifications(int userId) {
785            // Launch verifications requests
786            int count = mCurrentIntentFilterVerifications.size();
787            for (int n=0; n<count; n++) {
788                int verificationId = mCurrentIntentFilterVerifications.get(n);
789                final IntentFilterVerificationState ivs =
790                        mIntentFilterVerificationStates.get(verificationId);
791
792                String packageName = ivs.getPackageName();
793
794                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
795                final int filterCount = filters.size();
796                ArraySet<String> domainsSet = new ArraySet<>();
797                for (int m=0; m<filterCount; m++) {
798                    PackageParser.ActivityIntentInfo filter = filters.get(m);
799                    domainsSet.addAll(filter.getHostsList());
800                }
801                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
802                synchronized (mPackages) {
803                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
804                            packageName, domainsList) != null) {
805                        scheduleWriteSettingsLocked();
806                    }
807                }
808                sendVerificationRequest(userId, verificationId, ivs);
809            }
810            mCurrentIntentFilterVerifications.clear();
811        }
812
813        private void sendVerificationRequest(int userId, int verificationId,
814                IntentFilterVerificationState ivs) {
815
816            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
819                    verificationId);
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
822                    getDefaultScheme());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
825                    ivs.getHostsString());
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
828                    ivs.getPackageName());
829            verificationIntent.setComponent(mIntentFilterVerifierComponent);
830            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
831
832            UserHandle user = new UserHandle(userId);
833            mContext.sendBroadcastAsUser(verificationIntent, user);
834            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
835                    "Sending IntentFilter verification broadcast");
836        }
837
838        public void receiveVerificationResponse(int verificationId) {
839            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
840
841            final boolean verified = ivs.isVerified();
842
843            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
844            final int count = filters.size();
845            if (DEBUG_DOMAIN_VERIFICATION) {
846                Slog.i(TAG, "Received verification response " + verificationId
847                        + " for " + count + " filters, verified=" + verified);
848            }
849            for (int n=0; n<count; n++) {
850                PackageParser.ActivityIntentInfo filter = filters.get(n);
851                filter.setVerified(verified);
852
853                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
854                        + " verified with result:" + verified + " and hosts:"
855                        + ivs.getHostsString());
856            }
857
858            mIntentFilterVerificationStates.remove(verificationId);
859
860            final String packageName = ivs.getPackageName();
861            IntentFilterVerificationInfo ivi = null;
862
863            synchronized (mPackages) {
864                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
865            }
866            if (ivi == null) {
867                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
868                        + verificationId + " packageName:" + packageName);
869                return;
870            }
871            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
872                    "Updating IntentFilterVerificationInfo for package " + packageName
873                            +" verificationId:" + verificationId);
874
875            synchronized (mPackages) {
876                if (verified) {
877                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
878                } else {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
880                }
881                scheduleWriteSettingsLocked();
882
883                final int userId = ivs.getUserId();
884                if (userId != UserHandle.USER_ALL) {
885                    final int userStatus =
886                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
887
888                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
889                    boolean needUpdate = false;
890
891                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
892                    // already been set by the User thru the Disambiguation dialog
893                    switch (userStatus) {
894                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
895                            if (verified) {
896                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
897                            } else {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
899                            }
900                            needUpdate = true;
901                            break;
902
903                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
904                            if (verified) {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
906                                needUpdate = true;
907                            }
908                            break;
909
910                        default:
911                            // Nothing to do
912                    }
913
914                    if (needUpdate) {
915                        mSettings.updateIntentFilterVerificationStatusLPw(
916                                packageName, updatedStatus, userId);
917                        scheduleWritePackageRestrictionsLocked(userId);
918                    }
919                }
920            }
921        }
922
923        @Override
924        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
925                    ActivityIntentInfo filter, String packageName) {
926            if (!hasValidDomains(filter)) {
927                return false;
928            }
929            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
930            if (ivs == null) {
931                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
932                        packageName);
933            }
934            if (DEBUG_DOMAIN_VERIFICATION) {
935                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
936            }
937            ivs.addFilter(filter);
938            return true;
939        }
940
941        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
942                int userId, int verificationId, String packageName) {
943            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
944                    verifierUid, userId, packageName);
945            ivs.setPendingState();
946            synchronized (mPackages) {
947                mIntentFilterVerificationStates.append(verificationId, ivs);
948                mCurrentIntentFilterVerifications.add(verificationId);
949            }
950            return ivs;
951        }
952    }
953
954    private static boolean hasValidDomains(ActivityIntentInfo filter) {
955        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
956                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
957                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
958    }
959
960    // Set of pending broadcasts for aggregating enable/disable of components.
961    static class PendingPackageBroadcasts {
962        // for each user id, a map of <package name -> components within that package>
963        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
964
965        public PendingPackageBroadcasts() {
966            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
967        }
968
969        public ArrayList<String> get(int userId, String packageName) {
970            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
971            return packages.get(packageName);
972        }
973
974        public void put(int userId, String packageName, ArrayList<String> components) {
975            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
976            packages.put(packageName, components);
977        }
978
979        public void remove(int userId, String packageName) {
980            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
981            if (packages != null) {
982                packages.remove(packageName);
983            }
984        }
985
986        public void remove(int userId) {
987            mUidMap.remove(userId);
988        }
989
990        public int userIdCount() {
991            return mUidMap.size();
992        }
993
994        public int userIdAt(int n) {
995            return mUidMap.keyAt(n);
996        }
997
998        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
999            return mUidMap.get(userId);
1000        }
1001
1002        public int size() {
1003            // total number of pending broadcast entries across all userIds
1004            int num = 0;
1005            for (int i = 0; i< mUidMap.size(); i++) {
1006                num += mUidMap.valueAt(i).size();
1007            }
1008            return num;
1009        }
1010
1011        public void clear() {
1012            mUidMap.clear();
1013        }
1014
1015        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1016            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1017            if (map == null) {
1018                map = new ArrayMap<String, ArrayList<String>>();
1019                mUidMap.put(userId, map);
1020            }
1021            return map;
1022        }
1023    }
1024    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1025
1026    // Service Connection to remote media container service to copy
1027    // package uri's from external media onto secure containers
1028    // or internal storage.
1029    private IMediaContainerService mContainerService = null;
1030
1031    static final int SEND_PENDING_BROADCAST = 1;
1032    static final int MCS_BOUND = 3;
1033    static final int END_COPY = 4;
1034    static final int INIT_COPY = 5;
1035    static final int MCS_UNBIND = 6;
1036    static final int START_CLEANING_PACKAGE = 7;
1037    static final int FIND_INSTALL_LOC = 8;
1038    static final int POST_INSTALL = 9;
1039    static final int MCS_RECONNECT = 10;
1040    static final int MCS_GIVE_UP = 11;
1041    static final int UPDATED_MEDIA_STATUS = 12;
1042    static final int WRITE_SETTINGS = 13;
1043    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1044    static final int PACKAGE_VERIFIED = 15;
1045    static final int CHECK_PENDING_VERIFICATION = 16;
1046    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1047    static final int INTENT_FILTER_VERIFIED = 18;
1048    static final int WRITE_PACKAGE_LIST = 19;
1049
1050    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1051
1052    // Delay time in millisecs
1053    static final int BROADCAST_DELAY = 10 * 1000;
1054
1055    static UserManagerService sUserManager;
1056
1057    // Stores a list of users whose package restrictions file needs to be updated
1058    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1059
1060    final private DefaultContainerConnection mDefContainerConn =
1061            new DefaultContainerConnection();
1062    class DefaultContainerConnection implements ServiceConnection {
1063        public void onServiceConnected(ComponentName name, IBinder service) {
1064            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1065            IMediaContainerService imcs =
1066                IMediaContainerService.Stub.asInterface(service);
1067            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1068        }
1069
1070        public void onServiceDisconnected(ComponentName name) {
1071            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1072        }
1073    }
1074
1075    // Recordkeeping of restore-after-install operations that are currently in flight
1076    // between the Package Manager and the Backup Manager
1077    static class PostInstallData {
1078        public InstallArgs args;
1079        public PackageInstalledInfo res;
1080
1081        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1082            args = _a;
1083            res = _r;
1084        }
1085    }
1086
1087    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1088    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1089
1090    // XML tags for backup/restore of various bits of state
1091    private static final String TAG_PREFERRED_BACKUP = "pa";
1092    private static final String TAG_DEFAULT_APPS = "da";
1093    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1094
1095    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1096    private static final String TAG_ALL_GRANTS = "rt-grants";
1097    private static final String TAG_GRANT = "grant";
1098    private static final String ATTR_PACKAGE_NAME = "pkg";
1099
1100    private static final String TAG_PERMISSION = "perm";
1101    private static final String ATTR_PERMISSION_NAME = "name";
1102    private static final String ATTR_IS_GRANTED = "g";
1103    private static final String ATTR_USER_SET = "set";
1104    private static final String ATTR_USER_FIXED = "fixed";
1105    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1106
1107    // System/policy permission grants are not backed up
1108    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1109            FLAG_PERMISSION_POLICY_FIXED
1110            | FLAG_PERMISSION_SYSTEM_FIXED
1111            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1112
1113    // And we back up these user-adjusted states
1114    private static final int USER_RUNTIME_GRANT_MASK =
1115            FLAG_PERMISSION_USER_SET
1116            | FLAG_PERMISSION_USER_FIXED
1117            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1118
1119    final @Nullable String mRequiredVerifierPackage;
1120    final @NonNull String mRequiredInstallerPackage;
1121    final @Nullable String mSetupWizardPackage;
1122    final @NonNull String mServicesSystemSharedLibraryPackageName;
1123    final @NonNull String mSharedSystemSharedLibraryPackageName;
1124
1125    private final PackageUsage mPackageUsage = new PackageUsage();
1126
1127    private class PackageUsage {
1128        private static final int WRITE_INTERVAL
1129            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1130
1131        private final Object mFileLock = new Object();
1132        private final AtomicLong mLastWritten = new AtomicLong(0);
1133        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1134
1135        private boolean mIsHistoricalPackageUsageAvailable = true;
1136
1137        boolean isHistoricalPackageUsageAvailable() {
1138            return mIsHistoricalPackageUsageAvailable;
1139        }
1140
1141        void write(boolean force) {
1142            if (force) {
1143                writeInternal();
1144                return;
1145            }
1146            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1147                && !DEBUG_DEXOPT) {
1148                return;
1149            }
1150            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1151                new Thread("PackageUsage_DiskWriter") {
1152                    @Override
1153                    public void run() {
1154                        try {
1155                            writeInternal();
1156                        } finally {
1157                            mBackgroundWriteRunning.set(false);
1158                        }
1159                    }
1160                }.start();
1161            }
1162        }
1163
1164        private void writeInternal() {
1165            synchronized (mPackages) {
1166                synchronized (mFileLock) {
1167                    AtomicFile file = getFile();
1168                    FileOutputStream f = null;
1169                    try {
1170                        f = file.startWrite();
1171                        BufferedOutputStream out = new BufferedOutputStream(f);
1172                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1173                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1174                        StringBuilder sb = new StringBuilder();
1175
1176                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1177                        sb.append('\n');
1178                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1179
1180                        for (PackageParser.Package pkg : mPackages.values()) {
1181                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1182                                continue;
1183                            }
1184                            sb.setLength(0);
1185                            sb.append(pkg.packageName);
1186                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1187                                sb.append(' ');
1188                                sb.append(usageTimeInMillis);
1189                            }
1190                            sb.append('\n');
1191                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1192                        }
1193                        out.flush();
1194                        file.finishWrite(f);
1195                    } catch (IOException e) {
1196                        if (f != null) {
1197                            file.failWrite(f);
1198                        }
1199                        Log.e(TAG, "Failed to write package usage times", e);
1200                    }
1201                }
1202            }
1203            mLastWritten.set(SystemClock.elapsedRealtime());
1204        }
1205
1206        void readLP() {
1207            synchronized (mFileLock) {
1208                AtomicFile file = getFile();
1209                BufferedInputStream in = null;
1210                try {
1211                    in = new BufferedInputStream(file.openRead());
1212                    StringBuffer sb = new StringBuffer();
1213
1214                    String firstLine = readLine(in, sb);
1215                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1216                        readVersion1LP(in, sb);
1217                    } else {
1218                        readVersion0LP(in, sb, firstLine);
1219                    }
1220                } catch (FileNotFoundException expected) {
1221                    mIsHistoricalPackageUsageAvailable = false;
1222                } catch (IOException e) {
1223                    Log.w(TAG, "Failed to read package usage times", e);
1224                } finally {
1225                    IoUtils.closeQuietly(in);
1226                }
1227            }
1228            mLastWritten.set(SystemClock.elapsedRealtime());
1229        }
1230
1231        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1232                throws IOException {
1233            // Initial version of the file had no version number and stored one
1234            // package-timestamp pair per line.
1235            // Note that the first line has already been read from the InputStream.
1236            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1237                String[] tokens = line.split(" ");
1238                if (tokens.length != 2) {
1239                    throw new IOException("Failed to parse " + line +
1240                            " as package-timestamp pair.");
1241                }
1242
1243                String packageName = tokens[0];
1244                PackageParser.Package pkg = mPackages.get(packageName);
1245                if (pkg == null) {
1246                    continue;
1247                }
1248
1249                long timestamp = parseAsLong(tokens[1]);
1250                for (int reason = 0;
1251                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1252                        reason++) {
1253                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1254                }
1255            }
1256        }
1257
1258        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1259            // Version 1 of the file started with the corresponding version
1260            // number and then stored a package name and eight timestamps per line.
1261            String line;
1262            while ((line = readLine(in, sb)) != null) {
1263                String[] tokens = line.split(" ");
1264                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1265                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1266                }
1267
1268                String packageName = tokens[0];
1269                PackageParser.Package pkg = mPackages.get(packageName);
1270                if (pkg == null) {
1271                    continue;
1272                }
1273
1274                for (int reason = 0;
1275                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1276                        reason++) {
1277                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1278                }
1279            }
1280        }
1281
1282        private long parseAsLong(String token) throws IOException {
1283            try {
1284                return Long.parseLong(token);
1285            } catch (NumberFormatException e) {
1286                throw new IOException("Failed to parse " + token + " as a long.", e);
1287            }
1288        }
1289
1290        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1291            return readToken(in, sb, '\n');
1292        }
1293
1294        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1295                throws IOException {
1296            sb.setLength(0);
1297            while (true) {
1298                int ch = in.read();
1299                if (ch == -1) {
1300                    if (sb.length() == 0) {
1301                        return null;
1302                    }
1303                    throw new IOException("Unexpected EOF");
1304                }
1305                if (ch == endOfToken) {
1306                    return sb.toString();
1307                }
1308                sb.append((char)ch);
1309            }
1310        }
1311
1312        private AtomicFile getFile() {
1313            File dataDir = Environment.getDataDirectory();
1314            File systemDir = new File(dataDir, "system");
1315            File fname = new File(systemDir, "package-usage.list");
1316            return new AtomicFile(fname);
1317        }
1318
1319        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1320        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1321    }
1322
1323    class PackageHandler extends Handler {
1324        private boolean mBound = false;
1325        final ArrayList<HandlerParams> mPendingInstalls =
1326            new ArrayList<HandlerParams>();
1327
1328        private boolean connectToService() {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1330                    " DefaultContainerService");
1331            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1332            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1333            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1334                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1335                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336                mBound = true;
1337                return true;
1338            }
1339            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1340            return false;
1341        }
1342
1343        private void disconnectService() {
1344            mContainerService = null;
1345            mBound = false;
1346            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1347            mContext.unbindService(mDefContainerConn);
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1349        }
1350
1351        PackageHandler(Looper looper) {
1352            super(looper);
1353        }
1354
1355        public void handleMessage(Message msg) {
1356            try {
1357                doHandleMessage(msg);
1358            } finally {
1359                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1360            }
1361        }
1362
1363        void doHandleMessage(Message msg) {
1364            switch (msg.what) {
1365                case INIT_COPY: {
1366                    HandlerParams params = (HandlerParams) msg.obj;
1367                    int idx = mPendingInstalls.size();
1368                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1369                    // If a bind was already initiated we dont really
1370                    // need to do anything. The pending install
1371                    // will be processed later on.
1372                    if (!mBound) {
1373                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1374                                System.identityHashCode(mHandler));
1375                        // If this is the only one pending we might
1376                        // have to bind to the service again.
1377                        if (!connectToService()) {
1378                            Slog.e(TAG, "Failed to bind to media container service");
1379                            params.serviceError();
1380                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1381                                    System.identityHashCode(mHandler));
1382                            if (params.traceMethod != null) {
1383                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1384                                        params.traceCookie);
1385                            }
1386                            return;
1387                        } else {
1388                            // Once we bind to the service, the first
1389                            // pending request will be processed.
1390                            mPendingInstalls.add(idx, params);
1391                        }
1392                    } else {
1393                        mPendingInstalls.add(idx, params);
1394                        // Already bound to the service. Just make
1395                        // sure we trigger off processing the first request.
1396                        if (idx == 0) {
1397                            mHandler.sendEmptyMessage(MCS_BOUND);
1398                        }
1399                    }
1400                    break;
1401                }
1402                case MCS_BOUND: {
1403                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1404                    if (msg.obj != null) {
1405                        mContainerService = (IMediaContainerService) msg.obj;
1406                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1407                                System.identityHashCode(mHandler));
1408                    }
1409                    if (mContainerService == null) {
1410                        if (!mBound) {
1411                            // Something seriously wrong since we are not bound and we are not
1412                            // waiting for connection. Bail out.
1413                            Slog.e(TAG, "Cannot bind to media container service");
1414                            for (HandlerParams params : mPendingInstalls) {
1415                                // Indicate service bind error
1416                                params.serviceError();
1417                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1418                                        System.identityHashCode(params));
1419                                if (params.traceMethod != null) {
1420                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1421                                            params.traceMethod, params.traceCookie);
1422                                }
1423                                return;
1424                            }
1425                            mPendingInstalls.clear();
1426                        } else {
1427                            Slog.w(TAG, "Waiting to connect to media container service");
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        HandlerParams params = mPendingInstalls.get(0);
1431                        if (params != null) {
1432                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1433                                    System.identityHashCode(params));
1434                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1435                            if (params.startCopy()) {
1436                                // We are done...  look for more work or to
1437                                // go idle.
1438                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1439                                        "Checking for more work or unbind...");
1440                                // Delete pending install
1441                                if (mPendingInstalls.size() > 0) {
1442                                    mPendingInstalls.remove(0);
1443                                }
1444                                if (mPendingInstalls.size() == 0) {
1445                                    if (mBound) {
1446                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1447                                                "Posting delayed MCS_UNBIND");
1448                                        removeMessages(MCS_UNBIND);
1449                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1450                                        // Unbind after a little delay, to avoid
1451                                        // continual thrashing.
1452                                        sendMessageDelayed(ubmsg, 10000);
1453                                    }
1454                                } else {
1455                                    // There are more pending requests in queue.
1456                                    // Just post MCS_BOUND message to trigger processing
1457                                    // of next pending install.
1458                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1459                                            "Posting MCS_BOUND for next work");
1460                                    mHandler.sendEmptyMessage(MCS_BOUND);
1461                                }
1462                            }
1463                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1464                        }
1465                    } else {
1466                        // Should never happen ideally.
1467                        Slog.w(TAG, "Empty queue");
1468                    }
1469                    break;
1470                }
1471                case MCS_RECONNECT: {
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1473                    if (mPendingInstalls.size() > 0) {
1474                        if (mBound) {
1475                            disconnectService();
1476                        }
1477                        if (!connectToService()) {
1478                            Slog.e(TAG, "Failed to bind to media container service");
1479                            for (HandlerParams params : mPendingInstalls) {
1480                                // Indicate service bind error
1481                                params.serviceError();
1482                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1483                                        System.identityHashCode(params));
1484                            }
1485                            mPendingInstalls.clear();
1486                        }
1487                    }
1488                    break;
1489                }
1490                case MCS_UNBIND: {
1491                    // If there is no actual work left, then time to unbind.
1492                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1493
1494                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1495                        if (mBound) {
1496                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1497
1498                            disconnectService();
1499                        }
1500                    } else if (mPendingInstalls.size() > 0) {
1501                        // There are more pending requests in queue.
1502                        // Just post MCS_BOUND message to trigger processing
1503                        // of next pending install.
1504                        mHandler.sendEmptyMessage(MCS_BOUND);
1505                    }
1506
1507                    break;
1508                }
1509                case MCS_GIVE_UP: {
1510                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1511                    HandlerParams params = mPendingInstalls.remove(0);
1512                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                            System.identityHashCode(params));
1514                    break;
1515                }
1516                case SEND_PENDING_BROADCAST: {
1517                    String packages[];
1518                    ArrayList<String> components[];
1519                    int size = 0;
1520                    int uids[];
1521                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1522                    synchronized (mPackages) {
1523                        if (mPendingBroadcasts == null) {
1524                            return;
1525                        }
1526                        size = mPendingBroadcasts.size();
1527                        if (size <= 0) {
1528                            // Nothing to be done. Just return
1529                            return;
1530                        }
1531                        packages = new String[size];
1532                        components = new ArrayList[size];
1533                        uids = new int[size];
1534                        int i = 0;  // filling out the above arrays
1535
1536                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1537                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1538                            Iterator<Map.Entry<String, ArrayList<String>>> it
1539                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1540                                            .entrySet().iterator();
1541                            while (it.hasNext() && i < size) {
1542                                Map.Entry<String, ArrayList<String>> ent = it.next();
1543                                packages[i] = ent.getKey();
1544                                components[i] = ent.getValue();
1545                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1546                                uids[i] = (ps != null)
1547                                        ? UserHandle.getUid(packageUserId, ps.appId)
1548                                        : -1;
1549                                i++;
1550                            }
1551                        }
1552                        size = i;
1553                        mPendingBroadcasts.clear();
1554                    }
1555                    // Send broadcasts
1556                    for (int i = 0; i < size; i++) {
1557                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1558                    }
1559                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1560                    break;
1561                }
1562                case START_CLEANING_PACKAGE: {
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1564                    final String packageName = (String)msg.obj;
1565                    final int userId = msg.arg1;
1566                    final boolean andCode = msg.arg2 != 0;
1567                    synchronized (mPackages) {
1568                        if (userId == UserHandle.USER_ALL) {
1569                            int[] users = sUserManager.getUserIds();
1570                            for (int user : users) {
1571                                mSettings.addPackageToCleanLPw(
1572                                        new PackageCleanItem(user, packageName, andCode));
1573                            }
1574                        } else {
1575                            mSettings.addPackageToCleanLPw(
1576                                    new PackageCleanItem(userId, packageName, andCode));
1577                        }
1578                    }
1579                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1580                    startCleaningPackages();
1581                } break;
1582                case POST_INSTALL: {
1583                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1584
1585                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1586                    final boolean didRestore = (msg.arg2 != 0);
1587                    mRunningInstalls.delete(msg.arg1);
1588
1589                    if (data != null) {
1590                        InstallArgs args = data.args;
1591                        PackageInstalledInfo parentRes = data.res;
1592
1593                        final boolean grantPermissions = (args.installFlags
1594                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1595                        final boolean killApp = (args.installFlags
1596                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1597                        final String[] grantedPermissions = args.installGrantPermissions;
1598
1599                        // Handle the parent package
1600                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1601                                grantedPermissions, didRestore, args.installerPackageName,
1602                                args.observer);
1603
1604                        // Handle the child packages
1605                        final int childCount = (parentRes.addedChildPackages != null)
1606                                ? parentRes.addedChildPackages.size() : 0;
1607                        for (int i = 0; i < childCount; i++) {
1608                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1609                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1610                                    grantedPermissions, false, args.installerPackageName,
1611                                    args.observer);
1612                        }
1613
1614                        // Log tracing if needed
1615                        if (args.traceMethod != null) {
1616                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1617                                    args.traceCookie);
1618                        }
1619                    } else {
1620                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1621                    }
1622
1623                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1624                } break;
1625                case UPDATED_MEDIA_STATUS: {
1626                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1627                    boolean reportStatus = msg.arg1 == 1;
1628                    boolean doGc = msg.arg2 == 1;
1629                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1630                    if (doGc) {
1631                        // Force a gc to clear up stale containers.
1632                        Runtime.getRuntime().gc();
1633                    }
1634                    if (msg.obj != null) {
1635                        @SuppressWarnings("unchecked")
1636                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1637                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1638                        // Unload containers
1639                        unloadAllContainers(args);
1640                    }
1641                    if (reportStatus) {
1642                        try {
1643                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1644                            PackageHelper.getMountService().finishMediaUpdate();
1645                        } catch (RemoteException e) {
1646                            Log.e(TAG, "MountService not running?");
1647                        }
1648                    }
1649                } break;
1650                case WRITE_SETTINGS: {
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1652                    synchronized (mPackages) {
1653                        removeMessages(WRITE_SETTINGS);
1654                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1655                        mSettings.writeLPr();
1656                        mDirtyUsers.clear();
1657                    }
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1659                } break;
1660                case WRITE_PACKAGE_RESTRICTIONS: {
1661                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1662                    synchronized (mPackages) {
1663                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1664                        for (int userId : mDirtyUsers) {
1665                            mSettings.writePackageRestrictionsLPr(userId);
1666                        }
1667                        mDirtyUsers.clear();
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                } break;
1671                case WRITE_PACKAGE_LIST: {
1672                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1673                    synchronized (mPackages) {
1674                        removeMessages(WRITE_PACKAGE_LIST);
1675                        mSettings.writePackageListLPr(msg.arg1);
1676                    }
1677                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1678                } break;
1679                case CHECK_PENDING_VERIFICATION: {
1680                    final int verificationId = msg.arg1;
1681                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1682
1683                    if ((state != null) && !state.timeoutExtended()) {
1684                        final InstallArgs args = state.getInstallArgs();
1685                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1686
1687                        Slog.i(TAG, "Verification timed out for " + originUri);
1688                        mPendingVerification.remove(verificationId);
1689
1690                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1691
1692                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1693                            Slog.i(TAG, "Continuing with installation of " + originUri);
1694                            state.setVerifierResponse(Binder.getCallingUid(),
1695                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1696                            broadcastPackageVerified(verificationId, originUri,
1697                                    PackageManager.VERIFICATION_ALLOW,
1698                                    state.getInstallArgs().getUser());
1699                            try {
1700                                ret = args.copyApk(mContainerService, true);
1701                            } catch (RemoteException e) {
1702                                Slog.e(TAG, "Could not contact the ContainerService");
1703                            }
1704                        } else {
1705                            broadcastPackageVerified(verificationId, originUri,
1706                                    PackageManager.VERIFICATION_REJECT,
1707                                    state.getInstallArgs().getUser());
1708                        }
1709
1710                        Trace.asyncTraceEnd(
1711                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1712
1713                        processPendingInstall(args, ret);
1714                        mHandler.sendEmptyMessage(MCS_UNBIND);
1715                    }
1716                    break;
1717                }
1718                case PACKAGE_VERIFIED: {
1719                    final int verificationId = msg.arg1;
1720
1721                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1722                    if (state == null) {
1723                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1724                        break;
1725                    }
1726
1727                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1728
1729                    state.setVerifierResponse(response.callerUid, response.code);
1730
1731                    if (state.isVerificationComplete()) {
1732                        mPendingVerification.remove(verificationId);
1733
1734                        final InstallArgs args = state.getInstallArgs();
1735                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1736
1737                        int ret;
1738                        if (state.isInstallAllowed()) {
1739                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1740                            broadcastPackageVerified(verificationId, originUri,
1741                                    response.code, state.getInstallArgs().getUser());
1742                            try {
1743                                ret = args.copyApk(mContainerService, true);
1744                            } catch (RemoteException e) {
1745                                Slog.e(TAG, "Could not contact the ContainerService");
1746                            }
1747                        } else {
1748                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1749                        }
1750
1751                        Trace.asyncTraceEnd(
1752                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1753
1754                        processPendingInstall(args, ret);
1755                        mHandler.sendEmptyMessage(MCS_UNBIND);
1756                    }
1757
1758                    break;
1759                }
1760                case START_INTENT_FILTER_VERIFICATIONS: {
1761                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1762                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1763                            params.replacing, params.pkg);
1764                    break;
1765                }
1766                case INTENT_FILTER_VERIFIED: {
1767                    final int verificationId = msg.arg1;
1768
1769                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1770                            verificationId);
1771                    if (state == null) {
1772                        Slog.w(TAG, "Invalid IntentFilter verification token "
1773                                + verificationId + " received");
1774                        break;
1775                    }
1776
1777                    final int userId = state.getUserId();
1778
1779                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1780                            "Processing IntentFilter verification with token:"
1781                            + verificationId + " and userId:" + userId);
1782
1783                    final IntentFilterVerificationResponse response =
1784                            (IntentFilterVerificationResponse) msg.obj;
1785
1786                    state.setVerifierResponse(response.callerUid, response.code);
1787
1788                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1789                            "IntentFilter verification with token:" + verificationId
1790                            + " and userId:" + userId
1791                            + " is settings verifier response with response code:"
1792                            + response.code);
1793
1794                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1795                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1796                                + response.getFailedDomainsString());
1797                    }
1798
1799                    if (state.isVerificationComplete()) {
1800                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1801                    } else {
1802                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1803                                "IntentFilter verification with token:" + verificationId
1804                                + " was not said to be complete");
1805                    }
1806
1807                    break;
1808                }
1809            }
1810        }
1811    }
1812
1813    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1814            boolean killApp, String[] grantedPermissions,
1815            boolean launchedForRestore, String installerPackage,
1816            IPackageInstallObserver2 installObserver) {
1817        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1818            // Send the removed broadcasts
1819            if (res.removedInfo != null) {
1820                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1821            }
1822
1823            // Now that we successfully installed the package, grant runtime
1824            // permissions if requested before broadcasting the install.
1825            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1826                    >= Build.VERSION_CODES.M) {
1827                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1828            }
1829
1830            final boolean update = res.removedInfo != null
1831                    && res.removedInfo.removedPackage != null;
1832
1833            // If this is the first time we have child packages for a disabled privileged
1834            // app that had no children, we grant requested runtime permissions to the new
1835            // children if the parent on the system image had them already granted.
1836            if (res.pkg.parentPackage != null) {
1837                synchronized (mPackages) {
1838                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1839                }
1840            }
1841
1842            synchronized (mPackages) {
1843                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1844            }
1845
1846            final String packageName = res.pkg.applicationInfo.packageName;
1847            Bundle extras = new Bundle(1);
1848            extras.putInt(Intent.EXTRA_UID, res.uid);
1849
1850            // Determine the set of users who are adding this package for
1851            // the first time vs. those who are seeing an update.
1852            int[] firstUsers = EMPTY_INT_ARRAY;
1853            int[] updateUsers = EMPTY_INT_ARRAY;
1854            if (res.origUsers == null || res.origUsers.length == 0) {
1855                firstUsers = res.newUsers;
1856            } else {
1857                for (int newUser : res.newUsers) {
1858                    boolean isNew = true;
1859                    for (int origUser : res.origUsers) {
1860                        if (origUser == newUser) {
1861                            isNew = false;
1862                            break;
1863                        }
1864                    }
1865                    if (isNew) {
1866                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1867                    } else {
1868                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1869                    }
1870                }
1871            }
1872
1873            // Send installed broadcasts if the install/update is not ephemeral
1874            if (!isEphemeral(res.pkg)) {
1875                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1876
1877                // Send added for users that see the package for the first time
1878                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1879                        extras, 0 /*flags*/, null /*targetPackage*/,
1880                        null /*finishedReceiver*/, firstUsers);
1881
1882                // Send added for users that don't see the package for the first time
1883                if (update) {
1884                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1885                }
1886                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1887                        extras, 0 /*flags*/, null /*targetPackage*/,
1888                        null /*finishedReceiver*/, updateUsers);
1889
1890                // Send replaced for users that don't see the package for the first time
1891                if (update) {
1892                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1893                            packageName, extras, 0 /*flags*/,
1894                            null /*targetPackage*/, null /*finishedReceiver*/,
1895                            updateUsers);
1896                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1897                            null /*package*/, null /*extras*/, 0 /*flags*/,
1898                            packageName /*targetPackage*/,
1899                            null /*finishedReceiver*/, updateUsers);
1900                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1901                    // First-install and we did a restore, so we're responsible for the
1902                    // first-launch broadcast.
1903                    if (DEBUG_BACKUP) {
1904                        Slog.i(TAG, "Post-restore of " + packageName
1905                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1906                    }
1907                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1908                }
1909
1910                // Send broadcast package appeared if forward locked/external for all users
1911                // treat asec-hosted packages like removable media on upgrade
1912                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1913                    if (DEBUG_INSTALL) {
1914                        Slog.i(TAG, "upgrading pkg " + res.pkg
1915                                + " is ASEC-hosted -> AVAILABLE");
1916                    }
1917                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1918                    ArrayList<String> pkgList = new ArrayList<>(1);
1919                    pkgList.add(packageName);
1920                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1921                }
1922            }
1923
1924            // Work that needs to happen on first install within each user
1925            if (firstUsers != null && firstUsers.length > 0) {
1926                synchronized (mPackages) {
1927                    for (int userId : firstUsers) {
1928                        // If this app is a browser and it's newly-installed for some
1929                        // users, clear any default-browser state in those users. The
1930                        // app's nature doesn't depend on the user, so we can just check
1931                        // its browser nature in any user and generalize.
1932                        if (packageIsBrowser(packageName, userId)) {
1933                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1934                        }
1935
1936                        // We may also need to apply pending (restored) runtime
1937                        // permission grants within these users.
1938                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1939                    }
1940                }
1941            }
1942
1943            // Log current value of "unknown sources" setting
1944            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1945                    getUnknownSourcesSettings());
1946
1947            // Force a gc to clear up things
1948            Runtime.getRuntime().gc();
1949
1950            // Remove the replaced package's older resources safely now
1951            // We delete after a gc for applications  on sdcard.
1952            if (res.removedInfo != null && res.removedInfo.args != null) {
1953                synchronized (mInstallLock) {
1954                    res.removedInfo.args.doPostDeleteLI(true);
1955                }
1956            }
1957        }
1958
1959        // If someone is watching installs - notify them
1960        if (installObserver != null) {
1961            try {
1962                Bundle extras = extrasForInstallResult(res);
1963                installObserver.onPackageInstalled(res.name, res.returnCode,
1964                        res.returnMsg, extras);
1965            } catch (RemoteException e) {
1966                Slog.i(TAG, "Observer no longer exists.");
1967            }
1968        }
1969    }
1970
1971    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1972            PackageParser.Package pkg) {
1973        if (pkg.parentPackage == null) {
1974            return;
1975        }
1976        if (pkg.requestedPermissions == null) {
1977            return;
1978        }
1979        final PackageSetting disabledSysParentPs = mSettings
1980                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1981        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1982                || !disabledSysParentPs.isPrivileged()
1983                || (disabledSysParentPs.childPackageNames != null
1984                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1985            return;
1986        }
1987        final int[] allUserIds = sUserManager.getUserIds();
1988        final int permCount = pkg.requestedPermissions.size();
1989        for (int i = 0; i < permCount; i++) {
1990            String permission = pkg.requestedPermissions.get(i);
1991            BasePermission bp = mSettings.mPermissions.get(permission);
1992            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1993                continue;
1994            }
1995            for (int userId : allUserIds) {
1996                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1997                        permission, userId)) {
1998                    grantRuntimePermission(pkg.packageName, permission, userId);
1999                }
2000            }
2001        }
2002    }
2003
2004    private StorageEventListener mStorageListener = new StorageEventListener() {
2005        @Override
2006        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2007            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2008                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2009                    final String volumeUuid = vol.getFsUuid();
2010
2011                    // Clean up any users or apps that were removed or recreated
2012                    // while this volume was missing
2013                    reconcileUsers(volumeUuid);
2014                    reconcileApps(volumeUuid);
2015
2016                    // Clean up any install sessions that expired or were
2017                    // cancelled while this volume was missing
2018                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2019
2020                    loadPrivatePackages(vol);
2021
2022                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2023                    unloadPrivatePackages(vol);
2024                }
2025            }
2026
2027            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2028                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2029                    updateExternalMediaStatus(true, false);
2030                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2031                    updateExternalMediaStatus(false, false);
2032                }
2033            }
2034        }
2035
2036        @Override
2037        public void onVolumeForgotten(String fsUuid) {
2038            if (TextUtils.isEmpty(fsUuid)) {
2039                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2040                return;
2041            }
2042
2043            // Remove any apps installed on the forgotten volume
2044            synchronized (mPackages) {
2045                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2046                for (PackageSetting ps : packages) {
2047                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2048                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2049                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2050                }
2051
2052                mSettings.onVolumeForgotten(fsUuid);
2053                mSettings.writeLPr();
2054            }
2055        }
2056    };
2057
2058    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2059            String[] grantedPermissions) {
2060        for (int userId : userIds) {
2061            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2062        }
2063
2064        // We could have touched GID membership, so flush out packages.list
2065        synchronized (mPackages) {
2066            mSettings.writePackageListLPr();
2067        }
2068    }
2069
2070    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2071            String[] grantedPermissions) {
2072        SettingBase sb = (SettingBase) pkg.mExtras;
2073        if (sb == null) {
2074            return;
2075        }
2076
2077        PermissionsState permissionsState = sb.getPermissionsState();
2078
2079        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2080                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2081
2082        for (String permission : pkg.requestedPermissions) {
2083            final BasePermission bp;
2084            synchronized (mPackages) {
2085                bp = mSettings.mPermissions.get(permission);
2086            }
2087            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2088                    && (grantedPermissions == null
2089                           || ArrayUtils.contains(grantedPermissions, permission))) {
2090                final int flags = permissionsState.getPermissionFlags(permission, userId);
2091                // Installer cannot change immutable permissions.
2092                if ((flags & immutableFlags) == 0) {
2093                    grantRuntimePermission(pkg.packageName, permission, userId);
2094                }
2095            }
2096        }
2097    }
2098
2099    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2100        Bundle extras = null;
2101        switch (res.returnCode) {
2102            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2103                extras = new Bundle();
2104                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2105                        res.origPermission);
2106                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2107                        res.origPackage);
2108                break;
2109            }
2110            case PackageManager.INSTALL_SUCCEEDED: {
2111                extras = new Bundle();
2112                extras.putBoolean(Intent.EXTRA_REPLACING,
2113                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2114                break;
2115            }
2116        }
2117        return extras;
2118    }
2119
2120    void scheduleWriteSettingsLocked() {
2121        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2122            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2123        }
2124    }
2125
2126    void scheduleWritePackageListLocked(int userId) {
2127        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2128            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2129            msg.arg1 = userId;
2130            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2131        }
2132    }
2133
2134    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2135        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2136        scheduleWritePackageRestrictionsLocked(userId);
2137    }
2138
2139    void scheduleWritePackageRestrictionsLocked(int userId) {
2140        final int[] userIds = (userId == UserHandle.USER_ALL)
2141                ? sUserManager.getUserIds() : new int[]{userId};
2142        for (int nextUserId : userIds) {
2143            if (!sUserManager.exists(nextUserId)) return;
2144            mDirtyUsers.add(nextUserId);
2145            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2146                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2147            }
2148        }
2149    }
2150
2151    public static PackageManagerService main(Context context, Installer installer,
2152            boolean factoryTest, boolean onlyCore) {
2153        // Self-check for initial settings.
2154        PackageManagerServiceCompilerMapping.checkProperties();
2155
2156        PackageManagerService m = new PackageManagerService(context, installer,
2157                factoryTest, onlyCore);
2158        m.enableSystemUserPackages();
2159        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2160        // disabled after already being started.
2161        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2162                UserHandle.USER_SYSTEM);
2163        ServiceManager.addService("package", m);
2164        return m;
2165    }
2166
2167    private void enableSystemUserPackages() {
2168        if (!UserManager.isSplitSystemUser()) {
2169            return;
2170        }
2171        // For system user, enable apps based on the following conditions:
2172        // - app is whitelisted or belong to one of these groups:
2173        //   -- system app which has no launcher icons
2174        //   -- system app which has INTERACT_ACROSS_USERS permission
2175        //   -- system IME app
2176        // - app is not in the blacklist
2177        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2178        Set<String> enableApps = new ArraySet<>();
2179        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2180                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2181                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2182        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2183        enableApps.addAll(wlApps);
2184        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2185                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2186        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2187        enableApps.removeAll(blApps);
2188        Log.i(TAG, "Applications installed for system user: " + enableApps);
2189        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2190                UserHandle.SYSTEM);
2191        final int allAppsSize = allAps.size();
2192        synchronized (mPackages) {
2193            for (int i = 0; i < allAppsSize; i++) {
2194                String pName = allAps.get(i);
2195                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2196                // Should not happen, but we shouldn't be failing if it does
2197                if (pkgSetting == null) {
2198                    continue;
2199                }
2200                boolean install = enableApps.contains(pName);
2201                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2202                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2203                            + " for system user");
2204                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2205                }
2206            }
2207        }
2208    }
2209
2210    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2211        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2212                Context.DISPLAY_SERVICE);
2213        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2214    }
2215
2216    public PackageManagerService(Context context, Installer installer,
2217            boolean factoryTest, boolean onlyCore) {
2218        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2219                SystemClock.uptimeMillis());
2220
2221        if (mSdkVersion <= 0) {
2222            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2223        }
2224
2225        mContext = context;
2226        mFactoryTest = factoryTest;
2227        mOnlyCore = onlyCore;
2228        mMetrics = new DisplayMetrics();
2229        mSettings = new Settings(mPackages);
2230        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2231                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2232        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2233                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2234        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242
2243        String separateProcesses = SystemProperties.get("debug.separate_processes");
2244        if (separateProcesses != null && separateProcesses.length() > 0) {
2245            if ("*".equals(separateProcesses)) {
2246                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2247                mSeparateProcesses = null;
2248                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2249            } else {
2250                mDefParseFlags = 0;
2251                mSeparateProcesses = separateProcesses.split(",");
2252                Slog.w(TAG, "Running with debug.separate_processes: "
2253                        + separateProcesses);
2254            }
2255        } else {
2256            mDefParseFlags = 0;
2257            mSeparateProcesses = null;
2258        }
2259
2260        mInstaller = installer;
2261        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2262                "*dexopt*");
2263        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2264
2265        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2266                FgThread.get().getLooper());
2267
2268        getDefaultDisplayMetrics(context, mMetrics);
2269
2270        SystemConfig systemConfig = SystemConfig.getInstance();
2271        mGlobalGids = systemConfig.getGlobalGids();
2272        mSystemPermissions = systemConfig.getSystemPermissions();
2273        mAvailableFeatures = systemConfig.getAvailableFeatures();
2274
2275        synchronized (mInstallLock) {
2276        // writer
2277        synchronized (mPackages) {
2278            mHandlerThread = new ServiceThread(TAG,
2279                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2280            mHandlerThread.start();
2281            mHandler = new PackageHandler(mHandlerThread.getLooper());
2282            mProcessLoggingHandler = new ProcessLoggingHandler();
2283            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2284
2285            File dataDir = Environment.getDataDirectory();
2286            mAppInstallDir = new File(dataDir, "app");
2287            mAppLib32InstallDir = new File(dataDir, "app-lib");
2288            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2289            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2290            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2291
2292            sUserManager = new UserManagerService(context, this, mPackages);
2293
2294            // Propagate permission configuration in to package manager.
2295            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2296                    = systemConfig.getPermissions();
2297            for (int i=0; i<permConfig.size(); i++) {
2298                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2299                BasePermission bp = mSettings.mPermissions.get(perm.name);
2300                if (bp == null) {
2301                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2302                    mSettings.mPermissions.put(perm.name, bp);
2303                }
2304                if (perm.gids != null) {
2305                    bp.setGids(perm.gids, perm.perUser);
2306                }
2307            }
2308
2309            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2310            for (int i=0; i<libConfig.size(); i++) {
2311                mSharedLibraries.put(libConfig.keyAt(i),
2312                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2313            }
2314
2315            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2316
2317            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2318
2319            String customResolverActivity = Resources.getSystem().getString(
2320                    R.string.config_customResolverActivity);
2321            if (TextUtils.isEmpty(customResolverActivity)) {
2322                customResolverActivity = null;
2323            } else {
2324                mCustomResolverComponentName = ComponentName.unflattenFromString(
2325                        customResolverActivity);
2326            }
2327
2328            long startTime = SystemClock.uptimeMillis();
2329
2330            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2331                    startTime);
2332
2333            // Set flag to monitor and not change apk file paths when
2334            // scanning install directories.
2335            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2336
2337            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2338            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2339
2340            if (bootClassPath == null) {
2341                Slog.w(TAG, "No BOOTCLASSPATH found!");
2342            }
2343
2344            if (systemServerClassPath == null) {
2345                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2346            }
2347
2348            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2349            final String[] dexCodeInstructionSets =
2350                    getDexCodeInstructionSets(
2351                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2352
2353            /**
2354             * Ensure all external libraries have had dexopt run on them.
2355             */
2356            if (mSharedLibraries.size() > 0) {
2357                // NOTE: For now, we're compiling these system "shared libraries"
2358                // (and framework jars) into all available architectures. It's possible
2359                // to compile them only when we come across an app that uses them (there's
2360                // already logic for that in scanPackageLI) but that adds some complexity.
2361                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2362                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2363                        final String lib = libEntry.path;
2364                        if (lib == null) {
2365                            continue;
2366                        }
2367
2368                        try {
2369                            // Shared libraries do not have profiles so we perform a full
2370                            // AOT compilation (if needed).
2371                            int dexoptNeeded = DexFile.getDexOptNeeded(
2372                                    lib, dexCodeInstructionSet,
2373                                    getCompilerFilterForReason(REASON_SHARED_APK),
2374                                    false /* newProfile */);
2375                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2376                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2377                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2378                                        getCompilerFilterForReason(REASON_SHARED_APK),
2379                                        StorageManager.UUID_PRIVATE_INTERNAL,
2380                                        SKIP_SHARED_LIBRARY_CHECK);
2381                            }
2382                        } catch (FileNotFoundException e) {
2383                            Slog.w(TAG, "Library not found: " + lib);
2384                        } catch (IOException | InstallerException e) {
2385                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2386                                    + e.getMessage());
2387                        }
2388                    }
2389                }
2390            }
2391
2392            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2393
2394            final VersionInfo ver = mSettings.getInternalVersion();
2395            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2396
2397            // when upgrading from pre-M, promote system app permissions from install to runtime
2398            mPromoteSystemApps =
2399                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2400
2401            // When upgrading from pre-N, we need to handle package extraction like first boot,
2402            // as there is no profiling data available.
2403            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2404
2405            // save off the names of pre-existing system packages prior to scanning; we don't
2406            // want to automatically grant runtime permissions for new system apps
2407            if (mPromoteSystemApps) {
2408                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2409                while (pkgSettingIter.hasNext()) {
2410                    PackageSetting ps = pkgSettingIter.next();
2411                    if (isSystemApp(ps)) {
2412                        mExistingSystemPackages.add(ps.name);
2413                    }
2414                }
2415            }
2416
2417            // Collect vendor overlay packages.
2418            // (Do this before scanning any apps.)
2419            // For security and version matching reason, only consider
2420            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2421            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2422            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2423                    | PackageParser.PARSE_IS_SYSTEM
2424                    | PackageParser.PARSE_IS_SYSTEM_DIR
2425                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2426
2427            // Find base frameworks (resource packages without code).
2428            scanDirTracedLI(frameworkDir, mDefParseFlags
2429                    | PackageParser.PARSE_IS_SYSTEM
2430                    | PackageParser.PARSE_IS_SYSTEM_DIR
2431                    | PackageParser.PARSE_IS_PRIVILEGED,
2432                    scanFlags | SCAN_NO_DEX, 0);
2433
2434            // Collected privileged system packages.
2435            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2436            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2437                    | PackageParser.PARSE_IS_SYSTEM
2438                    | PackageParser.PARSE_IS_SYSTEM_DIR
2439                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2440
2441            // Collect ordinary system packages.
2442            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2443            scanDirTracedLI(systemAppDir, mDefParseFlags
2444                    | PackageParser.PARSE_IS_SYSTEM
2445                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2446
2447            // Collect all vendor packages.
2448            File vendorAppDir = new File("/vendor/app");
2449            try {
2450                vendorAppDir = vendorAppDir.getCanonicalFile();
2451            } catch (IOException e) {
2452                // failed to look up canonical path, continue with original one
2453            }
2454            scanDirTracedLI(vendorAppDir, mDefParseFlags
2455                    | PackageParser.PARSE_IS_SYSTEM
2456                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2457
2458            // Collect all OEM packages.
2459            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2460            scanDirTracedLI(oemAppDir, mDefParseFlags
2461                    | PackageParser.PARSE_IS_SYSTEM
2462                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2463
2464            // Prune any system packages that no longer exist.
2465            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2466            if (!mOnlyCore) {
2467                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2468                while (psit.hasNext()) {
2469                    PackageSetting ps = psit.next();
2470
2471                    /*
2472                     * If this is not a system app, it can't be a
2473                     * disable system app.
2474                     */
2475                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2476                        continue;
2477                    }
2478
2479                    /*
2480                     * If the package is scanned, it's not erased.
2481                     */
2482                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2483                    if (scannedPkg != null) {
2484                        /*
2485                         * If the system app is both scanned and in the
2486                         * disabled packages list, then it must have been
2487                         * added via OTA. Remove it from the currently
2488                         * scanned package so the previously user-installed
2489                         * application can be scanned.
2490                         */
2491                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2492                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2493                                    + ps.name + "; removing system app.  Last known codePath="
2494                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2495                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2496                                    + scannedPkg.mVersionCode);
2497                            removePackageLI(scannedPkg, true);
2498                            mExpectingBetter.put(ps.name, ps.codePath);
2499                        }
2500
2501                        continue;
2502                    }
2503
2504                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2505                        psit.remove();
2506                        logCriticalInfo(Log.WARN, "System package " + ps.name
2507                                + " no longer exists; it's data will be wiped");
2508                        // Actual deletion of code and data will be handled by later
2509                        // reconciliation step
2510                    } else {
2511                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2512                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2513                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2514                        }
2515                    }
2516                }
2517            }
2518
2519            //look for any incomplete package installations
2520            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2521            for (int i = 0; i < deletePkgsList.size(); i++) {
2522                // Actual deletion of code and data will be handled by later
2523                // reconciliation step
2524                final String packageName = deletePkgsList.get(i).name;
2525                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2526                synchronized (mPackages) {
2527                    mSettings.removePackageLPw(packageName);
2528                }
2529            }
2530
2531            //delete tmp files
2532            deleteTempPackageFiles();
2533
2534            // Remove any shared userIDs that have no associated packages
2535            mSettings.pruneSharedUsersLPw();
2536
2537            if (!mOnlyCore) {
2538                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2539                        SystemClock.uptimeMillis());
2540                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2541
2542                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2543                        | PackageParser.PARSE_FORWARD_LOCK,
2544                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2545
2546                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2547                        | PackageParser.PARSE_IS_EPHEMERAL,
2548                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2549
2550                /**
2551                 * Remove disable package settings for any updated system
2552                 * apps that were removed via an OTA. If they're not a
2553                 * previously-updated app, remove them completely.
2554                 * Otherwise, just revoke their system-level permissions.
2555                 */
2556                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2557                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2558                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2559
2560                    String msg;
2561                    if (deletedPkg == null) {
2562                        msg = "Updated system package " + deletedAppName
2563                                + " no longer exists; it's data will be wiped";
2564                        // Actual deletion of code and data will be handled by later
2565                        // reconciliation step
2566                    } else {
2567                        msg = "Updated system app + " + deletedAppName
2568                                + " no longer present; removing system privileges for "
2569                                + deletedAppName;
2570
2571                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2572
2573                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2574                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2575                    }
2576                    logCriticalInfo(Log.WARN, msg);
2577                }
2578
2579                /**
2580                 * Make sure all system apps that we expected to appear on
2581                 * the userdata partition actually showed up. If they never
2582                 * appeared, crawl back and revive the system version.
2583                 */
2584                for (int i = 0; i < mExpectingBetter.size(); i++) {
2585                    final String packageName = mExpectingBetter.keyAt(i);
2586                    if (!mPackages.containsKey(packageName)) {
2587                        final File scanFile = mExpectingBetter.valueAt(i);
2588
2589                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2590                                + " but never showed up; reverting to system");
2591
2592                        int reparseFlags = mDefParseFlags;
2593                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2594                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2595                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2596                                    | PackageParser.PARSE_IS_PRIVILEGED;
2597                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2598                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2599                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2600                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2601                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2602                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2603                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2604                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2605                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2606                        } else {
2607                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2608                            continue;
2609                        }
2610
2611                        mSettings.enableSystemPackageLPw(packageName);
2612
2613                        try {
2614                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2615                        } catch (PackageManagerException e) {
2616                            Slog.e(TAG, "Failed to parse original system package: "
2617                                    + e.getMessage());
2618                        }
2619                    }
2620                }
2621            }
2622            mExpectingBetter.clear();
2623
2624            // Resolve protected action filters. Only the setup wizard is allowed to
2625            // have a high priority filter for these actions.
2626            mSetupWizardPackage = getSetupWizardPackageName();
2627            if (mProtectedFilters.size() > 0) {
2628                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2629                    Slog.i(TAG, "No setup wizard;"
2630                        + " All protected intents capped to priority 0");
2631                }
2632                for (ActivityIntentInfo filter : mProtectedFilters) {
2633                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2634                        if (DEBUG_FILTERS) {
2635                            Slog.i(TAG, "Found setup wizard;"
2636                                + " allow priority " + filter.getPriority() + ";"
2637                                + " package: " + filter.activity.info.packageName
2638                                + " activity: " + filter.activity.className
2639                                + " priority: " + filter.getPriority());
2640                        }
2641                        // skip setup wizard; allow it to keep the high priority filter
2642                        continue;
2643                    }
2644                    Slog.w(TAG, "Protected action; cap priority to 0;"
2645                            + " package: " + filter.activity.info.packageName
2646                            + " activity: " + filter.activity.className
2647                            + " origPrio: " + filter.getPriority());
2648                    filter.setPriority(0);
2649                }
2650            }
2651            mDeferProtectedFilters = false;
2652            mProtectedFilters.clear();
2653
2654            // Now that we know all of the shared libraries, update all clients to have
2655            // the correct library paths.
2656            updateAllSharedLibrariesLPw();
2657
2658            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2659                // NOTE: We ignore potential failures here during a system scan (like
2660                // the rest of the commands above) because there's precious little we
2661                // can do about it. A settings error is reported, though.
2662                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2663                        false /* boot complete */);
2664            }
2665
2666            // Now that we know all the packages we are keeping,
2667            // read and update their last usage times.
2668            mPackageUsage.readLP();
2669
2670            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2671                    SystemClock.uptimeMillis());
2672            Slog.i(TAG, "Time to scan packages: "
2673                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2674                    + " seconds");
2675
2676            // If the platform SDK has changed since the last time we booted,
2677            // we need to re-grant app permission to catch any new ones that
2678            // appear.  This is really a hack, and means that apps can in some
2679            // cases get permissions that the user didn't initially explicitly
2680            // allow...  it would be nice to have some better way to handle
2681            // this situation.
2682            int updateFlags = UPDATE_PERMISSIONS_ALL;
2683            if (ver.sdkVersion != mSdkVersion) {
2684                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2685                        + mSdkVersion + "; regranting permissions for internal storage");
2686                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2687            }
2688            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2689            ver.sdkVersion = mSdkVersion;
2690
2691            // If this is the first boot or an update from pre-M, and it is a normal
2692            // boot, then we need to initialize the default preferred apps across
2693            // all defined users.
2694            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2695                for (UserInfo user : sUserManager.getUsers(true)) {
2696                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2697                    applyFactoryDefaultBrowserLPw(user.id);
2698                    primeDomainVerificationsLPw(user.id);
2699                }
2700            }
2701
2702            // Prepare storage for system user really early during boot,
2703            // since core system apps like SettingsProvider and SystemUI
2704            // can't wait for user to start
2705            final int storageFlags;
2706            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2707                storageFlags = StorageManager.FLAG_STORAGE_DE;
2708            } else {
2709                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2710            }
2711            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2712                    storageFlags);
2713
2714            // If this is first boot after an OTA, and a normal boot, then
2715            // we need to clear code cache directories.
2716            // Note that we do *not* clear the application profiles. These remain valid
2717            // across OTAs and are used to drive profile verification (post OTA) and
2718            // profile compilation (without waiting to collect a fresh set of profiles).
2719            if (mIsUpgrade && !onlyCore) {
2720                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2721                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2722                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2723                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2724                        // No apps are running this early, so no need to freeze
2725                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2726                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2727                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2728                    }
2729                }
2730                ver.fingerprint = Build.FINGERPRINT;
2731            }
2732
2733            checkDefaultBrowser();
2734
2735            // clear only after permissions and other defaults have been updated
2736            mExistingSystemPackages.clear();
2737            mPromoteSystemApps = false;
2738
2739            // All the changes are done during package scanning.
2740            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2741
2742            // can downgrade to reader
2743            mSettings.writeLPr();
2744
2745            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2746            // early on (before the package manager declares itself as early) because other
2747            // components in the system server might ask for package contexts for these apps.
2748            //
2749            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2750            // (i.e, that the data partition is unavailable).
2751            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2752                long start = System.nanoTime();
2753                List<PackageParser.Package> coreApps = new ArrayList<>();
2754                for (PackageParser.Package pkg : mPackages.values()) {
2755                    if (pkg.coreApp) {
2756                        coreApps.add(pkg);
2757                    }
2758                }
2759
2760                int[] stats = performDexOpt(coreApps, false,
2761                        getCompilerFilterForReason(REASON_CORE_APP));
2762
2763                final int elapsedTimeSeconds =
2764                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2765                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2766
2767                if (DEBUG_DEXOPT) {
2768                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2769                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2770                }
2771
2772
2773                // TODO: Should we log these stats to tron too ?
2774                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2775                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2776                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2777                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2778            }
2779
2780            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2781                    SystemClock.uptimeMillis());
2782
2783            if (!mOnlyCore) {
2784                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2785                mRequiredInstallerPackage = getRequiredInstallerLPr();
2786                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2787                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2788                        mIntentFilterVerifierComponent);
2789                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2790                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2791                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2792                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2793            } else {
2794                mRequiredVerifierPackage = null;
2795                mRequiredInstallerPackage = null;
2796                mIntentFilterVerifierComponent = null;
2797                mIntentFilterVerifier = null;
2798                mServicesSystemSharedLibraryPackageName = null;
2799                mSharedSystemSharedLibraryPackageName = null;
2800            }
2801
2802            mInstallerService = new PackageInstallerService(context, this);
2803
2804            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2805            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2806            // both the installer and resolver must be present to enable ephemeral
2807            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2808                if (DEBUG_EPHEMERAL) {
2809                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2810                            + " installer:" + ephemeralInstallerComponent);
2811                }
2812                mEphemeralResolverComponent = ephemeralResolverComponent;
2813                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2814                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2815                mEphemeralResolverConnection =
2816                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2817            } else {
2818                if (DEBUG_EPHEMERAL) {
2819                    final String missingComponent =
2820                            (ephemeralResolverComponent == null)
2821                            ? (ephemeralInstallerComponent == null)
2822                                    ? "resolver and installer"
2823                                    : "resolver"
2824                            : "installer";
2825                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2826                }
2827                mEphemeralResolverComponent = null;
2828                mEphemeralInstallerComponent = null;
2829                mEphemeralResolverConnection = null;
2830            }
2831
2832            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2833        } // synchronized (mPackages)
2834        } // synchronized (mInstallLock)
2835
2836        // Now after opening every single application zip, make sure they
2837        // are all flushed.  Not really needed, but keeps things nice and
2838        // tidy.
2839        Runtime.getRuntime().gc();
2840
2841        // The initial scanning above does many calls into installd while
2842        // holding the mPackages lock, but we're mostly interested in yelling
2843        // once we have a booted system.
2844        mInstaller.setWarnIfHeld(mPackages);
2845
2846        // Expose private service for system components to use.
2847        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2848    }
2849
2850    @Override
2851    public boolean isFirstBoot() {
2852        return !mRestoredSettings;
2853    }
2854
2855    @Override
2856    public boolean isOnlyCoreApps() {
2857        return mOnlyCore;
2858    }
2859
2860    @Override
2861    public boolean isUpgrade() {
2862        return mIsUpgrade;
2863    }
2864
2865    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2866        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2867
2868        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2869                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2870                UserHandle.USER_SYSTEM);
2871        if (matches.size() == 1) {
2872            return matches.get(0).getComponentInfo().packageName;
2873        } else {
2874            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2875            return null;
2876        }
2877    }
2878
2879    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2880        synchronized (mPackages) {
2881            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2882            if (libraryEntry == null) {
2883                throw new IllegalStateException("Missing required shared library:" + libraryName);
2884            }
2885            return libraryEntry.apk;
2886        }
2887    }
2888
2889    private @NonNull String getRequiredInstallerLPr() {
2890        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2891        intent.addCategory(Intent.CATEGORY_DEFAULT);
2892        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2893
2894        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2895                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2896                UserHandle.USER_SYSTEM);
2897        if (matches.size() == 1) {
2898            ResolveInfo resolveInfo = matches.get(0);
2899            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2900                throw new RuntimeException("The installer must be a privileged app");
2901            }
2902            return matches.get(0).getComponentInfo().packageName;
2903        } else {
2904            throw new RuntimeException("There must be exactly one installer; found " + matches);
2905        }
2906    }
2907
2908    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2909        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2910
2911        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2912                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2913                UserHandle.USER_SYSTEM);
2914        ResolveInfo best = null;
2915        final int N = matches.size();
2916        for (int i = 0; i < N; i++) {
2917            final ResolveInfo cur = matches.get(i);
2918            final String packageName = cur.getComponentInfo().packageName;
2919            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2920                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2921                continue;
2922            }
2923
2924            if (best == null || cur.priority > best.priority) {
2925                best = cur;
2926            }
2927        }
2928
2929        if (best != null) {
2930            return best.getComponentInfo().getComponentName();
2931        } else {
2932            throw new RuntimeException("There must be at least one intent filter verifier");
2933        }
2934    }
2935
2936    private @Nullable ComponentName getEphemeralResolverLPr() {
2937        final String[] packageArray =
2938                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2939        if (packageArray.length == 0) {
2940            if (DEBUG_EPHEMERAL) {
2941                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2942            }
2943            return null;
2944        }
2945
2946        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2947        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2948                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2949                UserHandle.USER_SYSTEM);
2950
2951        final int N = resolvers.size();
2952        if (N == 0) {
2953            if (DEBUG_EPHEMERAL) {
2954                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2955            }
2956            return null;
2957        }
2958
2959        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2960        for (int i = 0; i < N; i++) {
2961            final ResolveInfo info = resolvers.get(i);
2962
2963            if (info.serviceInfo == null) {
2964                continue;
2965            }
2966
2967            final String packageName = info.serviceInfo.packageName;
2968            if (!possiblePackages.contains(packageName)) {
2969                if (DEBUG_EPHEMERAL) {
2970                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2971                            + " pkg: " + packageName + ", info:" + info);
2972                }
2973                continue;
2974            }
2975
2976            if (DEBUG_EPHEMERAL) {
2977                Slog.v(TAG, "Ephemeral resolver found;"
2978                        + " pkg: " + packageName + ", info:" + info);
2979            }
2980            return new ComponentName(packageName, info.serviceInfo.name);
2981        }
2982        if (DEBUG_EPHEMERAL) {
2983            Slog.v(TAG, "Ephemeral resolver NOT found");
2984        }
2985        return null;
2986    }
2987
2988    private @Nullable ComponentName getEphemeralInstallerLPr() {
2989        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2990        intent.addCategory(Intent.CATEGORY_DEFAULT);
2991        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2992
2993        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2994                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2995                UserHandle.USER_SYSTEM);
2996        if (matches.size() == 0) {
2997            return null;
2998        } else if (matches.size() == 1) {
2999            return matches.get(0).getComponentInfo().getComponentName();
3000        } else {
3001            throw new RuntimeException(
3002                    "There must be at most one ephemeral installer; found " + matches);
3003        }
3004    }
3005
3006    private void primeDomainVerificationsLPw(int userId) {
3007        if (DEBUG_DOMAIN_VERIFICATION) {
3008            Slog.d(TAG, "Priming domain verifications in user " + userId);
3009        }
3010
3011        SystemConfig systemConfig = SystemConfig.getInstance();
3012        ArraySet<String> packages = systemConfig.getLinkedApps();
3013        ArraySet<String> domains = new ArraySet<String>();
3014
3015        for (String packageName : packages) {
3016            PackageParser.Package pkg = mPackages.get(packageName);
3017            if (pkg != null) {
3018                if (!pkg.isSystemApp()) {
3019                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3020                    continue;
3021                }
3022
3023                domains.clear();
3024                for (PackageParser.Activity a : pkg.activities) {
3025                    for (ActivityIntentInfo filter : a.intents) {
3026                        if (hasValidDomains(filter)) {
3027                            domains.addAll(filter.getHostsList());
3028                        }
3029                    }
3030                }
3031
3032                if (domains.size() > 0) {
3033                    if (DEBUG_DOMAIN_VERIFICATION) {
3034                        Slog.v(TAG, "      + " + packageName);
3035                    }
3036                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3037                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3038                    // and then 'always' in the per-user state actually used for intent resolution.
3039                    final IntentFilterVerificationInfo ivi;
3040                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3041                            new ArrayList<String>(domains));
3042                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3043                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3044                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3045                } else {
3046                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3047                            + "' does not handle web links");
3048                }
3049            } else {
3050                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3051            }
3052        }
3053
3054        scheduleWritePackageRestrictionsLocked(userId);
3055        scheduleWriteSettingsLocked();
3056    }
3057
3058    private void applyFactoryDefaultBrowserLPw(int userId) {
3059        // The default browser app's package name is stored in a string resource,
3060        // with a product-specific overlay used for vendor customization.
3061        String browserPkg = mContext.getResources().getString(
3062                com.android.internal.R.string.default_browser);
3063        if (!TextUtils.isEmpty(browserPkg)) {
3064            // non-empty string => required to be a known package
3065            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3066            if (ps == null) {
3067                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3068                browserPkg = null;
3069            } else {
3070                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3071            }
3072        }
3073
3074        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3075        // default.  If there's more than one, just leave everything alone.
3076        if (browserPkg == null) {
3077            calculateDefaultBrowserLPw(userId);
3078        }
3079    }
3080
3081    private void calculateDefaultBrowserLPw(int userId) {
3082        List<String> allBrowsers = resolveAllBrowserApps(userId);
3083        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3084        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3085    }
3086
3087    private List<String> resolveAllBrowserApps(int userId) {
3088        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3089        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3090                PackageManager.MATCH_ALL, userId);
3091
3092        final int count = list.size();
3093        List<String> result = new ArrayList<String>(count);
3094        for (int i=0; i<count; i++) {
3095            ResolveInfo info = list.get(i);
3096            if (info.activityInfo == null
3097                    || !info.handleAllWebDataURI
3098                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3099                    || result.contains(info.activityInfo.packageName)) {
3100                continue;
3101            }
3102            result.add(info.activityInfo.packageName);
3103        }
3104
3105        return result;
3106    }
3107
3108    private boolean packageIsBrowser(String packageName, int userId) {
3109        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3110                PackageManager.MATCH_ALL, userId);
3111        final int N = list.size();
3112        for (int i = 0; i < N; i++) {
3113            ResolveInfo info = list.get(i);
3114            if (packageName.equals(info.activityInfo.packageName)) {
3115                return true;
3116            }
3117        }
3118        return false;
3119    }
3120
3121    private void checkDefaultBrowser() {
3122        final int myUserId = UserHandle.myUserId();
3123        final String packageName = getDefaultBrowserPackageName(myUserId);
3124        if (packageName != null) {
3125            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3126            if (info == null) {
3127                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3128                synchronized (mPackages) {
3129                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3130                }
3131            }
3132        }
3133    }
3134
3135    @Override
3136    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3137            throws RemoteException {
3138        try {
3139            return super.onTransact(code, data, reply, flags);
3140        } catch (RuntimeException e) {
3141            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3142                Slog.wtf(TAG, "Package Manager Crash", e);
3143            }
3144            throw e;
3145        }
3146    }
3147
3148    static int[] appendInts(int[] cur, int[] add) {
3149        if (add == null) return cur;
3150        if (cur == null) return add;
3151        final int N = add.length;
3152        for (int i=0; i<N; i++) {
3153            cur = appendInt(cur, add[i]);
3154        }
3155        return cur;
3156    }
3157
3158    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3159        if (!sUserManager.exists(userId)) return null;
3160        if (ps == null) {
3161            return null;
3162        }
3163        final PackageParser.Package p = ps.pkg;
3164        if (p == null) {
3165            return null;
3166        }
3167
3168        final PermissionsState permissionsState = ps.getPermissionsState();
3169
3170        final int[] gids = permissionsState.computeGids(userId);
3171        final Set<String> permissions = permissionsState.getPermissions(userId);
3172        final PackageUserState state = ps.readUserState(userId);
3173
3174        return PackageParser.generatePackageInfo(p, gids, flags,
3175                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3176    }
3177
3178    @Override
3179    public void checkPackageStartable(String packageName, int userId) {
3180        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3181
3182        synchronized (mPackages) {
3183            final PackageSetting ps = mSettings.mPackages.get(packageName);
3184            if (ps == null) {
3185                throw new SecurityException("Package " + packageName + " was not found!");
3186            }
3187
3188            if (!ps.getInstalled(userId)) {
3189                throw new SecurityException(
3190                        "Package " + packageName + " was not installed for user " + userId + "!");
3191            }
3192
3193            if (mSafeMode && !ps.isSystem()) {
3194                throw new SecurityException("Package " + packageName + " not a system app!");
3195            }
3196
3197            if (mFrozenPackages.contains(packageName)) {
3198                throw new SecurityException("Package " + packageName + " is currently frozen!");
3199            }
3200
3201            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3202                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3203                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3204            }
3205        }
3206    }
3207
3208    @Override
3209    public boolean isPackageAvailable(String packageName, int userId) {
3210        if (!sUserManager.exists(userId)) return false;
3211        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3212                false /* requireFullPermission */, false /* checkShell */, "is package available");
3213        synchronized (mPackages) {
3214            PackageParser.Package p = mPackages.get(packageName);
3215            if (p != null) {
3216                final PackageSetting ps = (PackageSetting) p.mExtras;
3217                if (ps != null) {
3218                    final PackageUserState state = ps.readUserState(userId);
3219                    if (state != null) {
3220                        return PackageParser.isAvailable(state);
3221                    }
3222                }
3223            }
3224        }
3225        return false;
3226    }
3227
3228    @Override
3229    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return null;
3231        flags = updateFlagsForPackage(flags, userId, packageName);
3232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3233                false /* requireFullPermission */, false /* checkShell */, "get package info");
3234        // reader
3235        synchronized (mPackages) {
3236            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3237            PackageParser.Package p = null;
3238            if (matchFactoryOnly) {
3239                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3240                if (ps != null) {
3241                    return generatePackageInfo(ps, flags, userId);
3242                }
3243            }
3244            if (p == null) {
3245                p = mPackages.get(packageName);
3246                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3247                    return null;
3248                }
3249            }
3250            if (DEBUG_PACKAGE_INFO)
3251                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3252            if (p != null) {
3253                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3254            }
3255            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3256                final PackageSetting ps = mSettings.mPackages.get(packageName);
3257                return generatePackageInfo(ps, flags, userId);
3258            }
3259        }
3260        return null;
3261    }
3262
3263    @Override
3264    public String[] currentToCanonicalPackageNames(String[] names) {
3265        String[] out = new String[names.length];
3266        // reader
3267        synchronized (mPackages) {
3268            for (int i=names.length-1; i>=0; i--) {
3269                PackageSetting ps = mSettings.mPackages.get(names[i]);
3270                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3271            }
3272        }
3273        return out;
3274    }
3275
3276    @Override
3277    public String[] canonicalToCurrentPackageNames(String[] names) {
3278        String[] out = new String[names.length];
3279        // reader
3280        synchronized (mPackages) {
3281            for (int i=names.length-1; i>=0; i--) {
3282                String cur = mSettings.mRenamedPackages.get(names[i]);
3283                out[i] = cur != null ? cur : names[i];
3284            }
3285        }
3286        return out;
3287    }
3288
3289    @Override
3290    public int getPackageUid(String packageName, int flags, int userId) {
3291        if (!sUserManager.exists(userId)) return -1;
3292        flags = updateFlagsForPackage(flags, userId, packageName);
3293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3294                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3295
3296        // reader
3297        synchronized (mPackages) {
3298            final PackageParser.Package p = mPackages.get(packageName);
3299            if (p != null && p.isMatch(flags)) {
3300                return UserHandle.getUid(userId, p.applicationInfo.uid);
3301            }
3302            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3303                final PackageSetting ps = mSettings.mPackages.get(packageName);
3304                if (ps != null && ps.isMatch(flags)) {
3305                    return UserHandle.getUid(userId, ps.appId);
3306                }
3307            }
3308        }
3309
3310        return -1;
3311    }
3312
3313    @Override
3314    public int[] getPackageGids(String packageName, int flags, int userId) {
3315        if (!sUserManager.exists(userId)) return null;
3316        flags = updateFlagsForPackage(flags, userId, packageName);
3317        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3318                false /* requireFullPermission */, false /* checkShell */,
3319                "getPackageGids");
3320
3321        // reader
3322        synchronized (mPackages) {
3323            final PackageParser.Package p = mPackages.get(packageName);
3324            if (p != null && p.isMatch(flags)) {
3325                PackageSetting ps = (PackageSetting) p.mExtras;
3326                return ps.getPermissionsState().computeGids(userId);
3327            }
3328            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3329                final PackageSetting ps = mSettings.mPackages.get(packageName);
3330                if (ps != null && ps.isMatch(flags)) {
3331                    return ps.getPermissionsState().computeGids(userId);
3332                }
3333            }
3334        }
3335
3336        return null;
3337    }
3338
3339    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3340        if (bp.perm != null) {
3341            return PackageParser.generatePermissionInfo(bp.perm, flags);
3342        }
3343        PermissionInfo pi = new PermissionInfo();
3344        pi.name = bp.name;
3345        pi.packageName = bp.sourcePackage;
3346        pi.nonLocalizedLabel = bp.name;
3347        pi.protectionLevel = bp.protectionLevel;
3348        return pi;
3349    }
3350
3351    @Override
3352    public PermissionInfo getPermissionInfo(String name, int flags) {
3353        // reader
3354        synchronized (mPackages) {
3355            final BasePermission p = mSettings.mPermissions.get(name);
3356            if (p != null) {
3357                return generatePermissionInfo(p, flags);
3358            }
3359            return null;
3360        }
3361    }
3362
3363    @Override
3364    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3365            int flags) {
3366        // reader
3367        synchronized (mPackages) {
3368            if (group != null && !mPermissionGroups.containsKey(group)) {
3369                // This is thrown as NameNotFoundException
3370                return null;
3371            }
3372
3373            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3374            for (BasePermission p : mSettings.mPermissions.values()) {
3375                if (group == null) {
3376                    if (p.perm == null || p.perm.info.group == null) {
3377                        out.add(generatePermissionInfo(p, flags));
3378                    }
3379                } else {
3380                    if (p.perm != null && group.equals(p.perm.info.group)) {
3381                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3382                    }
3383                }
3384            }
3385            return new ParceledListSlice<>(out);
3386        }
3387    }
3388
3389    @Override
3390    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3391        // reader
3392        synchronized (mPackages) {
3393            return PackageParser.generatePermissionGroupInfo(
3394                    mPermissionGroups.get(name), flags);
3395        }
3396    }
3397
3398    @Override
3399    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3400        // reader
3401        synchronized (mPackages) {
3402            final int N = mPermissionGroups.size();
3403            ArrayList<PermissionGroupInfo> out
3404                    = new ArrayList<PermissionGroupInfo>(N);
3405            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3406                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3407            }
3408            return new ParceledListSlice<>(out);
3409        }
3410    }
3411
3412    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3413            int userId) {
3414        if (!sUserManager.exists(userId)) return null;
3415        PackageSetting ps = mSettings.mPackages.get(packageName);
3416        if (ps != null) {
3417            if (ps.pkg == null) {
3418                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3419                if (pInfo != null) {
3420                    return pInfo.applicationInfo;
3421                }
3422                return null;
3423            }
3424            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3425                    ps.readUserState(userId), userId);
3426        }
3427        return null;
3428    }
3429
3430    @Override
3431    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3432        if (!sUserManager.exists(userId)) return null;
3433        flags = updateFlagsForApplication(flags, userId, packageName);
3434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3435                false /* requireFullPermission */, false /* checkShell */, "get application info");
3436        // writer
3437        synchronized (mPackages) {
3438            PackageParser.Package p = mPackages.get(packageName);
3439            if (DEBUG_PACKAGE_INFO) Log.v(
3440                    TAG, "getApplicationInfo " + packageName
3441                    + ": " + p);
3442            if (p != null) {
3443                PackageSetting ps = mSettings.mPackages.get(packageName);
3444                if (ps == null) return null;
3445                // Note: isEnabledLP() does not apply here - always return info
3446                return PackageParser.generateApplicationInfo(
3447                        p, flags, ps.readUserState(userId), userId);
3448            }
3449            if ("android".equals(packageName)||"system".equals(packageName)) {
3450                return mAndroidApplication;
3451            }
3452            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3453                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3454            }
3455        }
3456        return null;
3457    }
3458
3459    @Override
3460    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3461            final IPackageDataObserver observer) {
3462        mContext.enforceCallingOrSelfPermission(
3463                android.Manifest.permission.CLEAR_APP_CACHE, null);
3464        // Queue up an async operation since clearing cache may take a little while.
3465        mHandler.post(new Runnable() {
3466            public void run() {
3467                mHandler.removeCallbacks(this);
3468                boolean success = true;
3469                synchronized (mInstallLock) {
3470                    try {
3471                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3472                    } catch (InstallerException e) {
3473                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3474                        success = false;
3475                    }
3476                }
3477                if (observer != null) {
3478                    try {
3479                        observer.onRemoveCompleted(null, success);
3480                    } catch (RemoteException e) {
3481                        Slog.w(TAG, "RemoveException when invoking call back");
3482                    }
3483                }
3484            }
3485        });
3486    }
3487
3488    @Override
3489    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3490            final IntentSender pi) {
3491        mContext.enforceCallingOrSelfPermission(
3492                android.Manifest.permission.CLEAR_APP_CACHE, null);
3493        // Queue up an async operation since clearing cache may take a little while.
3494        mHandler.post(new Runnable() {
3495            public void run() {
3496                mHandler.removeCallbacks(this);
3497                boolean success = true;
3498                synchronized (mInstallLock) {
3499                    try {
3500                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3501                    } catch (InstallerException e) {
3502                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3503                        success = false;
3504                    }
3505                }
3506                if(pi != null) {
3507                    try {
3508                        // Callback via pending intent
3509                        int code = success ? 1 : 0;
3510                        pi.sendIntent(null, code, null,
3511                                null, null);
3512                    } catch (SendIntentException e1) {
3513                        Slog.i(TAG, "Failed to send pending intent");
3514                    }
3515                }
3516            }
3517        });
3518    }
3519
3520    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3521        synchronized (mInstallLock) {
3522            try {
3523                mInstaller.freeCache(volumeUuid, freeStorageSize);
3524            } catch (InstallerException e) {
3525                throw new IOException("Failed to free enough space", e);
3526            }
3527        }
3528    }
3529
3530    /**
3531     * Update given flags based on encryption status of current user.
3532     */
3533    private int updateFlags(int flags, int userId) {
3534        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3535                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3536            // Caller expressed an explicit opinion about what encryption
3537            // aware/unaware components they want to see, so fall through and
3538            // give them what they want
3539        } else {
3540            // Caller expressed no opinion, so match based on user state
3541            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3542                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3543            } else {
3544                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3545            }
3546        }
3547        return flags;
3548    }
3549
3550    private UserManagerInternal getUserManagerInternal() {
3551        if (mUserManagerInternal == null) {
3552            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3553        }
3554        return mUserManagerInternal;
3555    }
3556
3557    /**
3558     * Update given flags when being used to request {@link PackageInfo}.
3559     */
3560    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3561        boolean triaged = true;
3562        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3563                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3564            // Caller is asking for component details, so they'd better be
3565            // asking for specific encryption matching behavior, or be triaged
3566            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3567                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3568                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3569                triaged = false;
3570            }
3571        }
3572        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3573                | PackageManager.MATCH_SYSTEM_ONLY
3574                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3575            triaged = false;
3576        }
3577        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3578            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3579                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3580        }
3581        return updateFlags(flags, userId);
3582    }
3583
3584    /**
3585     * Update given flags when being used to request {@link ApplicationInfo}.
3586     */
3587    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3588        return updateFlagsForPackage(flags, userId, cookie);
3589    }
3590
3591    /**
3592     * Update given flags when being used to request {@link ComponentInfo}.
3593     */
3594    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3595        if (cookie instanceof Intent) {
3596            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3597                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3598            }
3599        }
3600
3601        boolean triaged = true;
3602        // Caller is asking for component details, so they'd better be
3603        // asking for specific encryption matching behavior, or be triaged
3604        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3605                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3606                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3607            triaged = false;
3608        }
3609        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3610            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3611                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3612        }
3613
3614        return updateFlags(flags, userId);
3615    }
3616
3617    /**
3618     * Update given flags when being used to request {@link ResolveInfo}.
3619     */
3620    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3621        // Safe mode means we shouldn't match any third-party components
3622        if (mSafeMode) {
3623            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3624        }
3625
3626        return updateFlagsForComponent(flags, userId, cookie);
3627    }
3628
3629    @Override
3630    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3631        if (!sUserManager.exists(userId)) return null;
3632        flags = updateFlagsForComponent(flags, userId, component);
3633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3634                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3635        synchronized (mPackages) {
3636            PackageParser.Activity a = mActivities.mActivities.get(component);
3637
3638            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3639            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3640                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3641                if (ps == null) return null;
3642                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3643                        userId);
3644            }
3645            if (mResolveComponentName.equals(component)) {
3646                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3647                        new PackageUserState(), userId);
3648            }
3649        }
3650        return null;
3651    }
3652
3653    @Override
3654    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3655            String resolvedType) {
3656        synchronized (mPackages) {
3657            if (component.equals(mResolveComponentName)) {
3658                // The resolver supports EVERYTHING!
3659                return true;
3660            }
3661            PackageParser.Activity a = mActivities.mActivities.get(component);
3662            if (a == null) {
3663                return false;
3664            }
3665            for (int i=0; i<a.intents.size(); i++) {
3666                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3667                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3668                    return true;
3669                }
3670            }
3671            return false;
3672        }
3673    }
3674
3675    @Override
3676    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3677        if (!sUserManager.exists(userId)) return null;
3678        flags = updateFlagsForComponent(flags, userId, component);
3679        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3680                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3681        synchronized (mPackages) {
3682            PackageParser.Activity a = mReceivers.mActivities.get(component);
3683            if (DEBUG_PACKAGE_INFO) Log.v(
3684                TAG, "getReceiverInfo " + component + ": " + a);
3685            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3686                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3687                if (ps == null) return null;
3688                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3689                        userId);
3690            }
3691        }
3692        return null;
3693    }
3694
3695    @Override
3696    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3697        if (!sUserManager.exists(userId)) return null;
3698        flags = updateFlagsForComponent(flags, userId, component);
3699        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3700                false /* requireFullPermission */, false /* checkShell */, "get service info");
3701        synchronized (mPackages) {
3702            PackageParser.Service s = mServices.mServices.get(component);
3703            if (DEBUG_PACKAGE_INFO) Log.v(
3704                TAG, "getServiceInfo " + component + ": " + s);
3705            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3706                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3707                if (ps == null) return null;
3708                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3709                        userId);
3710            }
3711        }
3712        return null;
3713    }
3714
3715    @Override
3716    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3717        if (!sUserManager.exists(userId)) return null;
3718        flags = updateFlagsForComponent(flags, userId, component);
3719        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3720                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3721        synchronized (mPackages) {
3722            PackageParser.Provider p = mProviders.mProviders.get(component);
3723            if (DEBUG_PACKAGE_INFO) Log.v(
3724                TAG, "getProviderInfo " + component + ": " + p);
3725            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3726                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3727                if (ps == null) return null;
3728                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3729                        userId);
3730            }
3731        }
3732        return null;
3733    }
3734
3735    @Override
3736    public String[] getSystemSharedLibraryNames() {
3737        Set<String> libSet;
3738        synchronized (mPackages) {
3739            libSet = mSharedLibraries.keySet();
3740            int size = libSet.size();
3741            if (size > 0) {
3742                String[] libs = new String[size];
3743                libSet.toArray(libs);
3744                return libs;
3745            }
3746        }
3747        return null;
3748    }
3749
3750    @Override
3751    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3752        synchronized (mPackages) {
3753            return mServicesSystemSharedLibraryPackageName;
3754        }
3755    }
3756
3757    @Override
3758    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3759        synchronized (mPackages) {
3760            return mSharedSystemSharedLibraryPackageName;
3761        }
3762    }
3763
3764    @Override
3765    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3766        synchronized (mPackages) {
3767            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3768
3769            final FeatureInfo fi = new FeatureInfo();
3770            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3771                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3772            res.add(fi);
3773
3774            return new ParceledListSlice<>(res);
3775        }
3776    }
3777
3778    @Override
3779    public boolean hasSystemFeature(String name, int version) {
3780        synchronized (mPackages) {
3781            final FeatureInfo feat = mAvailableFeatures.get(name);
3782            if (feat == null) {
3783                return false;
3784            } else {
3785                return feat.version >= version;
3786            }
3787        }
3788    }
3789
3790    @Override
3791    public int checkPermission(String permName, String pkgName, int userId) {
3792        if (!sUserManager.exists(userId)) {
3793            return PackageManager.PERMISSION_DENIED;
3794        }
3795
3796        synchronized (mPackages) {
3797            final PackageParser.Package p = mPackages.get(pkgName);
3798            if (p != null && p.mExtras != null) {
3799                final PackageSetting ps = (PackageSetting) p.mExtras;
3800                final PermissionsState permissionsState = ps.getPermissionsState();
3801                if (permissionsState.hasPermission(permName, userId)) {
3802                    return PackageManager.PERMISSION_GRANTED;
3803                }
3804                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3805                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3806                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3807                    return PackageManager.PERMISSION_GRANTED;
3808                }
3809            }
3810        }
3811
3812        return PackageManager.PERMISSION_DENIED;
3813    }
3814
3815    @Override
3816    public int checkUidPermission(String permName, int uid) {
3817        final int userId = UserHandle.getUserId(uid);
3818
3819        if (!sUserManager.exists(userId)) {
3820            return PackageManager.PERMISSION_DENIED;
3821        }
3822
3823        synchronized (mPackages) {
3824            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3825            if (obj != null) {
3826                final SettingBase ps = (SettingBase) obj;
3827                final PermissionsState permissionsState = ps.getPermissionsState();
3828                if (permissionsState.hasPermission(permName, userId)) {
3829                    return PackageManager.PERMISSION_GRANTED;
3830                }
3831                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3832                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3833                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3834                    return PackageManager.PERMISSION_GRANTED;
3835                }
3836            } else {
3837                ArraySet<String> perms = mSystemPermissions.get(uid);
3838                if (perms != null) {
3839                    if (perms.contains(permName)) {
3840                        return PackageManager.PERMISSION_GRANTED;
3841                    }
3842                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3843                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3844                        return PackageManager.PERMISSION_GRANTED;
3845                    }
3846                }
3847            }
3848        }
3849
3850        return PackageManager.PERMISSION_DENIED;
3851    }
3852
3853    @Override
3854    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3855        if (UserHandle.getCallingUserId() != userId) {
3856            mContext.enforceCallingPermission(
3857                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3858                    "isPermissionRevokedByPolicy for user " + userId);
3859        }
3860
3861        if (checkPermission(permission, packageName, userId)
3862                == PackageManager.PERMISSION_GRANTED) {
3863            return false;
3864        }
3865
3866        final long identity = Binder.clearCallingIdentity();
3867        try {
3868            final int flags = getPermissionFlags(permission, packageName, userId);
3869            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3870        } finally {
3871            Binder.restoreCallingIdentity(identity);
3872        }
3873    }
3874
3875    @Override
3876    public String getPermissionControllerPackageName() {
3877        synchronized (mPackages) {
3878            return mRequiredInstallerPackage;
3879        }
3880    }
3881
3882    /**
3883     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3884     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3885     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3886     * @param message the message to log on security exception
3887     */
3888    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3889            boolean checkShell, String message) {
3890        if (userId < 0) {
3891            throw new IllegalArgumentException("Invalid userId " + userId);
3892        }
3893        if (checkShell) {
3894            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3895        }
3896        if (userId == UserHandle.getUserId(callingUid)) return;
3897        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3898            if (requireFullPermission) {
3899                mContext.enforceCallingOrSelfPermission(
3900                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3901            } else {
3902                try {
3903                    mContext.enforceCallingOrSelfPermission(
3904                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3905                } catch (SecurityException se) {
3906                    mContext.enforceCallingOrSelfPermission(
3907                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3908                }
3909            }
3910        }
3911    }
3912
3913    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3914        if (callingUid == Process.SHELL_UID) {
3915            if (userHandle >= 0
3916                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3917                throw new SecurityException("Shell does not have permission to access user "
3918                        + userHandle);
3919            } else if (userHandle < 0) {
3920                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3921                        + Debug.getCallers(3));
3922            }
3923        }
3924    }
3925
3926    private BasePermission findPermissionTreeLP(String permName) {
3927        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3928            if (permName.startsWith(bp.name) &&
3929                    permName.length() > bp.name.length() &&
3930                    permName.charAt(bp.name.length()) == '.') {
3931                return bp;
3932            }
3933        }
3934        return null;
3935    }
3936
3937    private BasePermission checkPermissionTreeLP(String permName) {
3938        if (permName != null) {
3939            BasePermission bp = findPermissionTreeLP(permName);
3940            if (bp != null) {
3941                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3942                    return bp;
3943                }
3944                throw new SecurityException("Calling uid "
3945                        + Binder.getCallingUid()
3946                        + " is not allowed to add to permission tree "
3947                        + bp.name + " owned by uid " + bp.uid);
3948            }
3949        }
3950        throw new SecurityException("No permission tree found for " + permName);
3951    }
3952
3953    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3954        if (s1 == null) {
3955            return s2 == null;
3956        }
3957        if (s2 == null) {
3958            return false;
3959        }
3960        if (s1.getClass() != s2.getClass()) {
3961            return false;
3962        }
3963        return s1.equals(s2);
3964    }
3965
3966    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3967        if (pi1.icon != pi2.icon) return false;
3968        if (pi1.logo != pi2.logo) return false;
3969        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3970        if (!compareStrings(pi1.name, pi2.name)) return false;
3971        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3972        // We'll take care of setting this one.
3973        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3974        // These are not currently stored in settings.
3975        //if (!compareStrings(pi1.group, pi2.group)) return false;
3976        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3977        //if (pi1.labelRes != pi2.labelRes) return false;
3978        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3979        return true;
3980    }
3981
3982    int permissionInfoFootprint(PermissionInfo info) {
3983        int size = info.name.length();
3984        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3985        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3986        return size;
3987    }
3988
3989    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3990        int size = 0;
3991        for (BasePermission perm : mSettings.mPermissions.values()) {
3992            if (perm.uid == tree.uid) {
3993                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3994            }
3995        }
3996        return size;
3997    }
3998
3999    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4000        // We calculate the max size of permissions defined by this uid and throw
4001        // if that plus the size of 'info' would exceed our stated maximum.
4002        if (tree.uid != Process.SYSTEM_UID) {
4003            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4004            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4005                throw new SecurityException("Permission tree size cap exceeded");
4006            }
4007        }
4008    }
4009
4010    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4011        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4012            throw new SecurityException("Label must be specified in permission");
4013        }
4014        BasePermission tree = checkPermissionTreeLP(info.name);
4015        BasePermission bp = mSettings.mPermissions.get(info.name);
4016        boolean added = bp == null;
4017        boolean changed = true;
4018        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4019        if (added) {
4020            enforcePermissionCapLocked(info, tree);
4021            bp = new BasePermission(info.name, tree.sourcePackage,
4022                    BasePermission.TYPE_DYNAMIC);
4023        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4024            throw new SecurityException(
4025                    "Not allowed to modify non-dynamic permission "
4026                    + info.name);
4027        } else {
4028            if (bp.protectionLevel == fixedLevel
4029                    && bp.perm.owner.equals(tree.perm.owner)
4030                    && bp.uid == tree.uid
4031                    && comparePermissionInfos(bp.perm.info, info)) {
4032                changed = false;
4033            }
4034        }
4035        bp.protectionLevel = fixedLevel;
4036        info = new PermissionInfo(info);
4037        info.protectionLevel = fixedLevel;
4038        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4039        bp.perm.info.packageName = tree.perm.info.packageName;
4040        bp.uid = tree.uid;
4041        if (added) {
4042            mSettings.mPermissions.put(info.name, bp);
4043        }
4044        if (changed) {
4045            if (!async) {
4046                mSettings.writeLPr();
4047            } else {
4048                scheduleWriteSettingsLocked();
4049            }
4050        }
4051        return added;
4052    }
4053
4054    @Override
4055    public boolean addPermission(PermissionInfo info) {
4056        synchronized (mPackages) {
4057            return addPermissionLocked(info, false);
4058        }
4059    }
4060
4061    @Override
4062    public boolean addPermissionAsync(PermissionInfo info) {
4063        synchronized (mPackages) {
4064            return addPermissionLocked(info, true);
4065        }
4066    }
4067
4068    @Override
4069    public void removePermission(String name) {
4070        synchronized (mPackages) {
4071            checkPermissionTreeLP(name);
4072            BasePermission bp = mSettings.mPermissions.get(name);
4073            if (bp != null) {
4074                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4075                    throw new SecurityException(
4076                            "Not allowed to modify non-dynamic permission "
4077                            + name);
4078                }
4079                mSettings.mPermissions.remove(name);
4080                mSettings.writeLPr();
4081            }
4082        }
4083    }
4084
4085    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4086            BasePermission bp) {
4087        int index = pkg.requestedPermissions.indexOf(bp.name);
4088        if (index == -1) {
4089            throw new SecurityException("Package " + pkg.packageName
4090                    + " has not requested permission " + bp.name);
4091        }
4092        if (!bp.isRuntime() && !bp.isDevelopment()) {
4093            throw new SecurityException("Permission " + bp.name
4094                    + " is not a changeable permission type");
4095        }
4096    }
4097
4098    @Override
4099    public void grantRuntimePermission(String packageName, String name, final int userId) {
4100        if (!sUserManager.exists(userId)) {
4101            Log.e(TAG, "No such user:" + userId);
4102            return;
4103        }
4104
4105        mContext.enforceCallingOrSelfPermission(
4106                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4107                "grantRuntimePermission");
4108
4109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4110                true /* requireFullPermission */, true /* checkShell */,
4111                "grantRuntimePermission");
4112
4113        final int uid;
4114        final SettingBase sb;
4115
4116        synchronized (mPackages) {
4117            final PackageParser.Package pkg = mPackages.get(packageName);
4118            if (pkg == null) {
4119                throw new IllegalArgumentException("Unknown package: " + packageName);
4120            }
4121
4122            final BasePermission bp = mSettings.mPermissions.get(name);
4123            if (bp == null) {
4124                throw new IllegalArgumentException("Unknown permission: " + name);
4125            }
4126
4127            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4128
4129            // If a permission review is required for legacy apps we represent
4130            // their permissions as always granted runtime ones since we need
4131            // to keep the review required permission flag per user while an
4132            // install permission's state is shared across all users.
4133            if (Build.PERMISSIONS_REVIEW_REQUIRED
4134                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4135                    && bp.isRuntime()) {
4136                return;
4137            }
4138
4139            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4140            sb = (SettingBase) pkg.mExtras;
4141            if (sb == null) {
4142                throw new IllegalArgumentException("Unknown package: " + packageName);
4143            }
4144
4145            final PermissionsState permissionsState = sb.getPermissionsState();
4146
4147            final int flags = permissionsState.getPermissionFlags(name, userId);
4148            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4149                throw new SecurityException("Cannot grant system fixed permission "
4150                        + name + " for package " + packageName);
4151            }
4152
4153            if (bp.isDevelopment()) {
4154                // Development permissions must be handled specially, since they are not
4155                // normal runtime permissions.  For now they apply to all users.
4156                if (permissionsState.grantInstallPermission(bp) !=
4157                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4158                    scheduleWriteSettingsLocked();
4159                }
4160                return;
4161            }
4162
4163            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4164                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4165                return;
4166            }
4167
4168            final int result = permissionsState.grantRuntimePermission(bp, userId);
4169            switch (result) {
4170                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4171                    return;
4172                }
4173
4174                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4175                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4176                    mHandler.post(new Runnable() {
4177                        @Override
4178                        public void run() {
4179                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4180                        }
4181                    });
4182                }
4183                break;
4184            }
4185
4186            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4187
4188            // Not critical if that is lost - app has to request again.
4189            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4190        }
4191
4192        // Only need to do this if user is initialized. Otherwise it's a new user
4193        // and there are no processes running as the user yet and there's no need
4194        // to make an expensive call to remount processes for the changed permissions.
4195        if (READ_EXTERNAL_STORAGE.equals(name)
4196                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4197            final long token = Binder.clearCallingIdentity();
4198            try {
4199                if (sUserManager.isInitialized(userId)) {
4200                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4201                            MountServiceInternal.class);
4202                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4203                }
4204            } finally {
4205                Binder.restoreCallingIdentity(token);
4206            }
4207        }
4208    }
4209
4210    @Override
4211    public void revokeRuntimePermission(String packageName, String name, int userId) {
4212        if (!sUserManager.exists(userId)) {
4213            Log.e(TAG, "No such user:" + userId);
4214            return;
4215        }
4216
4217        mContext.enforceCallingOrSelfPermission(
4218                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4219                "revokeRuntimePermission");
4220
4221        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4222                true /* requireFullPermission */, true /* checkShell */,
4223                "revokeRuntimePermission");
4224
4225        final int appId;
4226
4227        synchronized (mPackages) {
4228            final PackageParser.Package pkg = mPackages.get(packageName);
4229            if (pkg == null) {
4230                throw new IllegalArgumentException("Unknown package: " + packageName);
4231            }
4232
4233            final BasePermission bp = mSettings.mPermissions.get(name);
4234            if (bp == null) {
4235                throw new IllegalArgumentException("Unknown permission: " + name);
4236            }
4237
4238            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4239
4240            // If a permission review is required for legacy apps we represent
4241            // their permissions as always granted runtime ones since we need
4242            // to keep the review required permission flag per user while an
4243            // install permission's state is shared across all users.
4244            if (Build.PERMISSIONS_REVIEW_REQUIRED
4245                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4246                    && bp.isRuntime()) {
4247                return;
4248            }
4249
4250            SettingBase sb = (SettingBase) pkg.mExtras;
4251            if (sb == null) {
4252                throw new IllegalArgumentException("Unknown package: " + packageName);
4253            }
4254
4255            final PermissionsState permissionsState = sb.getPermissionsState();
4256
4257            final int flags = permissionsState.getPermissionFlags(name, userId);
4258            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4259                throw new SecurityException("Cannot revoke system fixed permission "
4260                        + name + " for package " + packageName);
4261            }
4262
4263            if (bp.isDevelopment()) {
4264                // Development permissions must be handled specially, since they are not
4265                // normal runtime permissions.  For now they apply to all users.
4266                if (permissionsState.revokeInstallPermission(bp) !=
4267                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4268                    scheduleWriteSettingsLocked();
4269                }
4270                return;
4271            }
4272
4273            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4274                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4275                return;
4276            }
4277
4278            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4279
4280            // Critical, after this call app should never have the permission.
4281            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4282
4283            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4284        }
4285
4286        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4287    }
4288
4289    @Override
4290    public void resetRuntimePermissions() {
4291        mContext.enforceCallingOrSelfPermission(
4292                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4293                "revokeRuntimePermission");
4294
4295        int callingUid = Binder.getCallingUid();
4296        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4297            mContext.enforceCallingOrSelfPermission(
4298                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4299                    "resetRuntimePermissions");
4300        }
4301
4302        synchronized (mPackages) {
4303            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4304            for (int userId : UserManagerService.getInstance().getUserIds()) {
4305                final int packageCount = mPackages.size();
4306                for (int i = 0; i < packageCount; i++) {
4307                    PackageParser.Package pkg = mPackages.valueAt(i);
4308                    if (!(pkg.mExtras instanceof PackageSetting)) {
4309                        continue;
4310                    }
4311                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4312                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4313                }
4314            }
4315        }
4316    }
4317
4318    @Override
4319    public int getPermissionFlags(String name, String packageName, int userId) {
4320        if (!sUserManager.exists(userId)) {
4321            return 0;
4322        }
4323
4324        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4325
4326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4327                true /* requireFullPermission */, false /* checkShell */,
4328                "getPermissionFlags");
4329
4330        synchronized (mPackages) {
4331            final PackageParser.Package pkg = mPackages.get(packageName);
4332            if (pkg == null) {
4333                return 0;
4334            }
4335
4336            final BasePermission bp = mSettings.mPermissions.get(name);
4337            if (bp == null) {
4338                return 0;
4339            }
4340
4341            SettingBase sb = (SettingBase) pkg.mExtras;
4342            if (sb == null) {
4343                return 0;
4344            }
4345
4346            PermissionsState permissionsState = sb.getPermissionsState();
4347            return permissionsState.getPermissionFlags(name, userId);
4348        }
4349    }
4350
4351    @Override
4352    public void updatePermissionFlags(String name, String packageName, int flagMask,
4353            int flagValues, int userId) {
4354        if (!sUserManager.exists(userId)) {
4355            return;
4356        }
4357
4358        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4359
4360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4361                true /* requireFullPermission */, true /* checkShell */,
4362                "updatePermissionFlags");
4363
4364        // Only the system can change these flags and nothing else.
4365        if (getCallingUid() != Process.SYSTEM_UID) {
4366            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4367            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4368            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4369            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4370            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4371        }
4372
4373        synchronized (mPackages) {
4374            final PackageParser.Package pkg = mPackages.get(packageName);
4375            if (pkg == null) {
4376                throw new IllegalArgumentException("Unknown package: " + packageName);
4377            }
4378
4379            final BasePermission bp = mSettings.mPermissions.get(name);
4380            if (bp == null) {
4381                throw new IllegalArgumentException("Unknown permission: " + name);
4382            }
4383
4384            SettingBase sb = (SettingBase) pkg.mExtras;
4385            if (sb == null) {
4386                throw new IllegalArgumentException("Unknown package: " + packageName);
4387            }
4388
4389            PermissionsState permissionsState = sb.getPermissionsState();
4390
4391            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4392
4393            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4394                // Install and runtime permissions are stored in different places,
4395                // so figure out what permission changed and persist the change.
4396                if (permissionsState.getInstallPermissionState(name) != null) {
4397                    scheduleWriteSettingsLocked();
4398                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4399                        || hadState) {
4400                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4401                }
4402            }
4403        }
4404    }
4405
4406    /**
4407     * Update the permission flags for all packages and runtime permissions of a user in order
4408     * to allow device or profile owner to remove POLICY_FIXED.
4409     */
4410    @Override
4411    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4412        if (!sUserManager.exists(userId)) {
4413            return;
4414        }
4415
4416        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4417
4418        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4419                true /* requireFullPermission */, true /* checkShell */,
4420                "updatePermissionFlagsForAllApps");
4421
4422        // Only the system can change system fixed flags.
4423        if (getCallingUid() != Process.SYSTEM_UID) {
4424            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4425            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4426        }
4427
4428        synchronized (mPackages) {
4429            boolean changed = false;
4430            final int packageCount = mPackages.size();
4431            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4432                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4433                SettingBase sb = (SettingBase) pkg.mExtras;
4434                if (sb == null) {
4435                    continue;
4436                }
4437                PermissionsState permissionsState = sb.getPermissionsState();
4438                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4439                        userId, flagMask, flagValues);
4440            }
4441            if (changed) {
4442                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4443            }
4444        }
4445    }
4446
4447    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4448        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4449                != PackageManager.PERMISSION_GRANTED
4450            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4451                != PackageManager.PERMISSION_GRANTED) {
4452            throw new SecurityException(message + " requires "
4453                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4454                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4455        }
4456    }
4457
4458    @Override
4459    public boolean shouldShowRequestPermissionRationale(String permissionName,
4460            String packageName, int userId) {
4461        if (UserHandle.getCallingUserId() != userId) {
4462            mContext.enforceCallingPermission(
4463                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4464                    "canShowRequestPermissionRationale for user " + userId);
4465        }
4466
4467        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4468        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4469            return false;
4470        }
4471
4472        if (checkPermission(permissionName, packageName, userId)
4473                == PackageManager.PERMISSION_GRANTED) {
4474            return false;
4475        }
4476
4477        final int flags;
4478
4479        final long identity = Binder.clearCallingIdentity();
4480        try {
4481            flags = getPermissionFlags(permissionName,
4482                    packageName, userId);
4483        } finally {
4484            Binder.restoreCallingIdentity(identity);
4485        }
4486
4487        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4488                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4489                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4490
4491        if ((flags & fixedFlags) != 0) {
4492            return false;
4493        }
4494
4495        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4496    }
4497
4498    @Override
4499    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4500        mContext.enforceCallingOrSelfPermission(
4501                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4502                "addOnPermissionsChangeListener");
4503
4504        synchronized (mPackages) {
4505            mOnPermissionChangeListeners.addListenerLocked(listener);
4506        }
4507    }
4508
4509    @Override
4510    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4511        synchronized (mPackages) {
4512            mOnPermissionChangeListeners.removeListenerLocked(listener);
4513        }
4514    }
4515
4516    @Override
4517    public boolean isProtectedBroadcast(String actionName) {
4518        synchronized (mPackages) {
4519            if (mProtectedBroadcasts.contains(actionName)) {
4520                return true;
4521            } else if (actionName != null) {
4522                // TODO: remove these terrible hacks
4523                if (actionName.startsWith("android.net.netmon.lingerExpired")
4524                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4525                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4526                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4527                    return true;
4528                }
4529            }
4530        }
4531        return false;
4532    }
4533
4534    @Override
4535    public int checkSignatures(String pkg1, String pkg2) {
4536        synchronized (mPackages) {
4537            final PackageParser.Package p1 = mPackages.get(pkg1);
4538            final PackageParser.Package p2 = mPackages.get(pkg2);
4539            if (p1 == null || p1.mExtras == null
4540                    || p2 == null || p2.mExtras == null) {
4541                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4542            }
4543            return compareSignatures(p1.mSignatures, p2.mSignatures);
4544        }
4545    }
4546
4547    @Override
4548    public int checkUidSignatures(int uid1, int uid2) {
4549        // Map to base uids.
4550        uid1 = UserHandle.getAppId(uid1);
4551        uid2 = UserHandle.getAppId(uid2);
4552        // reader
4553        synchronized (mPackages) {
4554            Signature[] s1;
4555            Signature[] s2;
4556            Object obj = mSettings.getUserIdLPr(uid1);
4557            if (obj != null) {
4558                if (obj instanceof SharedUserSetting) {
4559                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4560                } else if (obj instanceof PackageSetting) {
4561                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4562                } else {
4563                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4564                }
4565            } else {
4566                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4567            }
4568            obj = mSettings.getUserIdLPr(uid2);
4569            if (obj != null) {
4570                if (obj instanceof SharedUserSetting) {
4571                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4572                } else if (obj instanceof PackageSetting) {
4573                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4574                } else {
4575                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4576                }
4577            } else {
4578                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4579            }
4580            return compareSignatures(s1, s2);
4581        }
4582    }
4583
4584    /**
4585     * This method should typically only be used when granting or revoking
4586     * permissions, since the app may immediately restart after this call.
4587     * <p>
4588     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4589     * guard your work against the app being relaunched.
4590     */
4591    private void killUid(int appId, int userId, String reason) {
4592        final long identity = Binder.clearCallingIdentity();
4593        try {
4594            IActivityManager am = ActivityManagerNative.getDefault();
4595            if (am != null) {
4596                try {
4597                    am.killUid(appId, userId, reason);
4598                } catch (RemoteException e) {
4599                    /* ignore - same process */
4600                }
4601            }
4602        } finally {
4603            Binder.restoreCallingIdentity(identity);
4604        }
4605    }
4606
4607    /**
4608     * Compares two sets of signatures. Returns:
4609     * <br />
4610     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4611     * <br />
4612     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4613     * <br />
4614     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4615     * <br />
4616     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4617     * <br />
4618     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4619     */
4620    static int compareSignatures(Signature[] s1, Signature[] s2) {
4621        if (s1 == null) {
4622            return s2 == null
4623                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4624                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4625        }
4626
4627        if (s2 == null) {
4628            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4629        }
4630
4631        if (s1.length != s2.length) {
4632            return PackageManager.SIGNATURE_NO_MATCH;
4633        }
4634
4635        // Since both signature sets are of size 1, we can compare without HashSets.
4636        if (s1.length == 1) {
4637            return s1[0].equals(s2[0]) ?
4638                    PackageManager.SIGNATURE_MATCH :
4639                    PackageManager.SIGNATURE_NO_MATCH;
4640        }
4641
4642        ArraySet<Signature> set1 = new ArraySet<Signature>();
4643        for (Signature sig : s1) {
4644            set1.add(sig);
4645        }
4646        ArraySet<Signature> set2 = new ArraySet<Signature>();
4647        for (Signature sig : s2) {
4648            set2.add(sig);
4649        }
4650        // Make sure s2 contains all signatures in s1.
4651        if (set1.equals(set2)) {
4652            return PackageManager.SIGNATURE_MATCH;
4653        }
4654        return PackageManager.SIGNATURE_NO_MATCH;
4655    }
4656
4657    /**
4658     * If the database version for this type of package (internal storage or
4659     * external storage) is less than the version where package signatures
4660     * were updated, return true.
4661     */
4662    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4663        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4664        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4665    }
4666
4667    /**
4668     * Used for backward compatibility to make sure any packages with
4669     * certificate chains get upgraded to the new style. {@code existingSigs}
4670     * will be in the old format (since they were stored on disk from before the
4671     * system upgrade) and {@code scannedSigs} will be in the newer format.
4672     */
4673    private int compareSignaturesCompat(PackageSignatures existingSigs,
4674            PackageParser.Package scannedPkg) {
4675        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4676            return PackageManager.SIGNATURE_NO_MATCH;
4677        }
4678
4679        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4680        for (Signature sig : existingSigs.mSignatures) {
4681            existingSet.add(sig);
4682        }
4683        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4684        for (Signature sig : scannedPkg.mSignatures) {
4685            try {
4686                Signature[] chainSignatures = sig.getChainSignatures();
4687                for (Signature chainSig : chainSignatures) {
4688                    scannedCompatSet.add(chainSig);
4689                }
4690            } catch (CertificateEncodingException e) {
4691                scannedCompatSet.add(sig);
4692            }
4693        }
4694        /*
4695         * Make sure the expanded scanned set contains all signatures in the
4696         * existing one.
4697         */
4698        if (scannedCompatSet.equals(existingSet)) {
4699            // Migrate the old signatures to the new scheme.
4700            existingSigs.assignSignatures(scannedPkg.mSignatures);
4701            // The new KeySets will be re-added later in the scanning process.
4702            synchronized (mPackages) {
4703                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4704            }
4705            return PackageManager.SIGNATURE_MATCH;
4706        }
4707        return PackageManager.SIGNATURE_NO_MATCH;
4708    }
4709
4710    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4711        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4712        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4713    }
4714
4715    private int compareSignaturesRecover(PackageSignatures existingSigs,
4716            PackageParser.Package scannedPkg) {
4717        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4718            return PackageManager.SIGNATURE_NO_MATCH;
4719        }
4720
4721        String msg = null;
4722        try {
4723            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4724                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4725                        + scannedPkg.packageName);
4726                return PackageManager.SIGNATURE_MATCH;
4727            }
4728        } catch (CertificateException e) {
4729            msg = e.getMessage();
4730        }
4731
4732        logCriticalInfo(Log.INFO,
4733                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4734        return PackageManager.SIGNATURE_NO_MATCH;
4735    }
4736
4737    @Override
4738    public List<String> getAllPackages() {
4739        synchronized (mPackages) {
4740            return new ArrayList<String>(mPackages.keySet());
4741        }
4742    }
4743
4744    @Override
4745    public String[] getPackagesForUid(int uid) {
4746        uid = UserHandle.getAppId(uid);
4747        // reader
4748        synchronized (mPackages) {
4749            Object obj = mSettings.getUserIdLPr(uid);
4750            if (obj instanceof SharedUserSetting) {
4751                final SharedUserSetting sus = (SharedUserSetting) obj;
4752                final int N = sus.packages.size();
4753                final String[] res = new String[N];
4754                final Iterator<PackageSetting> it = sus.packages.iterator();
4755                int i = 0;
4756                while (it.hasNext()) {
4757                    res[i++] = it.next().name;
4758                }
4759                return res;
4760            } else if (obj instanceof PackageSetting) {
4761                final PackageSetting ps = (PackageSetting) obj;
4762                return new String[] { ps.name };
4763            }
4764        }
4765        return null;
4766    }
4767
4768    @Override
4769    public String getNameForUid(int uid) {
4770        // reader
4771        synchronized (mPackages) {
4772            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4773            if (obj instanceof SharedUserSetting) {
4774                final SharedUserSetting sus = (SharedUserSetting) obj;
4775                return sus.name + ":" + sus.userId;
4776            } else if (obj instanceof PackageSetting) {
4777                final PackageSetting ps = (PackageSetting) obj;
4778                return ps.name;
4779            }
4780        }
4781        return null;
4782    }
4783
4784    @Override
4785    public int getUidForSharedUser(String sharedUserName) {
4786        if(sharedUserName == null) {
4787            return -1;
4788        }
4789        // reader
4790        synchronized (mPackages) {
4791            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4792            if (suid == null) {
4793                return -1;
4794            }
4795            return suid.userId;
4796        }
4797    }
4798
4799    @Override
4800    public int getFlagsForUid(int uid) {
4801        synchronized (mPackages) {
4802            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4803            if (obj instanceof SharedUserSetting) {
4804                final SharedUserSetting sus = (SharedUserSetting) obj;
4805                return sus.pkgFlags;
4806            } else if (obj instanceof PackageSetting) {
4807                final PackageSetting ps = (PackageSetting) obj;
4808                return ps.pkgFlags;
4809            }
4810        }
4811        return 0;
4812    }
4813
4814    @Override
4815    public int getPrivateFlagsForUid(int uid) {
4816        synchronized (mPackages) {
4817            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4818            if (obj instanceof SharedUserSetting) {
4819                final SharedUserSetting sus = (SharedUserSetting) obj;
4820                return sus.pkgPrivateFlags;
4821            } else if (obj instanceof PackageSetting) {
4822                final PackageSetting ps = (PackageSetting) obj;
4823                return ps.pkgPrivateFlags;
4824            }
4825        }
4826        return 0;
4827    }
4828
4829    @Override
4830    public boolean isUidPrivileged(int uid) {
4831        uid = UserHandle.getAppId(uid);
4832        // reader
4833        synchronized (mPackages) {
4834            Object obj = mSettings.getUserIdLPr(uid);
4835            if (obj instanceof SharedUserSetting) {
4836                final SharedUserSetting sus = (SharedUserSetting) obj;
4837                final Iterator<PackageSetting> it = sus.packages.iterator();
4838                while (it.hasNext()) {
4839                    if (it.next().isPrivileged()) {
4840                        return true;
4841                    }
4842                }
4843            } else if (obj instanceof PackageSetting) {
4844                final PackageSetting ps = (PackageSetting) obj;
4845                return ps.isPrivileged();
4846            }
4847        }
4848        return false;
4849    }
4850
4851    @Override
4852    public String[] getAppOpPermissionPackages(String permissionName) {
4853        synchronized (mPackages) {
4854            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4855            if (pkgs == null) {
4856                return null;
4857            }
4858            return pkgs.toArray(new String[pkgs.size()]);
4859        }
4860    }
4861
4862    @Override
4863    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4864            int flags, int userId) {
4865        try {
4866            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4867
4868            if (!sUserManager.exists(userId)) return null;
4869            flags = updateFlagsForResolve(flags, userId, intent);
4870            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4871                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4872
4873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4874            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4875                    flags, userId);
4876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4877
4878            final ResolveInfo bestChoice =
4879                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4880
4881            if (isEphemeralAllowed(intent, query, userId)) {
4882                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4883                final EphemeralResolveInfo ai =
4884                        getEphemeralResolveInfo(intent, resolvedType, userId);
4885                if (ai != null) {
4886                    if (DEBUG_EPHEMERAL) {
4887                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4888                    }
4889                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4890                    bestChoice.ephemeralResolveInfo = ai;
4891                }
4892                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4893            }
4894            return bestChoice;
4895        } finally {
4896            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4897        }
4898    }
4899
4900    @Override
4901    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4902            IntentFilter filter, int match, ComponentName activity) {
4903        final int userId = UserHandle.getCallingUserId();
4904        if (DEBUG_PREFERRED) {
4905            Log.v(TAG, "setLastChosenActivity intent=" + intent
4906                + " resolvedType=" + resolvedType
4907                + " flags=" + flags
4908                + " filter=" + filter
4909                + " match=" + match
4910                + " activity=" + activity);
4911            filter.dump(new PrintStreamPrinter(System.out), "    ");
4912        }
4913        intent.setComponent(null);
4914        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4915                userId);
4916        // Find any earlier preferred or last chosen entries and nuke them
4917        findPreferredActivity(intent, resolvedType,
4918                flags, query, 0, false, true, false, userId);
4919        // Add the new activity as the last chosen for this filter
4920        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4921                "Setting last chosen");
4922    }
4923
4924    @Override
4925    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4926        final int userId = UserHandle.getCallingUserId();
4927        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4928        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4929                userId);
4930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4931                false, false, false, userId);
4932    }
4933
4934
4935    private boolean isEphemeralAllowed(
4936            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4937        // Short circuit and return early if possible.
4938        if (DISABLE_EPHEMERAL_APPS) {
4939            return false;
4940        }
4941        final int callingUser = UserHandle.getCallingUserId();
4942        if (callingUser != UserHandle.USER_SYSTEM) {
4943            return false;
4944        }
4945        if (mEphemeralResolverConnection == null) {
4946            return false;
4947        }
4948        if (intent.getComponent() != null) {
4949            return false;
4950        }
4951        if (intent.getPackage() != null) {
4952            return false;
4953        }
4954        final boolean isWebUri = hasWebURI(intent);
4955        if (!isWebUri) {
4956            return false;
4957        }
4958        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4959        synchronized (mPackages) {
4960            final int count = resolvedActivites.size();
4961            for (int n = 0; n < count; n++) {
4962                ResolveInfo info = resolvedActivites.get(n);
4963                String packageName = info.activityInfo.packageName;
4964                PackageSetting ps = mSettings.mPackages.get(packageName);
4965                if (ps != null) {
4966                    // Try to get the status from User settings first
4967                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4968                    int status = (int) (packedStatus >> 32);
4969                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4970                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4971                        if (DEBUG_EPHEMERAL) {
4972                            Slog.v(TAG, "DENY ephemeral apps;"
4973                                + " pkg: " + packageName + ", status: " + status);
4974                        }
4975                        return false;
4976                    }
4977                }
4978            }
4979        }
4980        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4981        return true;
4982    }
4983
4984    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4985            int userId) {
4986        MessageDigest digest = null;
4987        try {
4988            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4989        } catch (NoSuchAlgorithmException e) {
4990            // If we can't create a digest, ignore ephemeral apps.
4991            return null;
4992        }
4993
4994        final byte[] hostBytes = intent.getData().getHost().getBytes();
4995        final byte[] digestBytes = digest.digest(hostBytes);
4996        int shaPrefix =
4997                digestBytes[0] << 24
4998                | digestBytes[1] << 16
4999                | digestBytes[2] << 8
5000                | digestBytes[3] << 0;
5001        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5002                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5003        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5004            // No hash prefix match; there are no ephemeral apps for this domain.
5005            return null;
5006        }
5007        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5008            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5009            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5010                continue;
5011            }
5012            final List<IntentFilter> filters = ephemeralApplication.getFilters();
5013            // No filters; this should never happen.
5014            if (filters.isEmpty()) {
5015                continue;
5016            }
5017            // We have a domain match; resolve the filters to see if anything matches.
5018            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5019            for (int j = filters.size() - 1; j >= 0; --j) {
5020                final EphemeralResolveIntentInfo intentInfo =
5021                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5022                ephemeralResolver.addFilter(intentInfo);
5023            }
5024            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5025                    intent, resolvedType, false /*defaultOnly*/, userId);
5026            if (!matchedResolveInfoList.isEmpty()) {
5027                return matchedResolveInfoList.get(0);
5028            }
5029        }
5030        // Hash or filter mis-match; no ephemeral apps for this domain.
5031        return null;
5032    }
5033
5034    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5035            int flags, List<ResolveInfo> query, int userId) {
5036        if (query != null) {
5037            final int N = query.size();
5038            if (N == 1) {
5039                return query.get(0);
5040            } else if (N > 1) {
5041                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5042                // If there is more than one activity with the same priority,
5043                // then let the user decide between them.
5044                ResolveInfo r0 = query.get(0);
5045                ResolveInfo r1 = query.get(1);
5046                if (DEBUG_INTENT_MATCHING || debug) {
5047                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5048                            + r1.activityInfo.name + "=" + r1.priority);
5049                }
5050                // If the first activity has a higher priority, or a different
5051                // default, then it is always desirable to pick it.
5052                if (r0.priority != r1.priority
5053                        || r0.preferredOrder != r1.preferredOrder
5054                        || r0.isDefault != r1.isDefault) {
5055                    return query.get(0);
5056                }
5057                // If we have saved a preference for a preferred activity for
5058                // this Intent, use that.
5059                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5060                        flags, query, r0.priority, true, false, debug, userId);
5061                if (ri != null) {
5062                    return ri;
5063                }
5064                ri = new ResolveInfo(mResolveInfo);
5065                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5066                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5067                // If all of the options come from the same package, show the application's
5068                // label and icon instead of the generic resolver's.
5069                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5070                // and then throw away the ResolveInfo itself, meaning that the caller loses
5071                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5072                // a fallback for this case; we only set the target package's resources on
5073                // the ResolveInfo, not the ActivityInfo.
5074                final String intentPackage = intent.getPackage();
5075                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5076                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5077                    ri.resolvePackageName = intentPackage;
5078                    if (userNeedsBadging(userId)) {
5079                        ri.noResourceId = true;
5080                    } else {
5081                        ri.icon = appi.icon;
5082                    }
5083                    ri.iconResourceId = appi.icon;
5084                    ri.labelRes = appi.labelRes;
5085                }
5086                ri.activityInfo.applicationInfo = new ApplicationInfo(
5087                        ri.activityInfo.applicationInfo);
5088                if (userId != 0) {
5089                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5090                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5091                }
5092                // Make sure that the resolver is displayable in car mode
5093                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5094                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5095                return ri;
5096            }
5097        }
5098        return null;
5099    }
5100
5101    /**
5102     * Return true if the given list is not empty and all of its contents have
5103     * an activityInfo with the given package name.
5104     */
5105    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5106        if (ArrayUtils.isEmpty(list)) {
5107            return false;
5108        }
5109        for (int i = 0, N = list.size(); i < N; i++) {
5110            final ResolveInfo ri = list.get(i);
5111            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5112            if (ai == null || !packageName.equals(ai.packageName)) {
5113                return false;
5114            }
5115        }
5116        return true;
5117    }
5118
5119    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5120            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5121        final int N = query.size();
5122        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5123                .get(userId);
5124        // Get the list of persistent preferred activities that handle the intent
5125        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5126        List<PersistentPreferredActivity> pprefs = ppir != null
5127                ? ppir.queryIntent(intent, resolvedType,
5128                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5129                : null;
5130        if (pprefs != null && pprefs.size() > 0) {
5131            final int M = pprefs.size();
5132            for (int i=0; i<M; i++) {
5133                final PersistentPreferredActivity ppa = pprefs.get(i);
5134                if (DEBUG_PREFERRED || debug) {
5135                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5136                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5137                            + "\n  component=" + ppa.mComponent);
5138                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5139                }
5140                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5141                        flags | MATCH_DISABLED_COMPONENTS, userId);
5142                if (DEBUG_PREFERRED || debug) {
5143                    Slog.v(TAG, "Found persistent preferred activity:");
5144                    if (ai != null) {
5145                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5146                    } else {
5147                        Slog.v(TAG, "  null");
5148                    }
5149                }
5150                if (ai == null) {
5151                    // This previously registered persistent preferred activity
5152                    // component is no longer known. Ignore it and do NOT remove it.
5153                    continue;
5154                }
5155                for (int j=0; j<N; j++) {
5156                    final ResolveInfo ri = query.get(j);
5157                    if (!ri.activityInfo.applicationInfo.packageName
5158                            .equals(ai.applicationInfo.packageName)) {
5159                        continue;
5160                    }
5161                    if (!ri.activityInfo.name.equals(ai.name)) {
5162                        continue;
5163                    }
5164                    //  Found a persistent preference that can handle the intent.
5165                    if (DEBUG_PREFERRED || debug) {
5166                        Slog.v(TAG, "Returning persistent preferred activity: " +
5167                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5168                    }
5169                    return ri;
5170                }
5171            }
5172        }
5173        return null;
5174    }
5175
5176    // TODO: handle preferred activities missing while user has amnesia
5177    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5178            List<ResolveInfo> query, int priority, boolean always,
5179            boolean removeMatches, boolean debug, int userId) {
5180        if (!sUserManager.exists(userId)) return null;
5181        flags = updateFlagsForResolve(flags, userId, intent);
5182        // writer
5183        synchronized (mPackages) {
5184            if (intent.getSelector() != null) {
5185                intent = intent.getSelector();
5186            }
5187            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5188
5189            // Try to find a matching persistent preferred activity.
5190            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5191                    debug, userId);
5192
5193            // If a persistent preferred activity matched, use it.
5194            if (pri != null) {
5195                return pri;
5196            }
5197
5198            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5199            // Get the list of preferred activities that handle the intent
5200            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5201            List<PreferredActivity> prefs = pir != null
5202                    ? pir.queryIntent(intent, resolvedType,
5203                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5204                    : null;
5205            if (prefs != null && prefs.size() > 0) {
5206                boolean changed = false;
5207                try {
5208                    // First figure out how good the original match set is.
5209                    // We will only allow preferred activities that came
5210                    // from the same match quality.
5211                    int match = 0;
5212
5213                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5214
5215                    final int N = query.size();
5216                    for (int j=0; j<N; j++) {
5217                        final ResolveInfo ri = query.get(j);
5218                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5219                                + ": 0x" + Integer.toHexString(match));
5220                        if (ri.match > match) {
5221                            match = ri.match;
5222                        }
5223                    }
5224
5225                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5226                            + Integer.toHexString(match));
5227
5228                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5229                    final int M = prefs.size();
5230                    for (int i=0; i<M; i++) {
5231                        final PreferredActivity pa = prefs.get(i);
5232                        if (DEBUG_PREFERRED || debug) {
5233                            Slog.v(TAG, "Checking PreferredActivity ds="
5234                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5235                                    + "\n  component=" + pa.mPref.mComponent);
5236                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5237                        }
5238                        if (pa.mPref.mMatch != match) {
5239                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5240                                    + Integer.toHexString(pa.mPref.mMatch));
5241                            continue;
5242                        }
5243                        // If it's not an "always" type preferred activity and that's what we're
5244                        // looking for, skip it.
5245                        if (always && !pa.mPref.mAlways) {
5246                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5247                            continue;
5248                        }
5249                        final ActivityInfo ai = getActivityInfo(
5250                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5251                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5252                                userId);
5253                        if (DEBUG_PREFERRED || debug) {
5254                            Slog.v(TAG, "Found preferred activity:");
5255                            if (ai != null) {
5256                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5257                            } else {
5258                                Slog.v(TAG, "  null");
5259                            }
5260                        }
5261                        if (ai == null) {
5262                            // This previously registered preferred activity
5263                            // component is no longer known.  Most likely an update
5264                            // to the app was installed and in the new version this
5265                            // component no longer exists.  Clean it up by removing
5266                            // it from the preferred activities list, and skip it.
5267                            Slog.w(TAG, "Removing dangling preferred activity: "
5268                                    + pa.mPref.mComponent);
5269                            pir.removeFilter(pa);
5270                            changed = true;
5271                            continue;
5272                        }
5273                        for (int j=0; j<N; j++) {
5274                            final ResolveInfo ri = query.get(j);
5275                            if (!ri.activityInfo.applicationInfo.packageName
5276                                    .equals(ai.applicationInfo.packageName)) {
5277                                continue;
5278                            }
5279                            if (!ri.activityInfo.name.equals(ai.name)) {
5280                                continue;
5281                            }
5282
5283                            if (removeMatches) {
5284                                pir.removeFilter(pa);
5285                                changed = true;
5286                                if (DEBUG_PREFERRED) {
5287                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5288                                }
5289                                break;
5290                            }
5291
5292                            // Okay we found a previously set preferred or last chosen app.
5293                            // If the result set is different from when this
5294                            // was created, we need to clear it and re-ask the
5295                            // user their preference, if we're looking for an "always" type entry.
5296                            if (always && !pa.mPref.sameSet(query)) {
5297                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5298                                        + intent + " type " + resolvedType);
5299                                if (DEBUG_PREFERRED) {
5300                                    Slog.v(TAG, "Removing preferred activity since set changed "
5301                                            + pa.mPref.mComponent);
5302                                }
5303                                pir.removeFilter(pa);
5304                                // Re-add the filter as a "last chosen" entry (!always)
5305                                PreferredActivity lastChosen = new PreferredActivity(
5306                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5307                                pir.addFilter(lastChosen);
5308                                changed = true;
5309                                return null;
5310                            }
5311
5312                            // Yay! Either the set matched or we're looking for the last chosen
5313                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5314                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5315                            return ri;
5316                        }
5317                    }
5318                } finally {
5319                    if (changed) {
5320                        if (DEBUG_PREFERRED) {
5321                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5322                        }
5323                        scheduleWritePackageRestrictionsLocked(userId);
5324                    }
5325                }
5326            }
5327        }
5328        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5329        return null;
5330    }
5331
5332    /*
5333     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5334     */
5335    @Override
5336    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5337            int targetUserId) {
5338        mContext.enforceCallingOrSelfPermission(
5339                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5340        List<CrossProfileIntentFilter> matches =
5341                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5342        if (matches != null) {
5343            int size = matches.size();
5344            for (int i = 0; i < size; i++) {
5345                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5346            }
5347        }
5348        if (hasWebURI(intent)) {
5349            // cross-profile app linking works only towards the parent.
5350            final UserInfo parent = getProfileParent(sourceUserId);
5351            synchronized(mPackages) {
5352                int flags = updateFlagsForResolve(0, parent.id, intent);
5353                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5354                        intent, resolvedType, flags, sourceUserId, parent.id);
5355                return xpDomainInfo != null;
5356            }
5357        }
5358        return false;
5359    }
5360
5361    private UserInfo getProfileParent(int userId) {
5362        final long identity = Binder.clearCallingIdentity();
5363        try {
5364            return sUserManager.getProfileParent(userId);
5365        } finally {
5366            Binder.restoreCallingIdentity(identity);
5367        }
5368    }
5369
5370    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5371            String resolvedType, int userId) {
5372        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5373        if (resolver != null) {
5374            return resolver.queryIntent(intent, resolvedType, false, userId);
5375        }
5376        return null;
5377    }
5378
5379    @Override
5380    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5381            String resolvedType, int flags, int userId) {
5382        try {
5383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5384
5385            return new ParceledListSlice<>(
5386                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5387        } finally {
5388            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5389        }
5390    }
5391
5392    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5393            String resolvedType, int flags, int userId) {
5394        if (!sUserManager.exists(userId)) return Collections.emptyList();
5395        flags = updateFlagsForResolve(flags, userId, intent);
5396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5397                false /* requireFullPermission */, false /* checkShell */,
5398                "query intent activities");
5399        ComponentName comp = intent.getComponent();
5400        if (comp == null) {
5401            if (intent.getSelector() != null) {
5402                intent = intent.getSelector();
5403                comp = intent.getComponent();
5404            }
5405        }
5406
5407        if (comp != null) {
5408            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5409            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5410            if (ai != null) {
5411                final ResolveInfo ri = new ResolveInfo();
5412                ri.activityInfo = ai;
5413                list.add(ri);
5414            }
5415            return list;
5416        }
5417
5418        // reader
5419        synchronized (mPackages) {
5420            final String pkgName = intent.getPackage();
5421            if (pkgName == null) {
5422                List<CrossProfileIntentFilter> matchingFilters =
5423                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5424                // Check for results that need to skip the current profile.
5425                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5426                        resolvedType, flags, userId);
5427                if (xpResolveInfo != null) {
5428                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5429                    result.add(xpResolveInfo);
5430                    return filterIfNotSystemUser(result, userId);
5431                }
5432
5433                // Check for results in the current profile.
5434                List<ResolveInfo> result = mActivities.queryIntent(
5435                        intent, resolvedType, flags, userId);
5436                result = filterIfNotSystemUser(result, userId);
5437
5438                // Check for cross profile results.
5439                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5440                xpResolveInfo = queryCrossProfileIntents(
5441                        matchingFilters, intent, resolvedType, flags, userId,
5442                        hasNonNegativePriorityResult);
5443                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5444                    boolean isVisibleToUser = filterIfNotSystemUser(
5445                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5446                    if (isVisibleToUser) {
5447                        result.add(xpResolveInfo);
5448                        Collections.sort(result, mResolvePrioritySorter);
5449                    }
5450                }
5451                if (hasWebURI(intent)) {
5452                    CrossProfileDomainInfo xpDomainInfo = null;
5453                    final UserInfo parent = getProfileParent(userId);
5454                    if (parent != null) {
5455                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5456                                flags, userId, parent.id);
5457                    }
5458                    if (xpDomainInfo != null) {
5459                        if (xpResolveInfo != null) {
5460                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5461                            // in the result.
5462                            result.remove(xpResolveInfo);
5463                        }
5464                        if (result.size() == 0) {
5465                            result.add(xpDomainInfo.resolveInfo);
5466                            return result;
5467                        }
5468                    } else if (result.size() <= 1) {
5469                        return result;
5470                    }
5471                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5472                            xpDomainInfo, userId);
5473                    Collections.sort(result, mResolvePrioritySorter);
5474                }
5475                return result;
5476            }
5477            final PackageParser.Package pkg = mPackages.get(pkgName);
5478            if (pkg != null) {
5479                return filterIfNotSystemUser(
5480                        mActivities.queryIntentForPackage(
5481                                intent, resolvedType, flags, pkg.activities, userId),
5482                        userId);
5483            }
5484            return new ArrayList<ResolveInfo>();
5485        }
5486    }
5487
5488    private static class CrossProfileDomainInfo {
5489        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5490        ResolveInfo resolveInfo;
5491        /* Best domain verification status of the activities found in the other profile */
5492        int bestDomainVerificationStatus;
5493    }
5494
5495    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5496            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5497        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5498                sourceUserId)) {
5499            return null;
5500        }
5501        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5502                resolvedType, flags, parentUserId);
5503
5504        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5505            return null;
5506        }
5507        CrossProfileDomainInfo result = null;
5508        int size = resultTargetUser.size();
5509        for (int i = 0; i < size; i++) {
5510            ResolveInfo riTargetUser = resultTargetUser.get(i);
5511            // Intent filter verification is only for filters that specify a host. So don't return
5512            // those that handle all web uris.
5513            if (riTargetUser.handleAllWebDataURI) {
5514                continue;
5515            }
5516            String packageName = riTargetUser.activityInfo.packageName;
5517            PackageSetting ps = mSettings.mPackages.get(packageName);
5518            if (ps == null) {
5519                continue;
5520            }
5521            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5522            int status = (int)(verificationState >> 32);
5523            if (result == null) {
5524                result = new CrossProfileDomainInfo();
5525                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5526                        sourceUserId, parentUserId);
5527                result.bestDomainVerificationStatus = status;
5528            } else {
5529                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5530                        result.bestDomainVerificationStatus);
5531            }
5532        }
5533        // Don't consider matches with status NEVER across profiles.
5534        if (result != null && result.bestDomainVerificationStatus
5535                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5536            return null;
5537        }
5538        return result;
5539    }
5540
5541    /**
5542     * Verification statuses are ordered from the worse to the best, except for
5543     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5544     */
5545    private int bestDomainVerificationStatus(int status1, int status2) {
5546        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5547            return status2;
5548        }
5549        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5550            return status1;
5551        }
5552        return (int) MathUtils.max(status1, status2);
5553    }
5554
5555    private boolean isUserEnabled(int userId) {
5556        long callingId = Binder.clearCallingIdentity();
5557        try {
5558            UserInfo userInfo = sUserManager.getUserInfo(userId);
5559            return userInfo != null && userInfo.isEnabled();
5560        } finally {
5561            Binder.restoreCallingIdentity(callingId);
5562        }
5563    }
5564
5565    /**
5566     * Filter out activities with systemUserOnly flag set, when current user is not System.
5567     *
5568     * @return filtered list
5569     */
5570    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5571        if (userId == UserHandle.USER_SYSTEM) {
5572            return resolveInfos;
5573        }
5574        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5575            ResolveInfo info = resolveInfos.get(i);
5576            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5577                resolveInfos.remove(i);
5578            }
5579        }
5580        return resolveInfos;
5581    }
5582
5583    /**
5584     * @param resolveInfos list of resolve infos in descending priority order
5585     * @return if the list contains a resolve info with non-negative priority
5586     */
5587    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5588        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5589    }
5590
5591    private static boolean hasWebURI(Intent intent) {
5592        if (intent.getData() == null) {
5593            return false;
5594        }
5595        final String scheme = intent.getScheme();
5596        if (TextUtils.isEmpty(scheme)) {
5597            return false;
5598        }
5599        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5600    }
5601
5602    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5603            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5604            int userId) {
5605        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5606
5607        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5608            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5609                    candidates.size());
5610        }
5611
5612        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5613        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5614        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5615        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5616        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5617        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5618
5619        synchronized (mPackages) {
5620            final int count = candidates.size();
5621            // First, try to use linked apps. Partition the candidates into four lists:
5622            // one for the final results, one for the "do not use ever", one for "undefined status"
5623            // and finally one for "browser app type".
5624            for (int n=0; n<count; n++) {
5625                ResolveInfo info = candidates.get(n);
5626                String packageName = info.activityInfo.packageName;
5627                PackageSetting ps = mSettings.mPackages.get(packageName);
5628                if (ps != null) {
5629                    // Add to the special match all list (Browser use case)
5630                    if (info.handleAllWebDataURI) {
5631                        matchAllList.add(info);
5632                        continue;
5633                    }
5634                    // Try to get the status from User settings first
5635                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5636                    int status = (int)(packedStatus >> 32);
5637                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5638                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5639                        if (DEBUG_DOMAIN_VERIFICATION) {
5640                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5641                                    + " : linkgen=" + linkGeneration);
5642                        }
5643                        // Use link-enabled generation as preferredOrder, i.e.
5644                        // prefer newly-enabled over earlier-enabled.
5645                        info.preferredOrder = linkGeneration;
5646                        alwaysList.add(info);
5647                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5648                        if (DEBUG_DOMAIN_VERIFICATION) {
5649                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5650                        }
5651                        neverList.add(info);
5652                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5653                        if (DEBUG_DOMAIN_VERIFICATION) {
5654                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5655                        }
5656                        alwaysAskList.add(info);
5657                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5658                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5659                        if (DEBUG_DOMAIN_VERIFICATION) {
5660                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5661                        }
5662                        undefinedList.add(info);
5663                    }
5664                }
5665            }
5666
5667            // We'll want to include browser possibilities in a few cases
5668            boolean includeBrowser = false;
5669
5670            // First try to add the "always" resolution(s) for the current user, if any
5671            if (alwaysList.size() > 0) {
5672                result.addAll(alwaysList);
5673            } else {
5674                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5675                result.addAll(undefinedList);
5676                // Maybe add one for the other profile.
5677                if (xpDomainInfo != null && (
5678                        xpDomainInfo.bestDomainVerificationStatus
5679                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5680                    result.add(xpDomainInfo.resolveInfo);
5681                }
5682                includeBrowser = true;
5683            }
5684
5685            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5686            // If there were 'always' entries their preferred order has been set, so we also
5687            // back that off to make the alternatives equivalent
5688            if (alwaysAskList.size() > 0) {
5689                for (ResolveInfo i : result) {
5690                    i.preferredOrder = 0;
5691                }
5692                result.addAll(alwaysAskList);
5693                includeBrowser = true;
5694            }
5695
5696            if (includeBrowser) {
5697                // Also add browsers (all of them or only the default one)
5698                if (DEBUG_DOMAIN_VERIFICATION) {
5699                    Slog.v(TAG, "   ...including browsers in candidate set");
5700                }
5701                if ((matchFlags & MATCH_ALL) != 0) {
5702                    result.addAll(matchAllList);
5703                } else {
5704                    // Browser/generic handling case.  If there's a default browser, go straight
5705                    // to that (but only if there is no other higher-priority match).
5706                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5707                    int maxMatchPrio = 0;
5708                    ResolveInfo defaultBrowserMatch = null;
5709                    final int numCandidates = matchAllList.size();
5710                    for (int n = 0; n < numCandidates; n++) {
5711                        ResolveInfo info = matchAllList.get(n);
5712                        // track the highest overall match priority...
5713                        if (info.priority > maxMatchPrio) {
5714                            maxMatchPrio = info.priority;
5715                        }
5716                        // ...and the highest-priority default browser match
5717                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5718                            if (defaultBrowserMatch == null
5719                                    || (defaultBrowserMatch.priority < info.priority)) {
5720                                if (debug) {
5721                                    Slog.v(TAG, "Considering default browser match " + info);
5722                                }
5723                                defaultBrowserMatch = info;
5724                            }
5725                        }
5726                    }
5727                    if (defaultBrowserMatch != null
5728                            && defaultBrowserMatch.priority >= maxMatchPrio
5729                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5730                    {
5731                        if (debug) {
5732                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5733                        }
5734                        result.add(defaultBrowserMatch);
5735                    } else {
5736                        result.addAll(matchAllList);
5737                    }
5738                }
5739
5740                // If there is nothing selected, add all candidates and remove the ones that the user
5741                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5742                if (result.size() == 0) {
5743                    result.addAll(candidates);
5744                    result.removeAll(neverList);
5745                }
5746            }
5747        }
5748        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5749            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5750                    result.size());
5751            for (ResolveInfo info : result) {
5752                Slog.v(TAG, "  + " + info.activityInfo);
5753            }
5754        }
5755        return result;
5756    }
5757
5758    // Returns a packed value as a long:
5759    //
5760    // high 'int'-sized word: link status: undefined/ask/never/always.
5761    // low 'int'-sized word: relative priority among 'always' results.
5762    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5763        long result = ps.getDomainVerificationStatusForUser(userId);
5764        // if none available, get the master status
5765        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5766            if (ps.getIntentFilterVerificationInfo() != null) {
5767                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5768            }
5769        }
5770        return result;
5771    }
5772
5773    private ResolveInfo querySkipCurrentProfileIntents(
5774            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5775            int flags, int sourceUserId) {
5776        if (matchingFilters != null) {
5777            int size = matchingFilters.size();
5778            for (int i = 0; i < size; i ++) {
5779                CrossProfileIntentFilter filter = matchingFilters.get(i);
5780                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5781                    // Checking if there are activities in the target user that can handle the
5782                    // intent.
5783                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5784                            resolvedType, flags, sourceUserId);
5785                    if (resolveInfo != null) {
5786                        return resolveInfo;
5787                    }
5788                }
5789            }
5790        }
5791        return null;
5792    }
5793
5794    // Return matching ResolveInfo in target user if any.
5795    private ResolveInfo queryCrossProfileIntents(
5796            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5797            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5798        if (matchingFilters != null) {
5799            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5800            // match the same intent. For performance reasons, it is better not to
5801            // run queryIntent twice for the same userId
5802            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5803            int size = matchingFilters.size();
5804            for (int i = 0; i < size; i++) {
5805                CrossProfileIntentFilter filter = matchingFilters.get(i);
5806                int targetUserId = filter.getTargetUserId();
5807                boolean skipCurrentProfile =
5808                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5809                boolean skipCurrentProfileIfNoMatchFound =
5810                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5811                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5812                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5813                    // Checking if there are activities in the target user that can handle the
5814                    // intent.
5815                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5816                            resolvedType, flags, sourceUserId);
5817                    if (resolveInfo != null) return resolveInfo;
5818                    alreadyTriedUserIds.put(targetUserId, true);
5819                }
5820            }
5821        }
5822        return null;
5823    }
5824
5825    /**
5826     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5827     * will forward the intent to the filter's target user.
5828     * Otherwise, returns null.
5829     */
5830    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5831            String resolvedType, int flags, int sourceUserId) {
5832        int targetUserId = filter.getTargetUserId();
5833        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5834                resolvedType, flags, targetUserId);
5835        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5836            // If all the matches in the target profile are suspended, return null.
5837            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5838                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5839                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5840                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5841                            targetUserId);
5842                }
5843            }
5844        }
5845        return null;
5846    }
5847
5848    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5849            int sourceUserId, int targetUserId) {
5850        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5851        long ident = Binder.clearCallingIdentity();
5852        boolean targetIsProfile;
5853        try {
5854            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5855        } finally {
5856            Binder.restoreCallingIdentity(ident);
5857        }
5858        String className;
5859        if (targetIsProfile) {
5860            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5861        } else {
5862            className = FORWARD_INTENT_TO_PARENT;
5863        }
5864        ComponentName forwardingActivityComponentName = new ComponentName(
5865                mAndroidApplication.packageName, className);
5866        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5867                sourceUserId);
5868        if (!targetIsProfile) {
5869            forwardingActivityInfo.showUserIcon = targetUserId;
5870            forwardingResolveInfo.noResourceId = true;
5871        }
5872        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5873        forwardingResolveInfo.priority = 0;
5874        forwardingResolveInfo.preferredOrder = 0;
5875        forwardingResolveInfo.match = 0;
5876        forwardingResolveInfo.isDefault = true;
5877        forwardingResolveInfo.filter = filter;
5878        forwardingResolveInfo.targetUserId = targetUserId;
5879        return forwardingResolveInfo;
5880    }
5881
5882    @Override
5883    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5884            Intent[] specifics, String[] specificTypes, Intent intent,
5885            String resolvedType, int flags, int userId) {
5886        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5887                specificTypes, intent, resolvedType, flags, userId));
5888    }
5889
5890    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5891            Intent[] specifics, String[] specificTypes, Intent intent,
5892            String resolvedType, int flags, int userId) {
5893        if (!sUserManager.exists(userId)) return Collections.emptyList();
5894        flags = updateFlagsForResolve(flags, userId, intent);
5895        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5896                false /* requireFullPermission */, false /* checkShell */,
5897                "query intent activity options");
5898        final String resultsAction = intent.getAction();
5899
5900        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5901                | PackageManager.GET_RESOLVED_FILTER, userId);
5902
5903        if (DEBUG_INTENT_MATCHING) {
5904            Log.v(TAG, "Query " + intent + ": " + results);
5905        }
5906
5907        int specificsPos = 0;
5908        int N;
5909
5910        // todo: note that the algorithm used here is O(N^2).  This
5911        // isn't a problem in our current environment, but if we start running
5912        // into situations where we have more than 5 or 10 matches then this
5913        // should probably be changed to something smarter...
5914
5915        // First we go through and resolve each of the specific items
5916        // that were supplied, taking care of removing any corresponding
5917        // duplicate items in the generic resolve list.
5918        if (specifics != null) {
5919            for (int i=0; i<specifics.length; i++) {
5920                final Intent sintent = specifics[i];
5921                if (sintent == null) {
5922                    continue;
5923                }
5924
5925                if (DEBUG_INTENT_MATCHING) {
5926                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5927                }
5928
5929                String action = sintent.getAction();
5930                if (resultsAction != null && resultsAction.equals(action)) {
5931                    // If this action was explicitly requested, then don't
5932                    // remove things that have it.
5933                    action = null;
5934                }
5935
5936                ResolveInfo ri = null;
5937                ActivityInfo ai = null;
5938
5939                ComponentName comp = sintent.getComponent();
5940                if (comp == null) {
5941                    ri = resolveIntent(
5942                        sintent,
5943                        specificTypes != null ? specificTypes[i] : null,
5944                            flags, userId);
5945                    if (ri == null) {
5946                        continue;
5947                    }
5948                    if (ri == mResolveInfo) {
5949                        // ACK!  Must do something better with this.
5950                    }
5951                    ai = ri.activityInfo;
5952                    comp = new ComponentName(ai.applicationInfo.packageName,
5953                            ai.name);
5954                } else {
5955                    ai = getActivityInfo(comp, flags, userId);
5956                    if (ai == null) {
5957                        continue;
5958                    }
5959                }
5960
5961                // Look for any generic query activities that are duplicates
5962                // of this specific one, and remove them from the results.
5963                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5964                N = results.size();
5965                int j;
5966                for (j=specificsPos; j<N; j++) {
5967                    ResolveInfo sri = results.get(j);
5968                    if ((sri.activityInfo.name.equals(comp.getClassName())
5969                            && sri.activityInfo.applicationInfo.packageName.equals(
5970                                    comp.getPackageName()))
5971                        || (action != null && sri.filter.matchAction(action))) {
5972                        results.remove(j);
5973                        if (DEBUG_INTENT_MATCHING) Log.v(
5974                            TAG, "Removing duplicate item from " + j
5975                            + " due to specific " + specificsPos);
5976                        if (ri == null) {
5977                            ri = sri;
5978                        }
5979                        j--;
5980                        N--;
5981                    }
5982                }
5983
5984                // Add this specific item to its proper place.
5985                if (ri == null) {
5986                    ri = new ResolveInfo();
5987                    ri.activityInfo = ai;
5988                }
5989                results.add(specificsPos, ri);
5990                ri.specificIndex = i;
5991                specificsPos++;
5992            }
5993        }
5994
5995        // Now we go through the remaining generic results and remove any
5996        // duplicate actions that are found here.
5997        N = results.size();
5998        for (int i=specificsPos; i<N-1; i++) {
5999            final ResolveInfo rii = results.get(i);
6000            if (rii.filter == null) {
6001                continue;
6002            }
6003
6004            // Iterate over all of the actions of this result's intent
6005            // filter...  typically this should be just one.
6006            final Iterator<String> it = rii.filter.actionsIterator();
6007            if (it == null) {
6008                continue;
6009            }
6010            while (it.hasNext()) {
6011                final String action = it.next();
6012                if (resultsAction != null && resultsAction.equals(action)) {
6013                    // If this action was explicitly requested, then don't
6014                    // remove things that have it.
6015                    continue;
6016                }
6017                for (int j=i+1; j<N; j++) {
6018                    final ResolveInfo rij = results.get(j);
6019                    if (rij.filter != null && rij.filter.hasAction(action)) {
6020                        results.remove(j);
6021                        if (DEBUG_INTENT_MATCHING) Log.v(
6022                            TAG, "Removing duplicate item from " + j
6023                            + " due to action " + action + " at " + i);
6024                        j--;
6025                        N--;
6026                    }
6027                }
6028            }
6029
6030            // If the caller didn't request filter information, drop it now
6031            // so we don't have to marshall/unmarshall it.
6032            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6033                rii.filter = null;
6034            }
6035        }
6036
6037        // Filter out the caller activity if so requested.
6038        if (caller != null) {
6039            N = results.size();
6040            for (int i=0; i<N; i++) {
6041                ActivityInfo ainfo = results.get(i).activityInfo;
6042                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6043                        && caller.getClassName().equals(ainfo.name)) {
6044                    results.remove(i);
6045                    break;
6046                }
6047            }
6048        }
6049
6050        // If the caller didn't request filter information,
6051        // drop them now so we don't have to
6052        // marshall/unmarshall it.
6053        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6054            N = results.size();
6055            for (int i=0; i<N; i++) {
6056                results.get(i).filter = null;
6057            }
6058        }
6059
6060        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6061        return results;
6062    }
6063
6064    @Override
6065    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6066            String resolvedType, int flags, int userId) {
6067        return new ParceledListSlice<>(
6068                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6069    }
6070
6071    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6072            String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return Collections.emptyList();
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        ComponentName comp = intent.getComponent();
6076        if (comp == null) {
6077            if (intent.getSelector() != null) {
6078                intent = intent.getSelector();
6079                comp = intent.getComponent();
6080            }
6081        }
6082        if (comp != null) {
6083            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6084            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6085            if (ai != null) {
6086                ResolveInfo ri = new ResolveInfo();
6087                ri.activityInfo = ai;
6088                list.add(ri);
6089            }
6090            return list;
6091        }
6092
6093        // reader
6094        synchronized (mPackages) {
6095            String pkgName = intent.getPackage();
6096            if (pkgName == null) {
6097                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6098            }
6099            final PackageParser.Package pkg = mPackages.get(pkgName);
6100            if (pkg != null) {
6101                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6102                        userId);
6103            }
6104            return Collections.emptyList();
6105        }
6106    }
6107
6108    @Override
6109    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6110        if (!sUserManager.exists(userId)) return null;
6111        flags = updateFlagsForResolve(flags, userId, intent);
6112        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6113        if (query != null) {
6114            if (query.size() >= 1) {
6115                // If there is more than one service with the same priority,
6116                // just arbitrarily pick the first one.
6117                return query.get(0);
6118            }
6119        }
6120        return null;
6121    }
6122
6123    @Override
6124    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6125            String resolvedType, int flags, int userId) {
6126        return new ParceledListSlice<>(
6127                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6128    }
6129
6130    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6131            String resolvedType, int flags, int userId) {
6132        if (!sUserManager.exists(userId)) return Collections.emptyList();
6133        flags = updateFlagsForResolve(flags, userId, intent);
6134        ComponentName comp = intent.getComponent();
6135        if (comp == null) {
6136            if (intent.getSelector() != null) {
6137                intent = intent.getSelector();
6138                comp = intent.getComponent();
6139            }
6140        }
6141        if (comp != null) {
6142            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6143            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6144            if (si != null) {
6145                final ResolveInfo ri = new ResolveInfo();
6146                ri.serviceInfo = si;
6147                list.add(ri);
6148            }
6149            return list;
6150        }
6151
6152        // reader
6153        synchronized (mPackages) {
6154            String pkgName = intent.getPackage();
6155            if (pkgName == null) {
6156                return mServices.queryIntent(intent, resolvedType, flags, userId);
6157            }
6158            final PackageParser.Package pkg = mPackages.get(pkgName);
6159            if (pkg != null) {
6160                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6161                        userId);
6162            }
6163            return Collections.emptyList();
6164        }
6165    }
6166
6167    @Override
6168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6169            String resolvedType, int flags, int userId) {
6170        return new ParceledListSlice<>(
6171                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6172    }
6173
6174    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6175            Intent intent, String resolvedType, int flags, int userId) {
6176        if (!sUserManager.exists(userId)) return Collections.emptyList();
6177        flags = updateFlagsForResolve(flags, userId, intent);
6178        ComponentName comp = intent.getComponent();
6179        if (comp == null) {
6180            if (intent.getSelector() != null) {
6181                intent = intent.getSelector();
6182                comp = intent.getComponent();
6183            }
6184        }
6185        if (comp != null) {
6186            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6187            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6188            if (pi != null) {
6189                final ResolveInfo ri = new ResolveInfo();
6190                ri.providerInfo = pi;
6191                list.add(ri);
6192            }
6193            return list;
6194        }
6195
6196        // reader
6197        synchronized (mPackages) {
6198            String pkgName = intent.getPackage();
6199            if (pkgName == null) {
6200                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6201            }
6202            final PackageParser.Package pkg = mPackages.get(pkgName);
6203            if (pkg != null) {
6204                return mProviders.queryIntentForPackage(
6205                        intent, resolvedType, flags, pkg.providers, userId);
6206            }
6207            return Collections.emptyList();
6208        }
6209    }
6210
6211    @Override
6212    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6213        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6214        flags = updateFlagsForPackage(flags, userId, null);
6215        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6217                true /* requireFullPermission */, false /* checkShell */,
6218                "get installed packages");
6219
6220        // writer
6221        synchronized (mPackages) {
6222            ArrayList<PackageInfo> list;
6223            if (listUninstalled) {
6224                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6225                for (PackageSetting ps : mSettings.mPackages.values()) {
6226                    final PackageInfo pi;
6227                    if (ps.pkg != null) {
6228                        pi = generatePackageInfo(ps, flags, userId);
6229                    } else {
6230                        pi = generatePackageInfo(ps, flags, userId);
6231                    }
6232                    if (pi != null) {
6233                        list.add(pi);
6234                    }
6235                }
6236            } else {
6237                list = new ArrayList<PackageInfo>(mPackages.size());
6238                for (PackageParser.Package p : mPackages.values()) {
6239                    final PackageInfo pi =
6240                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6241                    if (pi != null) {
6242                        list.add(pi);
6243                    }
6244                }
6245            }
6246
6247            return new ParceledListSlice<PackageInfo>(list);
6248        }
6249    }
6250
6251    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6252            String[] permissions, boolean[] tmp, int flags, int userId) {
6253        int numMatch = 0;
6254        final PermissionsState permissionsState = ps.getPermissionsState();
6255        for (int i=0; i<permissions.length; i++) {
6256            final String permission = permissions[i];
6257            if (permissionsState.hasPermission(permission, userId)) {
6258                tmp[i] = true;
6259                numMatch++;
6260            } else {
6261                tmp[i] = false;
6262            }
6263        }
6264        if (numMatch == 0) {
6265            return;
6266        }
6267        final PackageInfo pi;
6268        if (ps.pkg != null) {
6269            pi = generatePackageInfo(ps, flags, userId);
6270        } else {
6271            pi = generatePackageInfo(ps, flags, userId);
6272        }
6273        // The above might return null in cases of uninstalled apps or install-state
6274        // skew across users/profiles.
6275        if (pi != null) {
6276            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6277                if (numMatch == permissions.length) {
6278                    pi.requestedPermissions = permissions;
6279                } else {
6280                    pi.requestedPermissions = new String[numMatch];
6281                    numMatch = 0;
6282                    for (int i=0; i<permissions.length; i++) {
6283                        if (tmp[i]) {
6284                            pi.requestedPermissions[numMatch] = permissions[i];
6285                            numMatch++;
6286                        }
6287                    }
6288                }
6289            }
6290            list.add(pi);
6291        }
6292    }
6293
6294    @Override
6295    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6296            String[] permissions, int flags, int userId) {
6297        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6298        flags = updateFlagsForPackage(flags, userId, permissions);
6299        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6300
6301        // writer
6302        synchronized (mPackages) {
6303            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6304            boolean[] tmpBools = new boolean[permissions.length];
6305            if (listUninstalled) {
6306                for (PackageSetting ps : mSettings.mPackages.values()) {
6307                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6308                }
6309            } else {
6310                for (PackageParser.Package pkg : mPackages.values()) {
6311                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6312                    if (ps != null) {
6313                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6314                                userId);
6315                    }
6316                }
6317            }
6318
6319            return new ParceledListSlice<PackageInfo>(list);
6320        }
6321    }
6322
6323    @Override
6324    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6325        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6326        flags = updateFlagsForApplication(flags, userId, null);
6327        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6328
6329        // writer
6330        synchronized (mPackages) {
6331            ArrayList<ApplicationInfo> list;
6332            if (listUninstalled) {
6333                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6334                for (PackageSetting ps : mSettings.mPackages.values()) {
6335                    ApplicationInfo ai;
6336                    if (ps.pkg != null) {
6337                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6338                                ps.readUserState(userId), userId);
6339                    } else {
6340                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6341                    }
6342                    if (ai != null) {
6343                        list.add(ai);
6344                    }
6345                }
6346            } else {
6347                list = new ArrayList<ApplicationInfo>(mPackages.size());
6348                for (PackageParser.Package p : mPackages.values()) {
6349                    if (p.mExtras != null) {
6350                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6351                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6352                        if (ai != null) {
6353                            list.add(ai);
6354                        }
6355                    }
6356                }
6357            }
6358
6359            return new ParceledListSlice<ApplicationInfo>(list);
6360        }
6361    }
6362
6363    @Override
6364    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6365        if (DISABLE_EPHEMERAL_APPS) {
6366            return null;
6367        }
6368
6369        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6370                "getEphemeralApplications");
6371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6372                true /* requireFullPermission */, false /* checkShell */,
6373                "getEphemeralApplications");
6374        synchronized (mPackages) {
6375            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6376                    .getEphemeralApplicationsLPw(userId);
6377            if (ephemeralApps != null) {
6378                return new ParceledListSlice<>(ephemeralApps);
6379            }
6380        }
6381        return null;
6382    }
6383
6384    @Override
6385    public boolean isEphemeralApplication(String packageName, int userId) {
6386        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6387                true /* requireFullPermission */, false /* checkShell */,
6388                "isEphemeral");
6389        if (DISABLE_EPHEMERAL_APPS) {
6390            return false;
6391        }
6392
6393        if (!isCallerSameApp(packageName)) {
6394            return false;
6395        }
6396        synchronized (mPackages) {
6397            PackageParser.Package pkg = mPackages.get(packageName);
6398            if (pkg != null) {
6399                return pkg.applicationInfo.isEphemeralApp();
6400            }
6401        }
6402        return false;
6403    }
6404
6405    @Override
6406    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6407        if (DISABLE_EPHEMERAL_APPS) {
6408            return null;
6409        }
6410
6411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6412                true /* requireFullPermission */, false /* checkShell */,
6413                "getCookie");
6414        if (!isCallerSameApp(packageName)) {
6415            return null;
6416        }
6417        synchronized (mPackages) {
6418            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6419                    packageName, userId);
6420        }
6421    }
6422
6423    @Override
6424    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6425        if (DISABLE_EPHEMERAL_APPS) {
6426            return true;
6427        }
6428
6429        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6430                true /* requireFullPermission */, true /* checkShell */,
6431                "setCookie");
6432        if (!isCallerSameApp(packageName)) {
6433            return false;
6434        }
6435        synchronized (mPackages) {
6436            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6437                    packageName, cookie, userId);
6438        }
6439    }
6440
6441    @Override
6442    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6443        if (DISABLE_EPHEMERAL_APPS) {
6444            return null;
6445        }
6446
6447        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6448                "getEphemeralApplicationIcon");
6449        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6450                true /* requireFullPermission */, false /* checkShell */,
6451                "getEphemeralApplicationIcon");
6452        synchronized (mPackages) {
6453            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6454                    packageName, userId);
6455        }
6456    }
6457
6458    private boolean isCallerSameApp(String packageName) {
6459        PackageParser.Package pkg = mPackages.get(packageName);
6460        return pkg != null
6461                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6462    }
6463
6464    @Override
6465    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6466        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6467    }
6468
6469    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6470        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6471
6472        // reader
6473        synchronized (mPackages) {
6474            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6475            final int userId = UserHandle.getCallingUserId();
6476            while (i.hasNext()) {
6477                final PackageParser.Package p = i.next();
6478                if (p.applicationInfo == null) continue;
6479
6480                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6481                        && !p.applicationInfo.isDirectBootAware();
6482                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6483                        && p.applicationInfo.isDirectBootAware();
6484
6485                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6486                        && (!mSafeMode || isSystemApp(p))
6487                        && (matchesUnaware || matchesAware)) {
6488                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6489                    if (ps != null) {
6490                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6491                                ps.readUserState(userId), userId);
6492                        if (ai != null) {
6493                            finalList.add(ai);
6494                        }
6495                    }
6496                }
6497            }
6498        }
6499
6500        return finalList;
6501    }
6502
6503    @Override
6504    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6505        if (!sUserManager.exists(userId)) return null;
6506        flags = updateFlagsForComponent(flags, userId, name);
6507        // reader
6508        synchronized (mPackages) {
6509            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6510            PackageSetting ps = provider != null
6511                    ? mSettings.mPackages.get(provider.owner.packageName)
6512                    : null;
6513            return ps != null
6514                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6515                    ? PackageParser.generateProviderInfo(provider, flags,
6516                            ps.readUserState(userId), userId)
6517                    : null;
6518        }
6519    }
6520
6521    /**
6522     * @deprecated
6523     */
6524    @Deprecated
6525    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6526        // reader
6527        synchronized (mPackages) {
6528            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6529                    .entrySet().iterator();
6530            final int userId = UserHandle.getCallingUserId();
6531            while (i.hasNext()) {
6532                Map.Entry<String, PackageParser.Provider> entry = i.next();
6533                PackageParser.Provider p = entry.getValue();
6534                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6535
6536                if (ps != null && p.syncable
6537                        && (!mSafeMode || (p.info.applicationInfo.flags
6538                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6539                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6540                            ps.readUserState(userId), userId);
6541                    if (info != null) {
6542                        outNames.add(entry.getKey());
6543                        outInfo.add(info);
6544                    }
6545                }
6546            }
6547        }
6548    }
6549
6550    @Override
6551    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6552            int uid, int flags) {
6553        final int userId = processName != null ? UserHandle.getUserId(uid)
6554                : UserHandle.getCallingUserId();
6555        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6556        flags = updateFlagsForComponent(flags, userId, processName);
6557
6558        ArrayList<ProviderInfo> finalList = null;
6559        // reader
6560        synchronized (mPackages) {
6561            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6562            while (i.hasNext()) {
6563                final PackageParser.Provider p = i.next();
6564                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6565                if (ps != null && p.info.authority != null
6566                        && (processName == null
6567                                || (p.info.processName.equals(processName)
6568                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6569                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6570                    if (finalList == null) {
6571                        finalList = new ArrayList<ProviderInfo>(3);
6572                    }
6573                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6574                            ps.readUserState(userId), userId);
6575                    if (info != null) {
6576                        finalList.add(info);
6577                    }
6578                }
6579            }
6580        }
6581
6582        if (finalList != null) {
6583            Collections.sort(finalList, mProviderInitOrderSorter);
6584            return new ParceledListSlice<ProviderInfo>(finalList);
6585        }
6586
6587        return ParceledListSlice.emptyList();
6588    }
6589
6590    @Override
6591    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6592        // reader
6593        synchronized (mPackages) {
6594            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6595            return PackageParser.generateInstrumentationInfo(i, flags);
6596        }
6597    }
6598
6599    @Override
6600    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6601            String targetPackage, int flags) {
6602        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6603    }
6604
6605    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6606            int flags) {
6607        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6608
6609        // reader
6610        synchronized (mPackages) {
6611            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6612            while (i.hasNext()) {
6613                final PackageParser.Instrumentation p = i.next();
6614                if (targetPackage == null
6615                        || targetPackage.equals(p.info.targetPackage)) {
6616                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6617                            flags);
6618                    if (ii != null) {
6619                        finalList.add(ii);
6620                    }
6621                }
6622            }
6623        }
6624
6625        return finalList;
6626    }
6627
6628    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6629        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6630        if (overlays == null) {
6631            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6632            return;
6633        }
6634        for (PackageParser.Package opkg : overlays.values()) {
6635            // Not much to do if idmap fails: we already logged the error
6636            // and we certainly don't want to abort installation of pkg simply
6637            // because an overlay didn't fit properly. For these reasons,
6638            // ignore the return value of createIdmapForPackagePairLI.
6639            createIdmapForPackagePairLI(pkg, opkg);
6640        }
6641    }
6642
6643    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6644            PackageParser.Package opkg) {
6645        if (!opkg.mTrustedOverlay) {
6646            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6647                    opkg.baseCodePath + ": overlay not trusted");
6648            return false;
6649        }
6650        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6651        if (overlaySet == null) {
6652            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6653                    opkg.baseCodePath + " but target package has no known overlays");
6654            return false;
6655        }
6656        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6657        // TODO: generate idmap for split APKs
6658        try {
6659            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6660        } catch (InstallerException e) {
6661            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6662                    + opkg.baseCodePath);
6663            return false;
6664        }
6665        PackageParser.Package[] overlayArray =
6666            overlaySet.values().toArray(new PackageParser.Package[0]);
6667        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6668            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6669                return p1.mOverlayPriority - p2.mOverlayPriority;
6670            }
6671        };
6672        Arrays.sort(overlayArray, cmp);
6673
6674        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6675        int i = 0;
6676        for (PackageParser.Package p : overlayArray) {
6677            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6678        }
6679        return true;
6680    }
6681
6682    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6684        try {
6685            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689    }
6690
6691    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6692        final File[] files = dir.listFiles();
6693        if (ArrayUtils.isEmpty(files)) {
6694            Log.d(TAG, "No files in app dir " + dir);
6695            return;
6696        }
6697
6698        if (DEBUG_PACKAGE_SCANNING) {
6699            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6700                    + " flags=0x" + Integer.toHexString(parseFlags));
6701        }
6702
6703        for (File file : files) {
6704            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6705                    && !PackageInstallerService.isStageName(file.getName());
6706            if (!isPackage) {
6707                // Ignore entries which are not packages
6708                continue;
6709            }
6710            try {
6711                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6712                        scanFlags, currentTime, null);
6713            } catch (PackageManagerException e) {
6714                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6715
6716                // Delete invalid userdata apps
6717                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6718                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6719                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6720                    removeCodePathLI(file);
6721                }
6722            }
6723        }
6724    }
6725
6726    private static File getSettingsProblemFile() {
6727        File dataDir = Environment.getDataDirectory();
6728        File systemDir = new File(dataDir, "system");
6729        File fname = new File(systemDir, "uiderrors.txt");
6730        return fname;
6731    }
6732
6733    static void reportSettingsProblem(int priority, String msg) {
6734        logCriticalInfo(priority, msg);
6735    }
6736
6737    static void logCriticalInfo(int priority, String msg) {
6738        Slog.println(priority, TAG, msg);
6739        EventLogTags.writePmCriticalInfo(msg);
6740        try {
6741            File fname = getSettingsProblemFile();
6742            FileOutputStream out = new FileOutputStream(fname, true);
6743            PrintWriter pw = new FastPrintWriter(out);
6744            SimpleDateFormat formatter = new SimpleDateFormat();
6745            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6746            pw.println(dateString + ": " + msg);
6747            pw.close();
6748            FileUtils.setPermissions(
6749                    fname.toString(),
6750                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6751                    -1, -1);
6752        } catch (java.io.IOException e) {
6753        }
6754    }
6755
6756    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6757            final int policyFlags) throws PackageManagerException {
6758        if (ps != null
6759                && ps.codePath.equals(srcFile)
6760                && ps.timeStamp == srcFile.lastModified()
6761                && !isCompatSignatureUpdateNeeded(pkg)
6762                && !isRecoverSignatureUpdateNeeded(pkg)) {
6763            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6764            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6765            ArraySet<PublicKey> signingKs;
6766            synchronized (mPackages) {
6767                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6768            }
6769            if (ps.signatures.mSignatures != null
6770                    && ps.signatures.mSignatures.length != 0
6771                    && signingKs != null) {
6772                // Optimization: reuse the existing cached certificates
6773                // if the package appears to be unchanged.
6774                pkg.mSignatures = ps.signatures.mSignatures;
6775                pkg.mSigningKeys = signingKs;
6776                return;
6777            }
6778
6779            Slog.w(TAG, "PackageSetting for " + ps.name
6780                    + " is missing signatures.  Collecting certs again to recover them.");
6781        } else {
6782            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6783        }
6784
6785        try {
6786            PackageParser.collectCertificates(pkg, policyFlags);
6787        } catch (PackageParserException e) {
6788            throw PackageManagerException.from(e);
6789        }
6790    }
6791
6792    /**
6793     *  Traces a package scan.
6794     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6795     */
6796    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6797            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6798        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6799        try {
6800            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6801        } finally {
6802            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6803        }
6804    }
6805
6806    /**
6807     *  Scans a package and returns the newly parsed package.
6808     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6809     */
6810    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6811            long currentTime, UserHandle user) throws PackageManagerException {
6812        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6813        PackageParser pp = new PackageParser();
6814        pp.setSeparateProcesses(mSeparateProcesses);
6815        pp.setOnlyCoreApps(mOnlyCore);
6816        pp.setDisplayMetrics(mMetrics);
6817
6818        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6819            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6820        }
6821
6822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6823        final PackageParser.Package pkg;
6824        try {
6825            pkg = pp.parsePackage(scanFile, parseFlags);
6826        } catch (PackageParserException e) {
6827            throw PackageManagerException.from(e);
6828        } finally {
6829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6830        }
6831
6832        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6833    }
6834
6835    /**
6836     *  Scans a package and returns the newly parsed package.
6837     *  @throws PackageManagerException on a parse error.
6838     */
6839    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6840            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6841            throws PackageManagerException {
6842        // If the package has children and this is the first dive in the function
6843        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6844        // packages (parent and children) would be successfully scanned before the
6845        // actual scan since scanning mutates internal state and we want to atomically
6846        // install the package and its children.
6847        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6848            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6849                scanFlags |= SCAN_CHECK_ONLY;
6850            }
6851        } else {
6852            scanFlags &= ~SCAN_CHECK_ONLY;
6853        }
6854
6855        // Scan the parent
6856        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6857                scanFlags, currentTime, user);
6858
6859        // Scan the children
6860        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6861        for (int i = 0; i < childCount; i++) {
6862            PackageParser.Package childPackage = pkg.childPackages.get(i);
6863            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6864                    currentTime, user);
6865        }
6866
6867
6868        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6869            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6870        }
6871
6872        return scannedPkg;
6873    }
6874
6875    /**
6876     *  Scans a package and returns the newly parsed package.
6877     *  @throws PackageManagerException on a parse error.
6878     */
6879    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6880            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6881            throws PackageManagerException {
6882        PackageSetting ps = null;
6883        PackageSetting updatedPkg;
6884        // reader
6885        synchronized (mPackages) {
6886            // Look to see if we already know about this package.
6887            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6888            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6889                // This package has been renamed to its original name.  Let's
6890                // use that.
6891                ps = mSettings.peekPackageLPr(oldName);
6892            }
6893            // If there was no original package, see one for the real package name.
6894            if (ps == null) {
6895                ps = mSettings.peekPackageLPr(pkg.packageName);
6896            }
6897            // Check to see if this package could be hiding/updating a system
6898            // package.  Must look for it either under the original or real
6899            // package name depending on our state.
6900            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6901            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6902
6903            // If this is a package we don't know about on the system partition, we
6904            // may need to remove disabled child packages on the system partition
6905            // or may need to not add child packages if the parent apk is updated
6906            // on the data partition and no longer defines this child package.
6907            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6908                // If this is a parent package for an updated system app and this system
6909                // app got an OTA update which no longer defines some of the child packages
6910                // we have to prune them from the disabled system packages.
6911                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6912                if (disabledPs != null) {
6913                    final int scannedChildCount = (pkg.childPackages != null)
6914                            ? pkg.childPackages.size() : 0;
6915                    final int disabledChildCount = disabledPs.childPackageNames != null
6916                            ? disabledPs.childPackageNames.size() : 0;
6917                    for (int i = 0; i < disabledChildCount; i++) {
6918                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6919                        boolean disabledPackageAvailable = false;
6920                        for (int j = 0; j < scannedChildCount; j++) {
6921                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6922                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6923                                disabledPackageAvailable = true;
6924                                break;
6925                            }
6926                         }
6927                         if (!disabledPackageAvailable) {
6928                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6929                         }
6930                    }
6931                }
6932            }
6933        }
6934
6935        boolean updatedPkgBetter = false;
6936        // First check if this is a system package that may involve an update
6937        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6938            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6939            // it needs to drop FLAG_PRIVILEGED.
6940            if (locationIsPrivileged(scanFile)) {
6941                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6942            } else {
6943                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6944            }
6945
6946            if (ps != null && !ps.codePath.equals(scanFile)) {
6947                // The path has changed from what was last scanned...  check the
6948                // version of the new path against what we have stored to determine
6949                // what to do.
6950                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6951                if (pkg.mVersionCode <= ps.versionCode) {
6952                    // The system package has been updated and the code path does not match
6953                    // Ignore entry. Skip it.
6954                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6955                            + " ignored: updated version " + ps.versionCode
6956                            + " better than this " + pkg.mVersionCode);
6957                    if (!updatedPkg.codePath.equals(scanFile)) {
6958                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6959                                + ps.name + " changing from " + updatedPkg.codePathString
6960                                + " to " + scanFile);
6961                        updatedPkg.codePath = scanFile;
6962                        updatedPkg.codePathString = scanFile.toString();
6963                        updatedPkg.resourcePath = scanFile;
6964                        updatedPkg.resourcePathString = scanFile.toString();
6965                    }
6966                    updatedPkg.pkg = pkg;
6967                    updatedPkg.versionCode = pkg.mVersionCode;
6968
6969                    // Update the disabled system child packages to point to the package too.
6970                    final int childCount = updatedPkg.childPackageNames != null
6971                            ? updatedPkg.childPackageNames.size() : 0;
6972                    for (int i = 0; i < childCount; i++) {
6973                        String childPackageName = updatedPkg.childPackageNames.get(i);
6974                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6975                                childPackageName);
6976                        if (updatedChildPkg != null) {
6977                            updatedChildPkg.pkg = pkg;
6978                            updatedChildPkg.versionCode = pkg.mVersionCode;
6979                        }
6980                    }
6981
6982                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6983                            + scanFile + " ignored: updated version " + ps.versionCode
6984                            + " better than this " + pkg.mVersionCode);
6985                } else {
6986                    // The current app on the system partition is better than
6987                    // what we have updated to on the data partition; switch
6988                    // back to the system partition version.
6989                    // At this point, its safely assumed that package installation for
6990                    // apps in system partition will go through. If not there won't be a working
6991                    // version of the app
6992                    // writer
6993                    synchronized (mPackages) {
6994                        // Just remove the loaded entries from package lists.
6995                        mPackages.remove(ps.name);
6996                    }
6997
6998                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6999                            + " reverting from " + ps.codePathString
7000                            + ": new version " + pkg.mVersionCode
7001                            + " better than installed " + ps.versionCode);
7002
7003                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7004                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7005                    synchronized (mInstallLock) {
7006                        args.cleanUpResourcesLI();
7007                    }
7008                    synchronized (mPackages) {
7009                        mSettings.enableSystemPackageLPw(ps.name);
7010                    }
7011                    updatedPkgBetter = true;
7012                }
7013            }
7014        }
7015
7016        if (updatedPkg != null) {
7017            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7018            // initially
7019            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7020
7021            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7022            // flag set initially
7023            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7024                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7025            }
7026        }
7027
7028        // Verify certificates against what was last scanned
7029        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7030
7031        /*
7032         * A new system app appeared, but we already had a non-system one of the
7033         * same name installed earlier.
7034         */
7035        boolean shouldHideSystemApp = false;
7036        if (updatedPkg == null && ps != null
7037                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7038            /*
7039             * Check to make sure the signatures match first. If they don't,
7040             * wipe the installed application and its data.
7041             */
7042            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7043                    != PackageManager.SIGNATURE_MATCH) {
7044                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7045                        + " signatures don't match existing userdata copy; removing");
7046                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7047                        "scanPackageInternalLI")) {
7048                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7049                }
7050                ps = null;
7051            } else {
7052                /*
7053                 * If the newly-added system app is an older version than the
7054                 * already installed version, hide it. It will be scanned later
7055                 * and re-added like an update.
7056                 */
7057                if (pkg.mVersionCode <= ps.versionCode) {
7058                    shouldHideSystemApp = true;
7059                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7060                            + " but new version " + pkg.mVersionCode + " better than installed "
7061                            + ps.versionCode + "; hiding system");
7062                } else {
7063                    /*
7064                     * The newly found system app is a newer version that the
7065                     * one previously installed. Simply remove the
7066                     * already-installed application and replace it with our own
7067                     * while keeping the application data.
7068                     */
7069                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7070                            + " reverting from " + ps.codePathString + ": new version "
7071                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7072                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7073                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7074                    synchronized (mInstallLock) {
7075                        args.cleanUpResourcesLI();
7076                    }
7077                }
7078            }
7079        }
7080
7081        // The apk is forward locked (not public) if its code and resources
7082        // are kept in different files. (except for app in either system or
7083        // vendor path).
7084        // TODO grab this value from PackageSettings
7085        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7086            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7087                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7088            }
7089        }
7090
7091        // TODO: extend to support forward-locked splits
7092        String resourcePath = null;
7093        String baseResourcePath = null;
7094        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7095            if (ps != null && ps.resourcePathString != null) {
7096                resourcePath = ps.resourcePathString;
7097                baseResourcePath = ps.resourcePathString;
7098            } else {
7099                // Should not happen at all. Just log an error.
7100                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7101            }
7102        } else {
7103            resourcePath = pkg.codePath;
7104            baseResourcePath = pkg.baseCodePath;
7105        }
7106
7107        // Set application objects path explicitly.
7108        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7109        pkg.setApplicationInfoCodePath(pkg.codePath);
7110        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7111        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7112        pkg.setApplicationInfoResourcePath(resourcePath);
7113        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7114        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7115
7116        // Note that we invoke the following method only if we are about to unpack an application
7117        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7118                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7119
7120        /*
7121         * If the system app should be overridden by a previously installed
7122         * data, hide the system app now and let the /data/app scan pick it up
7123         * again.
7124         */
7125        if (shouldHideSystemApp) {
7126            synchronized (mPackages) {
7127                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7128            }
7129        }
7130
7131        return scannedPkg;
7132    }
7133
7134    private static String fixProcessName(String defProcessName,
7135            String processName, int uid) {
7136        if (processName == null) {
7137            return defProcessName;
7138        }
7139        return processName;
7140    }
7141
7142    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7143            throws PackageManagerException {
7144        if (pkgSetting.signatures.mSignatures != null) {
7145            // Already existing package. Make sure signatures match
7146            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7147                    == PackageManager.SIGNATURE_MATCH;
7148            if (!match) {
7149                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7150                        == PackageManager.SIGNATURE_MATCH;
7151            }
7152            if (!match) {
7153                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7154                        == PackageManager.SIGNATURE_MATCH;
7155            }
7156            if (!match) {
7157                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7158                        + pkg.packageName + " signatures do not match the "
7159                        + "previously installed version; ignoring!");
7160            }
7161        }
7162
7163        // Check for shared user signatures
7164        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7165            // Already existing package. Make sure signatures match
7166            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7167                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7168            if (!match) {
7169                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7170                        == PackageManager.SIGNATURE_MATCH;
7171            }
7172            if (!match) {
7173                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7174                        == PackageManager.SIGNATURE_MATCH;
7175            }
7176            if (!match) {
7177                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7178                        "Package " + pkg.packageName
7179                        + " has no signatures that match those in shared user "
7180                        + pkgSetting.sharedUser.name + "; ignoring!");
7181            }
7182        }
7183    }
7184
7185    /**
7186     * Enforces that only the system UID or root's UID can call a method exposed
7187     * via Binder.
7188     *
7189     * @param message used as message if SecurityException is thrown
7190     * @throws SecurityException if the caller is not system or root
7191     */
7192    private static final void enforceSystemOrRoot(String message) {
7193        final int uid = Binder.getCallingUid();
7194        if (uid != Process.SYSTEM_UID && uid != 0) {
7195            throw new SecurityException(message);
7196        }
7197    }
7198
7199    @Override
7200    public void performFstrimIfNeeded() {
7201        enforceSystemOrRoot("Only the system can request fstrim");
7202
7203        // Before everything else, see whether we need to fstrim.
7204        try {
7205            IMountService ms = PackageHelper.getMountService();
7206            if (ms != null) {
7207                final boolean isUpgrade = isUpgrade();
7208                boolean doTrim = isUpgrade;
7209                if (doTrim) {
7210                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7211                } else {
7212                    final long interval = android.provider.Settings.Global.getLong(
7213                            mContext.getContentResolver(),
7214                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7215                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7216                    if (interval > 0) {
7217                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7218                        if (timeSinceLast > interval) {
7219                            doTrim = true;
7220                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7221                                    + "; running immediately");
7222                        }
7223                    }
7224                }
7225                if (doTrim) {
7226                    if (!isFirstBoot()) {
7227                        try {
7228                            ActivityManagerNative.getDefault().showBootMessage(
7229                                    mContext.getResources().getString(
7230                                            R.string.android_upgrading_fstrim), true);
7231                        } catch (RemoteException e) {
7232                        }
7233                    }
7234                    ms.runMaintenance();
7235                }
7236            } else {
7237                Slog.e(TAG, "Mount service unavailable!");
7238            }
7239        } catch (RemoteException e) {
7240            // Can't happen; MountService is local
7241        }
7242    }
7243
7244    @Override
7245    public void updatePackagesIfNeeded() {
7246        enforceSystemOrRoot("Only the system can request package update");
7247
7248        // We need to re-extract after an OTA.
7249        boolean causeUpgrade = isUpgrade();
7250
7251        // First boot or factory reset.
7252        // Note: we also handle devices that are upgrading to N right now as if it is their
7253        //       first boot, as they do not have profile data.
7254        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7255
7256        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7257        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7258
7259        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7260            return;
7261        }
7262
7263        List<PackageParser.Package> pkgs;
7264        synchronized (mPackages) {
7265            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7266        }
7267
7268        final long startTime = System.nanoTime();
7269        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7270                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7271
7272        final int elapsedTimeSeconds =
7273                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7274
7275        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7276        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7277        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7278        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7279        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7280    }
7281
7282    /**
7283     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7284     * containing statistics about the invocation. The array consists of three elements,
7285     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7286     * and {@code numberOfPackagesFailed}.
7287     */
7288    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7289            String compilerFilter) {
7290
7291        int numberOfPackagesVisited = 0;
7292        int numberOfPackagesOptimized = 0;
7293        int numberOfPackagesSkipped = 0;
7294        int numberOfPackagesFailed = 0;
7295        final int numberOfPackagesToDexopt = pkgs.size();
7296
7297        for (PackageParser.Package pkg : pkgs) {
7298            numberOfPackagesVisited++;
7299
7300            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7301                if (DEBUG_DEXOPT) {
7302                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7303                }
7304                numberOfPackagesSkipped++;
7305                continue;
7306            }
7307
7308            if (DEBUG_DEXOPT) {
7309                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7310                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7311            }
7312
7313            if (showDialog) {
7314                try {
7315                    ActivityManagerNative.getDefault().showBootMessage(
7316                            mContext.getResources().getString(R.string.android_upgrading_apk,
7317                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7318                } catch (RemoteException e) {
7319                }
7320            }
7321
7322            // checkProfiles is false to avoid merging profiles during boot which
7323            // might interfere with background compilation (b/28612421).
7324            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7325            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7326            // trade-off worth doing to save boot time work.
7327            int dexOptStatus = performDexOptTraced(pkg.packageName,
7328                    false /* checkProfiles */,
7329                    compilerFilter,
7330                    false /* force */);
7331            switch (dexOptStatus) {
7332                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7333                    numberOfPackagesOptimized++;
7334                    break;
7335                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7336                    numberOfPackagesSkipped++;
7337                    break;
7338                case PackageDexOptimizer.DEX_OPT_FAILED:
7339                    numberOfPackagesFailed++;
7340                    break;
7341                default:
7342                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7343                    break;
7344            }
7345        }
7346
7347        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7348                numberOfPackagesFailed };
7349    }
7350
7351    @Override
7352    public void notifyPackageUse(String packageName, int reason) {
7353        synchronized (mPackages) {
7354            PackageParser.Package p = mPackages.get(packageName);
7355            if (p == null) {
7356                return;
7357            }
7358            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7359        }
7360    }
7361
7362    // TODO: this is not used nor needed. Delete it.
7363    @Override
7364    public boolean performDexOptIfNeeded(String packageName) {
7365        int dexOptStatus = performDexOptTraced(packageName,
7366                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7367        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7368    }
7369
7370    @Override
7371    public boolean performDexOpt(String packageName,
7372            boolean checkProfiles, int compileReason, boolean force) {
7373        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7374                getCompilerFilterForReason(compileReason), force);
7375        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7376    }
7377
7378    @Override
7379    public boolean performDexOptMode(String packageName,
7380            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7381        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7382                targetCompilerFilter, force);
7383        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7384    }
7385
7386    private int performDexOptTraced(String packageName,
7387                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7389        try {
7390            return performDexOptInternal(packageName, checkProfiles,
7391                    targetCompilerFilter, force);
7392        } finally {
7393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7394        }
7395    }
7396
7397    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7398    // if the package can now be considered up to date for the given filter.
7399    private int performDexOptInternal(String packageName,
7400                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7401        PackageParser.Package p;
7402        synchronized (mPackages) {
7403            p = mPackages.get(packageName);
7404            if (p == null) {
7405                // Package could not be found. Report failure.
7406                return PackageDexOptimizer.DEX_OPT_FAILED;
7407            }
7408            mPackageUsage.write(false);
7409        }
7410        long callingId = Binder.clearCallingIdentity();
7411        try {
7412            synchronized (mInstallLock) {
7413                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7414                        targetCompilerFilter, force);
7415            }
7416        } finally {
7417            Binder.restoreCallingIdentity(callingId);
7418        }
7419    }
7420
7421    public ArraySet<String> getOptimizablePackages() {
7422        ArraySet<String> pkgs = new ArraySet<String>();
7423        synchronized (mPackages) {
7424            for (PackageParser.Package p : mPackages.values()) {
7425                if (PackageDexOptimizer.canOptimizePackage(p)) {
7426                    pkgs.add(p.packageName);
7427                }
7428            }
7429        }
7430        return pkgs;
7431    }
7432
7433    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7434            boolean checkProfiles, String targetCompilerFilter,
7435            boolean force) {
7436        // Select the dex optimizer based on the force parameter.
7437        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7438        //       allocate an object here.
7439        PackageDexOptimizer pdo = force
7440                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7441                : mPackageDexOptimizer;
7442
7443        // Optimize all dependencies first. Note: we ignore the return value and march on
7444        // on errors.
7445        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7446        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7447        if (!deps.isEmpty()) {
7448            for (PackageParser.Package depPackage : deps) {
7449                // TODO: Analyze and investigate if we (should) profile libraries.
7450                // Currently this will do a full compilation of the library by default.
7451                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7452                        false /* checkProfiles */,
7453                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7454            }
7455        }
7456        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7457                targetCompilerFilter);
7458    }
7459
7460    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7461        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7462            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7463            Set<String> collectedNames = new HashSet<>();
7464            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7465
7466            retValue.remove(p);
7467
7468            return retValue;
7469        } else {
7470            return Collections.emptyList();
7471        }
7472    }
7473
7474    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7475            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7476        if (!collectedNames.contains(p.packageName)) {
7477            collectedNames.add(p.packageName);
7478            collected.add(p);
7479
7480            if (p.usesLibraries != null) {
7481                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7482            }
7483            if (p.usesOptionalLibraries != null) {
7484                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7485                        collectedNames);
7486            }
7487        }
7488    }
7489
7490    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7491            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7492        for (String libName : libs) {
7493            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7494            if (libPkg != null) {
7495                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7496            }
7497        }
7498    }
7499
7500    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7501        synchronized (mPackages) {
7502            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7503            if (lib != null && lib.apk != null) {
7504                return mPackages.get(lib.apk);
7505            }
7506        }
7507        return null;
7508    }
7509
7510    public void shutdown() {
7511        mPackageUsage.write(true);
7512    }
7513
7514    @Override
7515    public void dumpProfiles(String packageName) {
7516        PackageParser.Package pkg;
7517        synchronized (mPackages) {
7518            pkg = mPackages.get(packageName);
7519            if (pkg == null) {
7520                throw new IllegalArgumentException("Unknown package: " + packageName);
7521            }
7522        }
7523        /* Only the shell or the app user should be able to dump profiles. */
7524        int callingUid = Binder.getCallingUid();
7525        if (callingUid != Process.SHELL_UID && callingUid != pkg.applicationInfo.uid) {
7526            throw new SecurityException("dumpProfiles");
7527        }
7528
7529        synchronized (mInstallLock) {
7530            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7531            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7532            try {
7533                final File codeFile = new File(pkg.applicationInfo.getCodePath());
7534                List<String> allCodePaths = Collections.EMPTY_LIST;
7535                if (codeFile != null && codeFile.exists()) {
7536                    try {
7537                        final PackageLite codePkg = PackageParser.parsePackageLite(codeFile, 0);
7538                        allCodePaths = codePkg.getAllCodePaths();
7539                    } catch (PackageParserException e) {
7540                        // Well, we tried.
7541                    }
7542                }
7543                String gid = Integer.toString(sharedGid);
7544                String codePaths = TextUtils.join(";", allCodePaths);
7545                mInstaller.dumpProfiles(gid, packageName, codePaths);
7546            } catch (InstallerException e) {
7547                Slog.w(TAG, "Failed to dump profiles", e);
7548            }
7549            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7550        }
7551    }
7552
7553    @Override
7554    public void forceDexOpt(String packageName) {
7555        enforceSystemOrRoot("forceDexOpt");
7556
7557        PackageParser.Package pkg;
7558        synchronized (mPackages) {
7559            pkg = mPackages.get(packageName);
7560            if (pkg == null) {
7561                throw new IllegalArgumentException("Unknown package: " + packageName);
7562            }
7563        }
7564
7565        synchronized (mInstallLock) {
7566            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7567
7568            // Whoever is calling forceDexOpt wants a fully compiled package.
7569            // Don't use profiles since that may cause compilation to be skipped.
7570            final int res = performDexOptInternalWithDependenciesLI(pkg,
7571                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7572                    true /* force */);
7573
7574            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7575            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7576                throw new IllegalStateException("Failed to dexopt: " + res);
7577            }
7578        }
7579    }
7580
7581    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7582        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7583            Slog.w(TAG, "Unable to update from " + oldPkg.name
7584                    + " to " + newPkg.packageName
7585                    + ": old package not in system partition");
7586            return false;
7587        } else if (mPackages.get(oldPkg.name) != null) {
7588            Slog.w(TAG, "Unable to update from " + oldPkg.name
7589                    + " to " + newPkg.packageName
7590                    + ": old package still exists");
7591            return false;
7592        }
7593        return true;
7594    }
7595
7596    void removeCodePathLI(File codePath) {
7597        if (codePath.isDirectory()) {
7598            try {
7599                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7600            } catch (InstallerException e) {
7601                Slog.w(TAG, "Failed to remove code path", e);
7602            }
7603        } else {
7604            codePath.delete();
7605        }
7606    }
7607
7608    private int[] resolveUserIds(int userId) {
7609        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7610    }
7611
7612    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7613        if (pkg == null) {
7614            Slog.wtf(TAG, "Package was null!", new Throwable());
7615            return;
7616        }
7617        clearAppDataLeafLIF(pkg, userId, flags);
7618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7619        for (int i = 0; i < childCount; i++) {
7620            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7621        }
7622    }
7623
7624    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7625        final PackageSetting ps;
7626        synchronized (mPackages) {
7627            ps = mSettings.mPackages.get(pkg.packageName);
7628        }
7629        for (int realUserId : resolveUserIds(userId)) {
7630            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7631            try {
7632                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7633                        ceDataInode);
7634            } catch (InstallerException e) {
7635                Slog.w(TAG, String.valueOf(e));
7636            }
7637        }
7638    }
7639
7640    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7641        if (pkg == null) {
7642            Slog.wtf(TAG, "Package was null!", new Throwable());
7643            return;
7644        }
7645        destroyAppDataLeafLIF(pkg, userId, flags);
7646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7647        for (int i = 0; i < childCount; i++) {
7648            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7649        }
7650    }
7651
7652    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7653        final PackageSetting ps;
7654        synchronized (mPackages) {
7655            ps = mSettings.mPackages.get(pkg.packageName);
7656        }
7657        for (int realUserId : resolveUserIds(userId)) {
7658            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7659            try {
7660                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7661                        ceDataInode);
7662            } catch (InstallerException e) {
7663                Slog.w(TAG, String.valueOf(e));
7664            }
7665        }
7666    }
7667
7668    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7669        if (pkg == null) {
7670            Slog.wtf(TAG, "Package was null!", new Throwable());
7671            return;
7672        }
7673        destroyAppProfilesLeafLIF(pkg);
7674        destroyAppReferenceProfileLeafLIF(pkg, userId);
7675        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7676        for (int i = 0; i < childCount; i++) {
7677            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7678            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId);
7679        }
7680    }
7681
7682    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId) {
7683        if (pkg.isForwardLocked()) {
7684            return;
7685        }
7686
7687        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7688            try {
7689                path = PackageManagerServiceUtils.realpath(new File(path));
7690            } catch (IOException e) {
7691                // TODO: Should we return early here ?
7692                Slog.w(TAG, "Failed to get canonical path", e);
7693                continue;
7694            }
7695
7696            final String useMarker = path.replace('/', '@');
7697            for (int realUserId : resolveUserIds(userId)) {
7698                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7699                File foreignUseMark = new File(profileDir, useMarker);
7700                if (foreignUseMark.exists()) {
7701                    if (!foreignUseMark.delete()) {
7702                        Slog.w(TAG, "Unable to delete foreign user mark for package: "
7703                            + pkg.packageName);
7704                    }
7705                }
7706
7707                File[] markers = profileDir.listFiles();
7708                if (markers != null) {
7709                    final String searchString = "@" + pkg.packageName + "@";
7710                    // We also delete all markers that contain the package name we're
7711                    // uninstalling. These are associated with secondary dex-files belonging
7712                    // to the package. Reconstructing the path of these dex files is messy
7713                    // in general.
7714                    for (File marker : markers) {
7715                        if (marker.getName().indexOf(searchString) > 0) {
7716                            if (!marker.delete()) {
7717                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7718                                    + pkg.packageName);
7719                            }
7720                        }
7721                    }
7722                }
7723            }
7724        }
7725    }
7726
7727    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7728        try {
7729            mInstaller.destroyAppProfiles(pkg.packageName);
7730        } catch (InstallerException e) {
7731            Slog.w(TAG, String.valueOf(e));
7732        }
7733    }
7734
7735    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7736        if (pkg == null) {
7737            Slog.wtf(TAG, "Package was null!", new Throwable());
7738            return;
7739        }
7740        clearAppProfilesLeafLIF(pkg);
7741        destroyAppReferenceProfileLeafLIF(pkg, userId);
7742        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7743        for (int i = 0; i < childCount; i++) {
7744            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7745        }
7746    }
7747
7748    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7749        try {
7750            mInstaller.clearAppProfiles(pkg.packageName);
7751        } catch (InstallerException e) {
7752            Slog.w(TAG, String.valueOf(e));
7753        }
7754    }
7755
7756    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7757            long lastUpdateTime) {
7758        // Set parent install/update time
7759        PackageSetting ps = (PackageSetting) pkg.mExtras;
7760        if (ps != null) {
7761            ps.firstInstallTime = firstInstallTime;
7762            ps.lastUpdateTime = lastUpdateTime;
7763        }
7764        // Set children install/update time
7765        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7766        for (int i = 0; i < childCount; i++) {
7767            PackageParser.Package childPkg = pkg.childPackages.get(i);
7768            ps = (PackageSetting) childPkg.mExtras;
7769            if (ps != null) {
7770                ps.firstInstallTime = firstInstallTime;
7771                ps.lastUpdateTime = lastUpdateTime;
7772            }
7773        }
7774    }
7775
7776    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7777            PackageParser.Package changingLib) {
7778        if (file.path != null) {
7779            usesLibraryFiles.add(file.path);
7780            return;
7781        }
7782        PackageParser.Package p = mPackages.get(file.apk);
7783        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7784            // If we are doing this while in the middle of updating a library apk,
7785            // then we need to make sure to use that new apk for determining the
7786            // dependencies here.  (We haven't yet finished committing the new apk
7787            // to the package manager state.)
7788            if (p == null || p.packageName.equals(changingLib.packageName)) {
7789                p = changingLib;
7790            }
7791        }
7792        if (p != null) {
7793            usesLibraryFiles.addAll(p.getAllCodePaths());
7794        }
7795    }
7796
7797    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7798            PackageParser.Package changingLib) throws PackageManagerException {
7799        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7800            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7801            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7802            for (int i=0; i<N; i++) {
7803                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7804                if (file == null) {
7805                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7806                            "Package " + pkg.packageName + " requires unavailable shared library "
7807                            + pkg.usesLibraries.get(i) + "; failing!");
7808                }
7809                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7810            }
7811            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7812            for (int i=0; i<N; i++) {
7813                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7814                if (file == null) {
7815                    Slog.w(TAG, "Package " + pkg.packageName
7816                            + " desires unavailable shared library "
7817                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7818                } else {
7819                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7820                }
7821            }
7822            N = usesLibraryFiles.size();
7823            if (N > 0) {
7824                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7825            } else {
7826                pkg.usesLibraryFiles = null;
7827            }
7828        }
7829    }
7830
7831    private static boolean hasString(List<String> list, List<String> which) {
7832        if (list == null) {
7833            return false;
7834        }
7835        for (int i=list.size()-1; i>=0; i--) {
7836            for (int j=which.size()-1; j>=0; j--) {
7837                if (which.get(j).equals(list.get(i))) {
7838                    return true;
7839                }
7840            }
7841        }
7842        return false;
7843    }
7844
7845    private void updateAllSharedLibrariesLPw() {
7846        for (PackageParser.Package pkg : mPackages.values()) {
7847            try {
7848                updateSharedLibrariesLPw(pkg, null);
7849            } catch (PackageManagerException e) {
7850                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7851            }
7852        }
7853    }
7854
7855    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7856            PackageParser.Package changingPkg) {
7857        ArrayList<PackageParser.Package> res = null;
7858        for (PackageParser.Package pkg : mPackages.values()) {
7859            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7860                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7861                if (res == null) {
7862                    res = new ArrayList<PackageParser.Package>();
7863                }
7864                res.add(pkg);
7865                try {
7866                    updateSharedLibrariesLPw(pkg, changingPkg);
7867                } catch (PackageManagerException e) {
7868                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7869                }
7870            }
7871        }
7872        return res;
7873    }
7874
7875    /**
7876     * Derive the value of the {@code cpuAbiOverride} based on the provided
7877     * value and an optional stored value from the package settings.
7878     */
7879    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7880        String cpuAbiOverride = null;
7881
7882        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7883            cpuAbiOverride = null;
7884        } else if (abiOverride != null) {
7885            cpuAbiOverride = abiOverride;
7886        } else if (settings != null) {
7887            cpuAbiOverride = settings.cpuAbiOverrideString;
7888        }
7889
7890        return cpuAbiOverride;
7891    }
7892
7893    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7894            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7895                    throws PackageManagerException {
7896        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7897        // If the package has children and this is the first dive in the function
7898        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7899        // whether all packages (parent and children) would be successfully scanned
7900        // before the actual scan since scanning mutates internal state and we want
7901        // to atomically install the package and its children.
7902        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7903            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7904                scanFlags |= SCAN_CHECK_ONLY;
7905            }
7906        } else {
7907            scanFlags &= ~SCAN_CHECK_ONLY;
7908        }
7909
7910        final PackageParser.Package scannedPkg;
7911        try {
7912            // Scan the parent
7913            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7914            // Scan the children
7915            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7916            for (int i = 0; i < childCount; i++) {
7917                PackageParser.Package childPkg = pkg.childPackages.get(i);
7918                scanPackageLI(childPkg, policyFlags,
7919                        scanFlags, currentTime, user);
7920            }
7921        } finally {
7922            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7923        }
7924
7925        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7926            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7927        }
7928
7929        return scannedPkg;
7930    }
7931
7932    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7933            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7934        boolean success = false;
7935        try {
7936            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7937                    currentTime, user);
7938            success = true;
7939            return res;
7940        } finally {
7941            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7942                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7943                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7944                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7945                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7946            }
7947        }
7948    }
7949
7950    /**
7951     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7952     */
7953    private static boolean apkHasCode(String fileName) {
7954        StrictJarFile jarFile = null;
7955        try {
7956            jarFile = new StrictJarFile(fileName,
7957                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7958            return jarFile.findEntry("classes.dex") != null;
7959        } catch (IOException ignore) {
7960        } finally {
7961            try {
7962                jarFile.close();
7963            } catch (IOException ignore) {}
7964        }
7965        return false;
7966    }
7967
7968    /**
7969     * Enforces code policy for the package. This ensures that if an APK has
7970     * declared hasCode="true" in its manifest that the APK actually contains
7971     * code.
7972     *
7973     * @throws PackageManagerException If bytecode could not be found when it should exist
7974     */
7975    private static void enforceCodePolicy(PackageParser.Package pkg)
7976            throws PackageManagerException {
7977        final boolean shouldHaveCode =
7978                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7979        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7980            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7981                    "Package " + pkg.baseCodePath + " code is missing");
7982        }
7983
7984        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7985            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7986                final boolean splitShouldHaveCode =
7987                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7988                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7989                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7990                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7991                }
7992            }
7993        }
7994    }
7995
7996    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7997            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7998            throws PackageManagerException {
7999        final File scanFile = new File(pkg.codePath);
8000        if (pkg.applicationInfo.getCodePath() == null ||
8001                pkg.applicationInfo.getResourcePath() == null) {
8002            // Bail out. The resource and code paths haven't been set.
8003            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8004                    "Code and resource paths haven't been set correctly");
8005        }
8006
8007        // Apply policy
8008        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8009            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8010            if (pkg.applicationInfo.isDirectBootAware()) {
8011                // we're direct boot aware; set for all components
8012                for (PackageParser.Service s : pkg.services) {
8013                    s.info.encryptionAware = s.info.directBootAware = true;
8014                }
8015                for (PackageParser.Provider p : pkg.providers) {
8016                    p.info.encryptionAware = p.info.directBootAware = true;
8017                }
8018                for (PackageParser.Activity a : pkg.activities) {
8019                    a.info.encryptionAware = a.info.directBootAware = true;
8020                }
8021                for (PackageParser.Activity r : pkg.receivers) {
8022                    r.info.encryptionAware = r.info.directBootAware = true;
8023                }
8024            }
8025        } else {
8026            // Only allow system apps to be flagged as core apps.
8027            pkg.coreApp = false;
8028            // clear flags not applicable to regular apps
8029            pkg.applicationInfo.privateFlags &=
8030                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8031            pkg.applicationInfo.privateFlags &=
8032                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8033        }
8034        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8035
8036        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8037            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8038        }
8039
8040        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8041            enforceCodePolicy(pkg);
8042        }
8043
8044        if (mCustomResolverComponentName != null &&
8045                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8046            setUpCustomResolverActivity(pkg);
8047        }
8048
8049        if (pkg.packageName.equals("android")) {
8050            synchronized (mPackages) {
8051                if (mAndroidApplication != null) {
8052                    Slog.w(TAG, "*************************************************");
8053                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8054                    Slog.w(TAG, " file=" + scanFile);
8055                    Slog.w(TAG, "*************************************************");
8056                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8057                            "Core android package being redefined.  Skipping.");
8058                }
8059
8060                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8061                    // Set up information for our fall-back user intent resolution activity.
8062                    mPlatformPackage = pkg;
8063                    pkg.mVersionCode = mSdkVersion;
8064                    mAndroidApplication = pkg.applicationInfo;
8065
8066                    if (!mResolverReplaced) {
8067                        mResolveActivity.applicationInfo = mAndroidApplication;
8068                        mResolveActivity.name = ResolverActivity.class.getName();
8069                        mResolveActivity.packageName = mAndroidApplication.packageName;
8070                        mResolveActivity.processName = "system:ui";
8071                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8072                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8073                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8074                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8075                        mResolveActivity.exported = true;
8076                        mResolveActivity.enabled = true;
8077                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8078                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8079                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8080                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8081                                | ActivityInfo.CONFIG_ORIENTATION
8082                                | ActivityInfo.CONFIG_KEYBOARD
8083                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8084                        mResolveInfo.activityInfo = mResolveActivity;
8085                        mResolveInfo.priority = 0;
8086                        mResolveInfo.preferredOrder = 0;
8087                        mResolveInfo.match = 0;
8088                        mResolveComponentName = new ComponentName(
8089                                mAndroidApplication.packageName, mResolveActivity.name);
8090                    }
8091                }
8092            }
8093        }
8094
8095        if (DEBUG_PACKAGE_SCANNING) {
8096            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8097                Log.d(TAG, "Scanning package " + pkg.packageName);
8098        }
8099
8100        synchronized (mPackages) {
8101            if (mPackages.containsKey(pkg.packageName)
8102                    || mSharedLibraries.containsKey(pkg.packageName)) {
8103                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8104                        "Application package " + pkg.packageName
8105                                + " already installed.  Skipping duplicate.");
8106            }
8107
8108            // If we're only installing presumed-existing packages, require that the
8109            // scanned APK is both already known and at the path previously established
8110            // for it.  Previously unknown packages we pick up normally, but if we have an
8111            // a priori expectation about this package's install presence, enforce it.
8112            // With a singular exception for new system packages. When an OTA contains
8113            // a new system package, we allow the codepath to change from a system location
8114            // to the user-installed location. If we don't allow this change, any newer,
8115            // user-installed version of the application will be ignored.
8116            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8117                if (mExpectingBetter.containsKey(pkg.packageName)) {
8118                    logCriticalInfo(Log.WARN,
8119                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8120                } else {
8121                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8122                    if (known != null) {
8123                        if (DEBUG_PACKAGE_SCANNING) {
8124                            Log.d(TAG, "Examining " + pkg.codePath
8125                                    + " and requiring known paths " + known.codePathString
8126                                    + " & " + known.resourcePathString);
8127                        }
8128                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8129                                || !pkg.applicationInfo.getResourcePath().equals(
8130                                known.resourcePathString)) {
8131                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8132                                    "Application package " + pkg.packageName
8133                                            + " found at " + pkg.applicationInfo.getCodePath()
8134                                            + " but expected at " + known.codePathString
8135                                            + "; ignoring.");
8136                        }
8137                    }
8138                }
8139            }
8140        }
8141
8142        // Initialize package source and resource directories
8143        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8144        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8145
8146        SharedUserSetting suid = null;
8147        PackageSetting pkgSetting = null;
8148
8149        if (!isSystemApp(pkg)) {
8150            // Only system apps can use these features.
8151            pkg.mOriginalPackages = null;
8152            pkg.mRealPackage = null;
8153            pkg.mAdoptPermissions = null;
8154        }
8155
8156        // Getting the package setting may have a side-effect, so if we
8157        // are only checking if scan would succeed, stash a copy of the
8158        // old setting to restore at the end.
8159        PackageSetting nonMutatedPs = null;
8160
8161        // writer
8162        synchronized (mPackages) {
8163            if (pkg.mSharedUserId != null) {
8164                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8165                if (suid == null) {
8166                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8167                            "Creating application package " + pkg.packageName
8168                            + " for shared user failed");
8169                }
8170                if (DEBUG_PACKAGE_SCANNING) {
8171                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8172                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8173                                + "): packages=" + suid.packages);
8174                }
8175            }
8176
8177            // Check if we are renaming from an original package name.
8178            PackageSetting origPackage = null;
8179            String realName = null;
8180            if (pkg.mOriginalPackages != null) {
8181                // This package may need to be renamed to a previously
8182                // installed name.  Let's check on that...
8183                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8184                if (pkg.mOriginalPackages.contains(renamed)) {
8185                    // This package had originally been installed as the
8186                    // original name, and we have already taken care of
8187                    // transitioning to the new one.  Just update the new
8188                    // one to continue using the old name.
8189                    realName = pkg.mRealPackage;
8190                    if (!pkg.packageName.equals(renamed)) {
8191                        // Callers into this function may have already taken
8192                        // care of renaming the package; only do it here if
8193                        // it is not already done.
8194                        pkg.setPackageName(renamed);
8195                    }
8196
8197                } else {
8198                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8199                        if ((origPackage = mSettings.peekPackageLPr(
8200                                pkg.mOriginalPackages.get(i))) != null) {
8201                            // We do have the package already installed under its
8202                            // original name...  should we use it?
8203                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8204                                // New package is not compatible with original.
8205                                origPackage = null;
8206                                continue;
8207                            } else if (origPackage.sharedUser != null) {
8208                                // Make sure uid is compatible between packages.
8209                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8210                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8211                                            + " to " + pkg.packageName + ": old uid "
8212                                            + origPackage.sharedUser.name
8213                                            + " differs from " + pkg.mSharedUserId);
8214                                    origPackage = null;
8215                                    continue;
8216                                }
8217                                // TODO: Add case when shared user id is added [b/28144775]
8218                            } else {
8219                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8220                                        + pkg.packageName + " to old name " + origPackage.name);
8221                            }
8222                            break;
8223                        }
8224                    }
8225                }
8226            }
8227
8228            if (mTransferedPackages.contains(pkg.packageName)) {
8229                Slog.w(TAG, "Package " + pkg.packageName
8230                        + " was transferred to another, but its .apk remains");
8231            }
8232
8233            // See comments in nonMutatedPs declaration
8234            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8235                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8236                if (foundPs != null) {
8237                    nonMutatedPs = new PackageSetting(foundPs);
8238                }
8239            }
8240
8241            // Just create the setting, don't add it yet. For already existing packages
8242            // the PkgSetting exists already and doesn't have to be created.
8243            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8244                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8245                    pkg.applicationInfo.primaryCpuAbi,
8246                    pkg.applicationInfo.secondaryCpuAbi,
8247                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8248                    user, false);
8249            if (pkgSetting == null) {
8250                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8251                        "Creating application package " + pkg.packageName + " failed");
8252            }
8253
8254            if (pkgSetting.origPackage != null) {
8255                // If we are first transitioning from an original package,
8256                // fix up the new package's name now.  We need to do this after
8257                // looking up the package under its new name, so getPackageLP
8258                // can take care of fiddling things correctly.
8259                pkg.setPackageName(origPackage.name);
8260
8261                // File a report about this.
8262                String msg = "New package " + pkgSetting.realName
8263                        + " renamed to replace old package " + pkgSetting.name;
8264                reportSettingsProblem(Log.WARN, msg);
8265
8266                // Make a note of it.
8267                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8268                    mTransferedPackages.add(origPackage.name);
8269                }
8270
8271                // No longer need to retain this.
8272                pkgSetting.origPackage = null;
8273            }
8274
8275            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8276                // Make a note of it.
8277                mTransferedPackages.add(pkg.packageName);
8278            }
8279
8280            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8281                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8282            }
8283
8284            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8285                // Check all shared libraries and map to their actual file path.
8286                // We only do this here for apps not on a system dir, because those
8287                // are the only ones that can fail an install due to this.  We
8288                // will take care of the system apps by updating all of their
8289                // library paths after the scan is done.
8290                updateSharedLibrariesLPw(pkg, null);
8291            }
8292
8293            if (mFoundPolicyFile) {
8294                SELinuxMMAC.assignSeinfoValue(pkg);
8295            }
8296
8297            pkg.applicationInfo.uid = pkgSetting.appId;
8298            pkg.mExtras = pkgSetting;
8299            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8300                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8301                    // We just determined the app is signed correctly, so bring
8302                    // over the latest parsed certs.
8303                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8304                } else {
8305                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8306                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8307                                "Package " + pkg.packageName + " upgrade keys do not match the "
8308                                + "previously installed version");
8309                    } else {
8310                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8311                        String msg = "System package " + pkg.packageName
8312                            + " signature changed; retaining data.";
8313                        reportSettingsProblem(Log.WARN, msg);
8314                    }
8315                }
8316            } else {
8317                try {
8318                    verifySignaturesLP(pkgSetting, pkg);
8319                    // We just determined the app is signed correctly, so bring
8320                    // over the latest parsed certs.
8321                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8322                } catch (PackageManagerException e) {
8323                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8324                        throw e;
8325                    }
8326                    // The signature has changed, but this package is in the system
8327                    // image...  let's recover!
8328                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8329                    // However...  if this package is part of a shared user, but it
8330                    // doesn't match the signature of the shared user, let's fail.
8331                    // What this means is that you can't change the signatures
8332                    // associated with an overall shared user, which doesn't seem all
8333                    // that unreasonable.
8334                    if (pkgSetting.sharedUser != null) {
8335                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8336                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8337                            throw new PackageManagerException(
8338                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8339                                            "Signature mismatch for shared user: "
8340                                            + pkgSetting.sharedUser);
8341                        }
8342                    }
8343                    // File a report about this.
8344                    String msg = "System package " + pkg.packageName
8345                        + " signature changed; retaining data.";
8346                    reportSettingsProblem(Log.WARN, msg);
8347                }
8348            }
8349            // Verify that this new package doesn't have any content providers
8350            // that conflict with existing packages.  Only do this if the
8351            // package isn't already installed, since we don't want to break
8352            // things that are installed.
8353            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8354                final int N = pkg.providers.size();
8355                int i;
8356                for (i=0; i<N; i++) {
8357                    PackageParser.Provider p = pkg.providers.get(i);
8358                    if (p.info.authority != null) {
8359                        String names[] = p.info.authority.split(";");
8360                        for (int j = 0; j < names.length; j++) {
8361                            if (mProvidersByAuthority.containsKey(names[j])) {
8362                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8363                                final String otherPackageName =
8364                                        ((other != null && other.getComponentName() != null) ?
8365                                                other.getComponentName().getPackageName() : "?");
8366                                throw new PackageManagerException(
8367                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8368                                                "Can't install because provider name " + names[j]
8369                                                + " (in package " + pkg.applicationInfo.packageName
8370                                                + ") is already used by " + otherPackageName);
8371                            }
8372                        }
8373                    }
8374                }
8375            }
8376
8377            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8378                // This package wants to adopt ownership of permissions from
8379                // another package.
8380                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8381                    final String origName = pkg.mAdoptPermissions.get(i);
8382                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8383                    if (orig != null) {
8384                        if (verifyPackageUpdateLPr(orig, pkg)) {
8385                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8386                                    + pkg.packageName);
8387                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8388                        }
8389                    }
8390                }
8391            }
8392        }
8393
8394        final String pkgName = pkg.packageName;
8395
8396        final long scanFileTime = scanFile.lastModified();
8397        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8398        pkg.applicationInfo.processName = fixProcessName(
8399                pkg.applicationInfo.packageName,
8400                pkg.applicationInfo.processName,
8401                pkg.applicationInfo.uid);
8402
8403        if (pkg != mPlatformPackage) {
8404            // Get all of our default paths setup
8405            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8406        }
8407
8408        final String path = scanFile.getPath();
8409        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8410
8411        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8412            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8413
8414            // Some system apps still use directory structure for native libraries
8415            // in which case we might end up not detecting abi solely based on apk
8416            // structure. Try to detect abi based on directory structure.
8417            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8418                    pkg.applicationInfo.primaryCpuAbi == null) {
8419                setBundledAppAbisAndRoots(pkg, pkgSetting);
8420                setNativeLibraryPaths(pkg);
8421            }
8422
8423        } else {
8424            if ((scanFlags & SCAN_MOVE) != 0) {
8425                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8426                // but we already have this packages package info in the PackageSetting. We just
8427                // use that and derive the native library path based on the new codepath.
8428                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8429                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8430            }
8431
8432            // Set native library paths again. For moves, the path will be updated based on the
8433            // ABIs we've determined above. For non-moves, the path will be updated based on the
8434            // ABIs we determined during compilation, but the path will depend on the final
8435            // package path (after the rename away from the stage path).
8436            setNativeLibraryPaths(pkg);
8437        }
8438
8439        // This is a special case for the "system" package, where the ABI is
8440        // dictated by the zygote configuration (and init.rc). We should keep track
8441        // of this ABI so that we can deal with "normal" applications that run under
8442        // the same UID correctly.
8443        if (mPlatformPackage == pkg) {
8444            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8445                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8446        }
8447
8448        // If there's a mismatch between the abi-override in the package setting
8449        // and the abiOverride specified for the install. Warn about this because we
8450        // would've already compiled the app without taking the package setting into
8451        // account.
8452        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8453            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8454                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8455                        " for package " + pkg.packageName);
8456            }
8457        }
8458
8459        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8460        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8461        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8462
8463        // Copy the derived override back to the parsed package, so that we can
8464        // update the package settings accordingly.
8465        pkg.cpuAbiOverride = cpuAbiOverride;
8466
8467        if (DEBUG_ABI_SELECTION) {
8468            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8469                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8470                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8471        }
8472
8473        // Push the derived path down into PackageSettings so we know what to
8474        // clean up at uninstall time.
8475        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8476
8477        if (DEBUG_ABI_SELECTION) {
8478            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8479                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8480                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8481        }
8482
8483        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8484            // We don't do this here during boot because we can do it all
8485            // at once after scanning all existing packages.
8486            //
8487            // We also do this *before* we perform dexopt on this package, so that
8488            // we can avoid redundant dexopts, and also to make sure we've got the
8489            // code and package path correct.
8490            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8491                    pkg, true /* boot complete */);
8492        }
8493
8494        if (mFactoryTest && pkg.requestedPermissions.contains(
8495                android.Manifest.permission.FACTORY_TEST)) {
8496            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8497        }
8498
8499        ArrayList<PackageParser.Package> clientLibPkgs = null;
8500
8501        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8502            if (nonMutatedPs != null) {
8503                synchronized (mPackages) {
8504                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8505                }
8506            }
8507            return pkg;
8508        }
8509
8510        // Only privileged apps and updated privileged apps can add child packages.
8511        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8512            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8513                throw new PackageManagerException("Only privileged apps and updated "
8514                        + "privileged apps can add child packages. Ignoring package "
8515                        + pkg.packageName);
8516            }
8517            final int childCount = pkg.childPackages.size();
8518            for (int i = 0; i < childCount; i++) {
8519                PackageParser.Package childPkg = pkg.childPackages.get(i);
8520                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8521                        childPkg.packageName)) {
8522                    throw new PackageManagerException("Cannot override a child package of "
8523                            + "another disabled system app. Ignoring package " + pkg.packageName);
8524                }
8525            }
8526        }
8527
8528        // writer
8529        synchronized (mPackages) {
8530            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8531                // Only system apps can add new shared libraries.
8532                if (pkg.libraryNames != null) {
8533                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8534                        String name = pkg.libraryNames.get(i);
8535                        boolean allowed = false;
8536                        if (pkg.isUpdatedSystemApp()) {
8537                            // New library entries can only be added through the
8538                            // system image.  This is important to get rid of a lot
8539                            // of nasty edge cases: for example if we allowed a non-
8540                            // system update of the app to add a library, then uninstalling
8541                            // the update would make the library go away, and assumptions
8542                            // we made such as through app install filtering would now
8543                            // have allowed apps on the device which aren't compatible
8544                            // with it.  Better to just have the restriction here, be
8545                            // conservative, and create many fewer cases that can negatively
8546                            // impact the user experience.
8547                            final PackageSetting sysPs = mSettings
8548                                    .getDisabledSystemPkgLPr(pkg.packageName);
8549                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8550                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8551                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8552                                        allowed = true;
8553                                        break;
8554                                    }
8555                                }
8556                            }
8557                        } else {
8558                            allowed = true;
8559                        }
8560                        if (allowed) {
8561                            if (!mSharedLibraries.containsKey(name)) {
8562                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8563                            } else if (!name.equals(pkg.packageName)) {
8564                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8565                                        + name + " already exists; skipping");
8566                            }
8567                        } else {
8568                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8569                                    + name + " that is not declared on system image; skipping");
8570                        }
8571                    }
8572                    if ((scanFlags & SCAN_BOOTING) == 0) {
8573                        // If we are not booting, we need to update any applications
8574                        // that are clients of our shared library.  If we are booting,
8575                        // this will all be done once the scan is complete.
8576                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8577                    }
8578                }
8579            }
8580        }
8581
8582        if ((scanFlags & SCAN_BOOTING) != 0) {
8583            // No apps can run during boot scan, so they don't need to be frozen
8584        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8585            // Caller asked to not kill app, so it's probably not frozen
8586        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8587            // Caller asked us to ignore frozen check for some reason; they
8588            // probably didn't know the package name
8589        } else {
8590            // We're doing major surgery on this package, so it better be frozen
8591            // right now to keep it from launching
8592            checkPackageFrozen(pkgName);
8593        }
8594
8595        // Also need to kill any apps that are dependent on the library.
8596        if (clientLibPkgs != null) {
8597            for (int i=0; i<clientLibPkgs.size(); i++) {
8598                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8599                killApplication(clientPkg.applicationInfo.packageName,
8600                        clientPkg.applicationInfo.uid, "update lib");
8601            }
8602        }
8603
8604        // Make sure we're not adding any bogus keyset info
8605        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8606        ksms.assertScannedPackageValid(pkg);
8607
8608        // writer
8609        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8610
8611        boolean createIdmapFailed = false;
8612        synchronized (mPackages) {
8613            // We don't expect installation to fail beyond this point
8614
8615            // Add the new setting to mSettings
8616            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8617            // Add the new setting to mPackages
8618            mPackages.put(pkg.applicationInfo.packageName, pkg);
8619            // Make sure we don't accidentally delete its data.
8620            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8621            while (iter.hasNext()) {
8622                PackageCleanItem item = iter.next();
8623                if (pkgName.equals(item.packageName)) {
8624                    iter.remove();
8625                }
8626            }
8627
8628            // Take care of first install / last update times.
8629            if (currentTime != 0) {
8630                if (pkgSetting.firstInstallTime == 0) {
8631                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8632                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8633                    pkgSetting.lastUpdateTime = currentTime;
8634                }
8635            } else if (pkgSetting.firstInstallTime == 0) {
8636                // We need *something*.  Take time time stamp of the file.
8637                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8638            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8639                if (scanFileTime != pkgSetting.timeStamp) {
8640                    // A package on the system image has changed; consider this
8641                    // to be an update.
8642                    pkgSetting.lastUpdateTime = scanFileTime;
8643                }
8644            }
8645
8646            // Add the package's KeySets to the global KeySetManagerService
8647            ksms.addScannedPackageLPw(pkg);
8648
8649            int N = pkg.providers.size();
8650            StringBuilder r = null;
8651            int i;
8652            for (i=0; i<N; i++) {
8653                PackageParser.Provider p = pkg.providers.get(i);
8654                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8655                        p.info.processName, pkg.applicationInfo.uid);
8656                mProviders.addProvider(p);
8657                p.syncable = p.info.isSyncable;
8658                if (p.info.authority != null) {
8659                    String names[] = p.info.authority.split(";");
8660                    p.info.authority = null;
8661                    for (int j = 0; j < names.length; j++) {
8662                        if (j == 1 && p.syncable) {
8663                            // We only want the first authority for a provider to possibly be
8664                            // syncable, so if we already added this provider using a different
8665                            // authority clear the syncable flag. We copy the provider before
8666                            // changing it because the mProviders object contains a reference
8667                            // to a provider that we don't want to change.
8668                            // Only do this for the second authority since the resulting provider
8669                            // object can be the same for all future authorities for this provider.
8670                            p = new PackageParser.Provider(p);
8671                            p.syncable = false;
8672                        }
8673                        if (!mProvidersByAuthority.containsKey(names[j])) {
8674                            mProvidersByAuthority.put(names[j], p);
8675                            if (p.info.authority == null) {
8676                                p.info.authority = names[j];
8677                            } else {
8678                                p.info.authority = p.info.authority + ";" + names[j];
8679                            }
8680                            if (DEBUG_PACKAGE_SCANNING) {
8681                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8682                                    Log.d(TAG, "Registered content provider: " + names[j]
8683                                            + ", className = " + p.info.name + ", isSyncable = "
8684                                            + p.info.isSyncable);
8685                            }
8686                        } else {
8687                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8688                            Slog.w(TAG, "Skipping provider name " + names[j] +
8689                                    " (in package " + pkg.applicationInfo.packageName +
8690                                    "): name already used by "
8691                                    + ((other != null && other.getComponentName() != null)
8692                                            ? other.getComponentName().getPackageName() : "?"));
8693                        }
8694                    }
8695                }
8696                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8697                    if (r == null) {
8698                        r = new StringBuilder(256);
8699                    } else {
8700                        r.append(' ');
8701                    }
8702                    r.append(p.info.name);
8703                }
8704            }
8705            if (r != null) {
8706                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8707            }
8708
8709            N = pkg.services.size();
8710            r = null;
8711            for (i=0; i<N; i++) {
8712                PackageParser.Service s = pkg.services.get(i);
8713                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8714                        s.info.processName, pkg.applicationInfo.uid);
8715                mServices.addService(s);
8716                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8717                    if (r == null) {
8718                        r = new StringBuilder(256);
8719                    } else {
8720                        r.append(' ');
8721                    }
8722                    r.append(s.info.name);
8723                }
8724            }
8725            if (r != null) {
8726                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8727            }
8728
8729            N = pkg.receivers.size();
8730            r = null;
8731            for (i=0; i<N; i++) {
8732                PackageParser.Activity a = pkg.receivers.get(i);
8733                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8734                        a.info.processName, pkg.applicationInfo.uid);
8735                mReceivers.addActivity(a, "receiver");
8736                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8737                    if (r == null) {
8738                        r = new StringBuilder(256);
8739                    } else {
8740                        r.append(' ');
8741                    }
8742                    r.append(a.info.name);
8743                }
8744            }
8745            if (r != null) {
8746                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8747            }
8748
8749            N = pkg.activities.size();
8750            r = null;
8751            for (i=0; i<N; i++) {
8752                PackageParser.Activity a = pkg.activities.get(i);
8753                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8754                        a.info.processName, pkg.applicationInfo.uid);
8755                mActivities.addActivity(a, "activity");
8756                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8757                    if (r == null) {
8758                        r = new StringBuilder(256);
8759                    } else {
8760                        r.append(' ');
8761                    }
8762                    r.append(a.info.name);
8763                }
8764            }
8765            if (r != null) {
8766                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8767            }
8768
8769            N = pkg.permissionGroups.size();
8770            r = null;
8771            for (i=0; i<N; i++) {
8772                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8773                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8774                if (cur == null) {
8775                    mPermissionGroups.put(pg.info.name, pg);
8776                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8777                        if (r == null) {
8778                            r = new StringBuilder(256);
8779                        } else {
8780                            r.append(' ');
8781                        }
8782                        r.append(pg.info.name);
8783                    }
8784                } else {
8785                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8786                            + pg.info.packageName + " ignored: original from "
8787                            + cur.info.packageName);
8788                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8789                        if (r == null) {
8790                            r = new StringBuilder(256);
8791                        } else {
8792                            r.append(' ');
8793                        }
8794                        r.append("DUP:");
8795                        r.append(pg.info.name);
8796                    }
8797                }
8798            }
8799            if (r != null) {
8800                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8801            }
8802
8803            N = pkg.permissions.size();
8804            r = null;
8805            for (i=0; i<N; i++) {
8806                PackageParser.Permission p = pkg.permissions.get(i);
8807
8808                // Assume by default that we did not install this permission into the system.
8809                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8810
8811                // Now that permission groups have a special meaning, we ignore permission
8812                // groups for legacy apps to prevent unexpected behavior. In particular,
8813                // permissions for one app being granted to someone just becase they happen
8814                // to be in a group defined by another app (before this had no implications).
8815                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8816                    p.group = mPermissionGroups.get(p.info.group);
8817                    // Warn for a permission in an unknown group.
8818                    if (p.info.group != null && p.group == null) {
8819                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8820                                + p.info.packageName + " in an unknown group " + p.info.group);
8821                    }
8822                }
8823
8824                ArrayMap<String, BasePermission> permissionMap =
8825                        p.tree ? mSettings.mPermissionTrees
8826                                : mSettings.mPermissions;
8827                BasePermission bp = permissionMap.get(p.info.name);
8828
8829                // Allow system apps to redefine non-system permissions
8830                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8831                    final boolean currentOwnerIsSystem = (bp.perm != null
8832                            && isSystemApp(bp.perm.owner));
8833                    if (isSystemApp(p.owner)) {
8834                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8835                            // It's a built-in permission and no owner, take ownership now
8836                            bp.packageSetting = pkgSetting;
8837                            bp.perm = p;
8838                            bp.uid = pkg.applicationInfo.uid;
8839                            bp.sourcePackage = p.info.packageName;
8840                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8841                        } else if (!currentOwnerIsSystem) {
8842                            String msg = "New decl " + p.owner + " of permission  "
8843                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8844                            reportSettingsProblem(Log.WARN, msg);
8845                            bp = null;
8846                        }
8847                    }
8848                }
8849
8850                if (bp == null) {
8851                    bp = new BasePermission(p.info.name, p.info.packageName,
8852                            BasePermission.TYPE_NORMAL);
8853                    permissionMap.put(p.info.name, bp);
8854                }
8855
8856                if (bp.perm == null) {
8857                    if (bp.sourcePackage == null
8858                            || bp.sourcePackage.equals(p.info.packageName)) {
8859                        BasePermission tree = findPermissionTreeLP(p.info.name);
8860                        if (tree == null
8861                                || tree.sourcePackage.equals(p.info.packageName)) {
8862                            bp.packageSetting = pkgSetting;
8863                            bp.perm = p;
8864                            bp.uid = pkg.applicationInfo.uid;
8865                            bp.sourcePackage = p.info.packageName;
8866                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8867                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8868                                if (r == null) {
8869                                    r = new StringBuilder(256);
8870                                } else {
8871                                    r.append(' ');
8872                                }
8873                                r.append(p.info.name);
8874                            }
8875                        } else {
8876                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8877                                    + p.info.packageName + " ignored: base tree "
8878                                    + tree.name + " is from package "
8879                                    + tree.sourcePackage);
8880                        }
8881                    } else {
8882                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8883                                + p.info.packageName + " ignored: original from "
8884                                + bp.sourcePackage);
8885                    }
8886                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8887                    if (r == null) {
8888                        r = new StringBuilder(256);
8889                    } else {
8890                        r.append(' ');
8891                    }
8892                    r.append("DUP:");
8893                    r.append(p.info.name);
8894                }
8895                if (bp.perm == p) {
8896                    bp.protectionLevel = p.info.protectionLevel;
8897                }
8898            }
8899
8900            if (r != null) {
8901                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8902            }
8903
8904            N = pkg.instrumentation.size();
8905            r = null;
8906            for (i=0; i<N; i++) {
8907                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8908                a.info.packageName = pkg.applicationInfo.packageName;
8909                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8910                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8911                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8912                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8913                a.info.dataDir = pkg.applicationInfo.dataDir;
8914                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8915                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8916
8917                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8918                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8919                mInstrumentation.put(a.getComponentName(), a);
8920                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8921                    if (r == null) {
8922                        r = new StringBuilder(256);
8923                    } else {
8924                        r.append(' ');
8925                    }
8926                    r.append(a.info.name);
8927                }
8928            }
8929            if (r != null) {
8930                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8931            }
8932
8933            if (pkg.protectedBroadcasts != null) {
8934                N = pkg.protectedBroadcasts.size();
8935                for (i=0; i<N; i++) {
8936                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8937                }
8938            }
8939
8940            pkgSetting.setTimeStamp(scanFileTime);
8941
8942            // Create idmap files for pairs of (packages, overlay packages).
8943            // Note: "android", ie framework-res.apk, is handled by native layers.
8944            if (pkg.mOverlayTarget != null) {
8945                // This is an overlay package.
8946                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8947                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8948                        mOverlays.put(pkg.mOverlayTarget,
8949                                new ArrayMap<String, PackageParser.Package>());
8950                    }
8951                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8952                    map.put(pkg.packageName, pkg);
8953                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8954                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8955                        createIdmapFailed = true;
8956                    }
8957                }
8958            } else if (mOverlays.containsKey(pkg.packageName) &&
8959                    !pkg.packageName.equals("android")) {
8960                // This is a regular package, with one or more known overlay packages.
8961                createIdmapsForPackageLI(pkg);
8962            }
8963        }
8964
8965        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8966
8967        if (createIdmapFailed) {
8968            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8969                    "scanPackageLI failed to createIdmap");
8970        }
8971        return pkg;
8972    }
8973
8974    /**
8975     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8976     * is derived purely on the basis of the contents of {@code scanFile} and
8977     * {@code cpuAbiOverride}.
8978     *
8979     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8980     */
8981    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8982                                 String cpuAbiOverride, boolean extractLibs)
8983            throws PackageManagerException {
8984        // TODO: We can probably be smarter about this stuff. For installed apps,
8985        // we can calculate this information at install time once and for all. For
8986        // system apps, we can probably assume that this information doesn't change
8987        // after the first boot scan. As things stand, we do lots of unnecessary work.
8988
8989        // Give ourselves some initial paths; we'll come back for another
8990        // pass once we've determined ABI below.
8991        setNativeLibraryPaths(pkg);
8992
8993        // We would never need to extract libs for forward-locked and external packages,
8994        // since the container service will do it for us. We shouldn't attempt to
8995        // extract libs from system app when it was not updated.
8996        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8997                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8998            extractLibs = false;
8999        }
9000
9001        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9002        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9003
9004        NativeLibraryHelper.Handle handle = null;
9005        try {
9006            handle = NativeLibraryHelper.Handle.create(pkg);
9007            // TODO(multiArch): This can be null for apps that didn't go through the
9008            // usual installation process. We can calculate it again, like we
9009            // do during install time.
9010            //
9011            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9012            // unnecessary.
9013            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9014
9015            // Null out the abis so that they can be recalculated.
9016            pkg.applicationInfo.primaryCpuAbi = null;
9017            pkg.applicationInfo.secondaryCpuAbi = null;
9018            if (isMultiArch(pkg.applicationInfo)) {
9019                // Warn if we've set an abiOverride for multi-lib packages..
9020                // By definition, we need to copy both 32 and 64 bit libraries for
9021                // such packages.
9022                if (pkg.cpuAbiOverride != null
9023                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9024                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9025                }
9026
9027                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9028                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9029                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9030                    if (extractLibs) {
9031                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9032                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9033                                useIsaSpecificSubdirs);
9034                    } else {
9035                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9036                    }
9037                }
9038
9039                maybeThrowExceptionForMultiArchCopy(
9040                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9041
9042                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9043                    if (extractLibs) {
9044                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9045                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9046                                useIsaSpecificSubdirs);
9047                    } else {
9048                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9049                    }
9050                }
9051
9052                maybeThrowExceptionForMultiArchCopy(
9053                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9054
9055                if (abi64 >= 0) {
9056                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9057                }
9058
9059                if (abi32 >= 0) {
9060                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9061                    if (abi64 >= 0) {
9062                        if (pkg.use32bitAbi) {
9063                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9064                            pkg.applicationInfo.primaryCpuAbi = abi;
9065                        } else {
9066                            pkg.applicationInfo.secondaryCpuAbi = abi;
9067                        }
9068                    } else {
9069                        pkg.applicationInfo.primaryCpuAbi = abi;
9070                    }
9071                }
9072
9073            } else {
9074                String[] abiList = (cpuAbiOverride != null) ?
9075                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9076
9077                // Enable gross and lame hacks for apps that are built with old
9078                // SDK tools. We must scan their APKs for renderscript bitcode and
9079                // not launch them if it's present. Don't bother checking on devices
9080                // that don't have 64 bit support.
9081                boolean needsRenderScriptOverride = false;
9082                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9083                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9084                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9085                    needsRenderScriptOverride = true;
9086                }
9087
9088                final int copyRet;
9089                if (extractLibs) {
9090                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9091                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9092                } else {
9093                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9094                }
9095
9096                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9097                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9098                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9099                }
9100
9101                if (copyRet >= 0) {
9102                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9103                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9104                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9105                } else if (needsRenderScriptOverride) {
9106                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9107                }
9108            }
9109        } catch (IOException ioe) {
9110            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9111        } finally {
9112            IoUtils.closeQuietly(handle);
9113        }
9114
9115        // Now that we've calculated the ABIs and determined if it's an internal app,
9116        // we will go ahead and populate the nativeLibraryPath.
9117        setNativeLibraryPaths(pkg);
9118    }
9119
9120    /**
9121     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9122     * i.e, so that all packages can be run inside a single process if required.
9123     *
9124     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9125     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9126     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9127     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9128     * updating a package that belongs to a shared user.
9129     *
9130     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9131     * adds unnecessary complexity.
9132     */
9133    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9134            PackageParser.Package scannedPackage, boolean bootComplete) {
9135        String requiredInstructionSet = null;
9136        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9137            requiredInstructionSet = VMRuntime.getInstructionSet(
9138                     scannedPackage.applicationInfo.primaryCpuAbi);
9139        }
9140
9141        PackageSetting requirer = null;
9142        for (PackageSetting ps : packagesForUser) {
9143            // If packagesForUser contains scannedPackage, we skip it. This will happen
9144            // when scannedPackage is an update of an existing package. Without this check,
9145            // we will never be able to change the ABI of any package belonging to a shared
9146            // user, even if it's compatible with other packages.
9147            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9148                if (ps.primaryCpuAbiString == null) {
9149                    continue;
9150                }
9151
9152                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9153                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9154                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9155                    // this but there's not much we can do.
9156                    String errorMessage = "Instruction set mismatch, "
9157                            + ((requirer == null) ? "[caller]" : requirer)
9158                            + " requires " + requiredInstructionSet + " whereas " + ps
9159                            + " requires " + instructionSet;
9160                    Slog.w(TAG, errorMessage);
9161                }
9162
9163                if (requiredInstructionSet == null) {
9164                    requiredInstructionSet = instructionSet;
9165                    requirer = ps;
9166                }
9167            }
9168        }
9169
9170        if (requiredInstructionSet != null) {
9171            String adjustedAbi;
9172            if (requirer != null) {
9173                // requirer != null implies that either scannedPackage was null or that scannedPackage
9174                // did not require an ABI, in which case we have to adjust scannedPackage to match
9175                // the ABI of the set (which is the same as requirer's ABI)
9176                adjustedAbi = requirer.primaryCpuAbiString;
9177                if (scannedPackage != null) {
9178                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9179                }
9180            } else {
9181                // requirer == null implies that we're updating all ABIs in the set to
9182                // match scannedPackage.
9183                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9184            }
9185
9186            for (PackageSetting ps : packagesForUser) {
9187                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9188                    if (ps.primaryCpuAbiString != null) {
9189                        continue;
9190                    }
9191
9192                    ps.primaryCpuAbiString = adjustedAbi;
9193                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9194                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9195                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9196                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9197                                + " (requirer="
9198                                + (requirer == null ? "null" : requirer.pkg.packageName)
9199                                + ", scannedPackage="
9200                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9201                                + ")");
9202                        try {
9203                            mInstaller.rmdex(ps.codePathString,
9204                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9205                        } catch (InstallerException ignored) {
9206                        }
9207                    }
9208                }
9209            }
9210        }
9211    }
9212
9213    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9214        synchronized (mPackages) {
9215            mResolverReplaced = true;
9216            // Set up information for custom user intent resolution activity.
9217            mResolveActivity.applicationInfo = pkg.applicationInfo;
9218            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9219            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9220            mResolveActivity.processName = pkg.applicationInfo.packageName;
9221            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9222            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9223                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9224            mResolveActivity.theme = 0;
9225            mResolveActivity.exported = true;
9226            mResolveActivity.enabled = true;
9227            mResolveInfo.activityInfo = mResolveActivity;
9228            mResolveInfo.priority = 0;
9229            mResolveInfo.preferredOrder = 0;
9230            mResolveInfo.match = 0;
9231            mResolveComponentName = mCustomResolverComponentName;
9232            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9233                    mResolveComponentName);
9234        }
9235    }
9236
9237    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9238        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9239
9240        // Set up information for ephemeral installer activity
9241        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9242        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9243        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9244        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9245        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9246        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9247                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9248        mEphemeralInstallerActivity.theme = 0;
9249        mEphemeralInstallerActivity.exported = true;
9250        mEphemeralInstallerActivity.enabled = true;
9251        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9252        mEphemeralInstallerInfo.priority = 0;
9253        mEphemeralInstallerInfo.preferredOrder = 0;
9254        mEphemeralInstallerInfo.match = 0;
9255
9256        if (DEBUG_EPHEMERAL) {
9257            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9258        }
9259    }
9260
9261    private static String calculateBundledApkRoot(final String codePathString) {
9262        final File codePath = new File(codePathString);
9263        final File codeRoot;
9264        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9265            codeRoot = Environment.getRootDirectory();
9266        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9267            codeRoot = Environment.getOemDirectory();
9268        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9269            codeRoot = Environment.getVendorDirectory();
9270        } else {
9271            // Unrecognized code path; take its top real segment as the apk root:
9272            // e.g. /something/app/blah.apk => /something
9273            try {
9274                File f = codePath.getCanonicalFile();
9275                File parent = f.getParentFile();    // non-null because codePath is a file
9276                File tmp;
9277                while ((tmp = parent.getParentFile()) != null) {
9278                    f = parent;
9279                    parent = tmp;
9280                }
9281                codeRoot = f;
9282                Slog.w(TAG, "Unrecognized code path "
9283                        + codePath + " - using " + codeRoot);
9284            } catch (IOException e) {
9285                // Can't canonicalize the code path -- shenanigans?
9286                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9287                return Environment.getRootDirectory().getPath();
9288            }
9289        }
9290        return codeRoot.getPath();
9291    }
9292
9293    /**
9294     * Derive and set the location of native libraries for the given package,
9295     * which varies depending on where and how the package was installed.
9296     */
9297    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9298        final ApplicationInfo info = pkg.applicationInfo;
9299        final String codePath = pkg.codePath;
9300        final File codeFile = new File(codePath);
9301        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9302        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9303
9304        info.nativeLibraryRootDir = null;
9305        info.nativeLibraryRootRequiresIsa = false;
9306        info.nativeLibraryDir = null;
9307        info.secondaryNativeLibraryDir = null;
9308
9309        if (isApkFile(codeFile)) {
9310            // Monolithic install
9311            if (bundledApp) {
9312                // If "/system/lib64/apkname" exists, assume that is the per-package
9313                // native library directory to use; otherwise use "/system/lib/apkname".
9314                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9315                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9316                        getPrimaryInstructionSet(info));
9317
9318                // This is a bundled system app so choose the path based on the ABI.
9319                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9320                // is just the default path.
9321                final String apkName = deriveCodePathName(codePath);
9322                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9323                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9324                        apkName).getAbsolutePath();
9325
9326                if (info.secondaryCpuAbi != null) {
9327                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9328                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9329                            secondaryLibDir, apkName).getAbsolutePath();
9330                }
9331            } else if (asecApp) {
9332                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9333                        .getAbsolutePath();
9334            } else {
9335                final String apkName = deriveCodePathName(codePath);
9336                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9337                        .getAbsolutePath();
9338            }
9339
9340            info.nativeLibraryRootRequiresIsa = false;
9341            info.nativeLibraryDir = info.nativeLibraryRootDir;
9342        } else {
9343            // Cluster install
9344            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9345            info.nativeLibraryRootRequiresIsa = true;
9346
9347            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9348                    getPrimaryInstructionSet(info)).getAbsolutePath();
9349
9350            if (info.secondaryCpuAbi != null) {
9351                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9352                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9353            }
9354        }
9355    }
9356
9357    /**
9358     * Calculate the abis and roots for a bundled app. These can uniquely
9359     * be determined from the contents of the system partition, i.e whether
9360     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9361     * of this information, and instead assume that the system was built
9362     * sensibly.
9363     */
9364    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9365                                           PackageSetting pkgSetting) {
9366        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9367
9368        // If "/system/lib64/apkname" exists, assume that is the per-package
9369        // native library directory to use; otherwise use "/system/lib/apkname".
9370        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9371        setBundledAppAbi(pkg, apkRoot, apkName);
9372        // pkgSetting might be null during rescan following uninstall of updates
9373        // to a bundled app, so accommodate that possibility.  The settings in
9374        // that case will be established later from the parsed package.
9375        //
9376        // If the settings aren't null, sync them up with what we've just derived.
9377        // note that apkRoot isn't stored in the package settings.
9378        if (pkgSetting != null) {
9379            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9380            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9381        }
9382    }
9383
9384    /**
9385     * Deduces the ABI of a bundled app and sets the relevant fields on the
9386     * parsed pkg object.
9387     *
9388     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9389     *        under which system libraries are installed.
9390     * @param apkName the name of the installed package.
9391     */
9392    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9393        final File codeFile = new File(pkg.codePath);
9394
9395        final boolean has64BitLibs;
9396        final boolean has32BitLibs;
9397        if (isApkFile(codeFile)) {
9398            // Monolithic install
9399            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9400            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9401        } else {
9402            // Cluster install
9403            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9404            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9405                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9406                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9407                has64BitLibs = (new File(rootDir, isa)).exists();
9408            } else {
9409                has64BitLibs = false;
9410            }
9411            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9412                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9413                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9414                has32BitLibs = (new File(rootDir, isa)).exists();
9415            } else {
9416                has32BitLibs = false;
9417            }
9418        }
9419
9420        if (has64BitLibs && !has32BitLibs) {
9421            // The package has 64 bit libs, but not 32 bit libs. Its primary
9422            // ABI should be 64 bit. We can safely assume here that the bundled
9423            // native libraries correspond to the most preferred ABI in the list.
9424
9425            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9426            pkg.applicationInfo.secondaryCpuAbi = null;
9427        } else if (has32BitLibs && !has64BitLibs) {
9428            // The package has 32 bit libs but not 64 bit libs. Its primary
9429            // ABI should be 32 bit.
9430
9431            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9432            pkg.applicationInfo.secondaryCpuAbi = null;
9433        } else if (has32BitLibs && has64BitLibs) {
9434            // The application has both 64 and 32 bit bundled libraries. We check
9435            // here that the app declares multiArch support, and warn if it doesn't.
9436            //
9437            // We will be lenient here and record both ABIs. The primary will be the
9438            // ABI that's higher on the list, i.e, a device that's configured to prefer
9439            // 64 bit apps will see a 64 bit primary ABI,
9440
9441            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9442                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9443            }
9444
9445            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9446                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9447                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9448            } else {
9449                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9450                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9451            }
9452        } else {
9453            pkg.applicationInfo.primaryCpuAbi = null;
9454            pkg.applicationInfo.secondaryCpuAbi = null;
9455        }
9456    }
9457
9458    private void killApplication(String pkgName, int appId, String reason) {
9459        // Request the ActivityManager to kill the process(only for existing packages)
9460        // so that we do not end up in a confused state while the user is still using the older
9461        // version of the application while the new one gets installed.
9462        final long token = Binder.clearCallingIdentity();
9463        try {
9464            IActivityManager am = ActivityManagerNative.getDefault();
9465            if (am != null) {
9466                try {
9467                    am.killApplicationWithAppId(pkgName, appId, reason);
9468                } catch (RemoteException e) {
9469                }
9470            }
9471        } finally {
9472            Binder.restoreCallingIdentity(token);
9473        }
9474    }
9475
9476    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9477        // Remove the parent package setting
9478        PackageSetting ps = (PackageSetting) pkg.mExtras;
9479        if (ps != null) {
9480            removePackageLI(ps, chatty);
9481        }
9482        // Remove the child package setting
9483        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9484        for (int i = 0; i < childCount; i++) {
9485            PackageParser.Package childPkg = pkg.childPackages.get(i);
9486            ps = (PackageSetting) childPkg.mExtras;
9487            if (ps != null) {
9488                removePackageLI(ps, chatty);
9489            }
9490        }
9491    }
9492
9493    void removePackageLI(PackageSetting ps, boolean chatty) {
9494        if (DEBUG_INSTALL) {
9495            if (chatty)
9496                Log.d(TAG, "Removing package " + ps.name);
9497        }
9498
9499        // writer
9500        synchronized (mPackages) {
9501            mPackages.remove(ps.name);
9502            final PackageParser.Package pkg = ps.pkg;
9503            if (pkg != null) {
9504                cleanPackageDataStructuresLILPw(pkg, chatty);
9505            }
9506        }
9507    }
9508
9509    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9510        if (DEBUG_INSTALL) {
9511            if (chatty)
9512                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9513        }
9514
9515        // writer
9516        synchronized (mPackages) {
9517            // Remove the parent package
9518            mPackages.remove(pkg.applicationInfo.packageName);
9519            cleanPackageDataStructuresLILPw(pkg, chatty);
9520
9521            // Remove the child packages
9522            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9523            for (int i = 0; i < childCount; i++) {
9524                PackageParser.Package childPkg = pkg.childPackages.get(i);
9525                mPackages.remove(childPkg.applicationInfo.packageName);
9526                cleanPackageDataStructuresLILPw(childPkg, chatty);
9527            }
9528        }
9529    }
9530
9531    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9532        int N = pkg.providers.size();
9533        StringBuilder r = null;
9534        int i;
9535        for (i=0; i<N; i++) {
9536            PackageParser.Provider p = pkg.providers.get(i);
9537            mProviders.removeProvider(p);
9538            if (p.info.authority == null) {
9539
9540                /* There was another ContentProvider with this authority when
9541                 * this app was installed so this authority is null,
9542                 * Ignore it as we don't have to unregister the provider.
9543                 */
9544                continue;
9545            }
9546            String names[] = p.info.authority.split(";");
9547            for (int j = 0; j < names.length; j++) {
9548                if (mProvidersByAuthority.get(names[j]) == p) {
9549                    mProvidersByAuthority.remove(names[j]);
9550                    if (DEBUG_REMOVE) {
9551                        if (chatty)
9552                            Log.d(TAG, "Unregistered content provider: " + names[j]
9553                                    + ", className = " + p.info.name + ", isSyncable = "
9554                                    + p.info.isSyncable);
9555                    }
9556                }
9557            }
9558            if (DEBUG_REMOVE && chatty) {
9559                if (r == null) {
9560                    r = new StringBuilder(256);
9561                } else {
9562                    r.append(' ');
9563                }
9564                r.append(p.info.name);
9565            }
9566        }
9567        if (r != null) {
9568            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9569        }
9570
9571        N = pkg.services.size();
9572        r = null;
9573        for (i=0; i<N; i++) {
9574            PackageParser.Service s = pkg.services.get(i);
9575            mServices.removeService(s);
9576            if (chatty) {
9577                if (r == null) {
9578                    r = new StringBuilder(256);
9579                } else {
9580                    r.append(' ');
9581                }
9582                r.append(s.info.name);
9583            }
9584        }
9585        if (r != null) {
9586            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9587        }
9588
9589        N = pkg.receivers.size();
9590        r = null;
9591        for (i=0; i<N; i++) {
9592            PackageParser.Activity a = pkg.receivers.get(i);
9593            mReceivers.removeActivity(a, "receiver");
9594            if (DEBUG_REMOVE && chatty) {
9595                if (r == null) {
9596                    r = new StringBuilder(256);
9597                } else {
9598                    r.append(' ');
9599                }
9600                r.append(a.info.name);
9601            }
9602        }
9603        if (r != null) {
9604            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9605        }
9606
9607        N = pkg.activities.size();
9608        r = null;
9609        for (i=0; i<N; i++) {
9610            PackageParser.Activity a = pkg.activities.get(i);
9611            mActivities.removeActivity(a, "activity");
9612            if (DEBUG_REMOVE && chatty) {
9613                if (r == null) {
9614                    r = new StringBuilder(256);
9615                } else {
9616                    r.append(' ');
9617                }
9618                r.append(a.info.name);
9619            }
9620        }
9621        if (r != null) {
9622            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9623        }
9624
9625        N = pkg.permissions.size();
9626        r = null;
9627        for (i=0; i<N; i++) {
9628            PackageParser.Permission p = pkg.permissions.get(i);
9629            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9630            if (bp == null) {
9631                bp = mSettings.mPermissionTrees.get(p.info.name);
9632            }
9633            if (bp != null && bp.perm == p) {
9634                bp.perm = null;
9635                if (DEBUG_REMOVE && chatty) {
9636                    if (r == null) {
9637                        r = new StringBuilder(256);
9638                    } else {
9639                        r.append(' ');
9640                    }
9641                    r.append(p.info.name);
9642                }
9643            }
9644            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9645                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9646                if (appOpPkgs != null) {
9647                    appOpPkgs.remove(pkg.packageName);
9648                }
9649            }
9650        }
9651        if (r != null) {
9652            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9653        }
9654
9655        N = pkg.requestedPermissions.size();
9656        r = null;
9657        for (i=0; i<N; i++) {
9658            String perm = pkg.requestedPermissions.get(i);
9659            BasePermission bp = mSettings.mPermissions.get(perm);
9660            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9661                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9662                if (appOpPkgs != null) {
9663                    appOpPkgs.remove(pkg.packageName);
9664                    if (appOpPkgs.isEmpty()) {
9665                        mAppOpPermissionPackages.remove(perm);
9666                    }
9667                }
9668            }
9669        }
9670        if (r != null) {
9671            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9672        }
9673
9674        N = pkg.instrumentation.size();
9675        r = null;
9676        for (i=0; i<N; i++) {
9677            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9678            mInstrumentation.remove(a.getComponentName());
9679            if (DEBUG_REMOVE && chatty) {
9680                if (r == null) {
9681                    r = new StringBuilder(256);
9682                } else {
9683                    r.append(' ');
9684                }
9685                r.append(a.info.name);
9686            }
9687        }
9688        if (r != null) {
9689            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9690        }
9691
9692        r = null;
9693        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9694            // Only system apps can hold shared libraries.
9695            if (pkg.libraryNames != null) {
9696                for (i=0; i<pkg.libraryNames.size(); i++) {
9697                    String name = pkg.libraryNames.get(i);
9698                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9699                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9700                        mSharedLibraries.remove(name);
9701                        if (DEBUG_REMOVE && chatty) {
9702                            if (r == null) {
9703                                r = new StringBuilder(256);
9704                            } else {
9705                                r.append(' ');
9706                            }
9707                            r.append(name);
9708                        }
9709                    }
9710                }
9711            }
9712        }
9713        if (r != null) {
9714            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9715        }
9716    }
9717
9718    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9719        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9720            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9721                return true;
9722            }
9723        }
9724        return false;
9725    }
9726
9727    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9728    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9729    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9730
9731    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9732        // Update the parent permissions
9733        updatePermissionsLPw(pkg.packageName, pkg, flags);
9734        // Update the child permissions
9735        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9736        for (int i = 0; i < childCount; i++) {
9737            PackageParser.Package childPkg = pkg.childPackages.get(i);
9738            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9739        }
9740    }
9741
9742    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9743            int flags) {
9744        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9745        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9746    }
9747
9748    private void updatePermissionsLPw(String changingPkg,
9749            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9750        // Make sure there are no dangling permission trees.
9751        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9752        while (it.hasNext()) {
9753            final BasePermission bp = it.next();
9754            if (bp.packageSetting == null) {
9755                // We may not yet have parsed the package, so just see if
9756                // we still know about its settings.
9757                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9758            }
9759            if (bp.packageSetting == null) {
9760                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9761                        + " from package " + bp.sourcePackage);
9762                it.remove();
9763            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9764                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9765                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9766                            + " from package " + bp.sourcePackage);
9767                    flags |= UPDATE_PERMISSIONS_ALL;
9768                    it.remove();
9769                }
9770            }
9771        }
9772
9773        // Make sure all dynamic permissions have been assigned to a package,
9774        // and make sure there are no dangling permissions.
9775        it = mSettings.mPermissions.values().iterator();
9776        while (it.hasNext()) {
9777            final BasePermission bp = it.next();
9778            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9779                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9780                        + bp.name + " pkg=" + bp.sourcePackage
9781                        + " info=" + bp.pendingInfo);
9782                if (bp.packageSetting == null && bp.pendingInfo != null) {
9783                    final BasePermission tree = findPermissionTreeLP(bp.name);
9784                    if (tree != null && tree.perm != null) {
9785                        bp.packageSetting = tree.packageSetting;
9786                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9787                                new PermissionInfo(bp.pendingInfo));
9788                        bp.perm.info.packageName = tree.perm.info.packageName;
9789                        bp.perm.info.name = bp.name;
9790                        bp.uid = tree.uid;
9791                    }
9792                }
9793            }
9794            if (bp.packageSetting == null) {
9795                // We may not yet have parsed the package, so just see if
9796                // we still know about its settings.
9797                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9798            }
9799            if (bp.packageSetting == null) {
9800                Slog.w(TAG, "Removing dangling permission: " + bp.name
9801                        + " from package " + bp.sourcePackage);
9802                it.remove();
9803            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9804                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9805                    Slog.i(TAG, "Removing old permission: " + bp.name
9806                            + " from package " + bp.sourcePackage);
9807                    flags |= UPDATE_PERMISSIONS_ALL;
9808                    it.remove();
9809                }
9810            }
9811        }
9812
9813        // Now update the permissions for all packages, in particular
9814        // replace the granted permissions of the system packages.
9815        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9816            for (PackageParser.Package pkg : mPackages.values()) {
9817                if (pkg != pkgInfo) {
9818                    // Only replace for packages on requested volume
9819                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9820                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9821                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9822                    grantPermissionsLPw(pkg, replace, changingPkg);
9823                }
9824            }
9825        }
9826
9827        if (pkgInfo != null) {
9828            // Only replace for packages on requested volume
9829            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9830            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9831                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9832            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9833        }
9834    }
9835
9836    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9837            String packageOfInterest) {
9838        // IMPORTANT: There are two types of permissions: install and runtime.
9839        // Install time permissions are granted when the app is installed to
9840        // all device users and users added in the future. Runtime permissions
9841        // are granted at runtime explicitly to specific users. Normal and signature
9842        // protected permissions are install time permissions. Dangerous permissions
9843        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9844        // otherwise they are runtime permissions. This function does not manage
9845        // runtime permissions except for the case an app targeting Lollipop MR1
9846        // being upgraded to target a newer SDK, in which case dangerous permissions
9847        // are transformed from install time to runtime ones.
9848
9849        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9850        if (ps == null) {
9851            return;
9852        }
9853
9854        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9855
9856        PermissionsState permissionsState = ps.getPermissionsState();
9857        PermissionsState origPermissions = permissionsState;
9858
9859        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9860
9861        boolean runtimePermissionsRevoked = false;
9862        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9863
9864        boolean changedInstallPermission = false;
9865
9866        if (replace) {
9867            ps.installPermissionsFixed = false;
9868            if (!ps.isSharedUser()) {
9869                origPermissions = new PermissionsState(permissionsState);
9870                permissionsState.reset();
9871            } else {
9872                // We need to know only about runtime permission changes since the
9873                // calling code always writes the install permissions state but
9874                // the runtime ones are written only if changed. The only cases of
9875                // changed runtime permissions here are promotion of an install to
9876                // runtime and revocation of a runtime from a shared user.
9877                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9878                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9879                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9880                    runtimePermissionsRevoked = true;
9881                }
9882            }
9883        }
9884
9885        permissionsState.setGlobalGids(mGlobalGids);
9886
9887        final int N = pkg.requestedPermissions.size();
9888        for (int i=0; i<N; i++) {
9889            final String name = pkg.requestedPermissions.get(i);
9890            final BasePermission bp = mSettings.mPermissions.get(name);
9891
9892            if (DEBUG_INSTALL) {
9893                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9894            }
9895
9896            if (bp == null || bp.packageSetting == null) {
9897                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9898                    Slog.w(TAG, "Unknown permission " + name
9899                            + " in package " + pkg.packageName);
9900                }
9901                continue;
9902            }
9903
9904            final String perm = bp.name;
9905            boolean allowedSig = false;
9906            int grant = GRANT_DENIED;
9907
9908            // Keep track of app op permissions.
9909            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9910                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9911                if (pkgs == null) {
9912                    pkgs = new ArraySet<>();
9913                    mAppOpPermissionPackages.put(bp.name, pkgs);
9914                }
9915                pkgs.add(pkg.packageName);
9916            }
9917
9918            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9919            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9920                    >= Build.VERSION_CODES.M;
9921            switch (level) {
9922                case PermissionInfo.PROTECTION_NORMAL: {
9923                    // For all apps normal permissions are install time ones.
9924                    grant = GRANT_INSTALL;
9925                } break;
9926
9927                case PermissionInfo.PROTECTION_DANGEROUS: {
9928                    // If a permission review is required for legacy apps we represent
9929                    // their permissions as always granted runtime ones since we need
9930                    // to keep the review required permission flag per user while an
9931                    // install permission's state is shared across all users.
9932                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9933                        // For legacy apps dangerous permissions are install time ones.
9934                        grant = GRANT_INSTALL;
9935                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9936                        // For legacy apps that became modern, install becomes runtime.
9937                        grant = GRANT_UPGRADE;
9938                    } else if (mPromoteSystemApps
9939                            && isSystemApp(ps)
9940                            && mExistingSystemPackages.contains(ps.name)) {
9941                        // For legacy system apps, install becomes runtime.
9942                        // We cannot check hasInstallPermission() for system apps since those
9943                        // permissions were granted implicitly and not persisted pre-M.
9944                        grant = GRANT_UPGRADE;
9945                    } else {
9946                        // For modern apps keep runtime permissions unchanged.
9947                        grant = GRANT_RUNTIME;
9948                    }
9949                } break;
9950
9951                case PermissionInfo.PROTECTION_SIGNATURE: {
9952                    // For all apps signature permissions are install time ones.
9953                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9954                    if (allowedSig) {
9955                        grant = GRANT_INSTALL;
9956                    }
9957                } break;
9958            }
9959
9960            if (DEBUG_INSTALL) {
9961                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9962            }
9963
9964            if (grant != GRANT_DENIED) {
9965                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9966                    // If this is an existing, non-system package, then
9967                    // we can't add any new permissions to it.
9968                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9969                        // Except...  if this is a permission that was added
9970                        // to the platform (note: need to only do this when
9971                        // updating the platform).
9972                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9973                            grant = GRANT_DENIED;
9974                        }
9975                    }
9976                }
9977
9978                switch (grant) {
9979                    case GRANT_INSTALL: {
9980                        // Revoke this as runtime permission to handle the case of
9981                        // a runtime permission being downgraded to an install one.
9982                        // Also in permission review mode we keep dangerous permissions
9983                        // for legacy apps
9984                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9985                            if (origPermissions.getRuntimePermissionState(
9986                                    bp.name, userId) != null) {
9987                                // Revoke the runtime permission and clear the flags.
9988                                origPermissions.revokeRuntimePermission(bp, userId);
9989                                origPermissions.updatePermissionFlags(bp, userId,
9990                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9991                                // If we revoked a permission permission, we have to write.
9992                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9993                                        changedRuntimePermissionUserIds, userId);
9994                            }
9995                        }
9996                        // Grant an install permission.
9997                        if (permissionsState.grantInstallPermission(bp) !=
9998                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9999                            changedInstallPermission = true;
10000                        }
10001                    } break;
10002
10003                    case GRANT_RUNTIME: {
10004                        // Grant previously granted runtime permissions.
10005                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10006                            PermissionState permissionState = origPermissions
10007                                    .getRuntimePermissionState(bp.name, userId);
10008                            int flags = permissionState != null
10009                                    ? permissionState.getFlags() : 0;
10010                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10011                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10012                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10013                                    // If we cannot put the permission as it was, we have to write.
10014                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10015                                            changedRuntimePermissionUserIds, userId);
10016                                }
10017                                // If the app supports runtime permissions no need for a review.
10018                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10019                                        && appSupportsRuntimePermissions
10020                                        && (flags & PackageManager
10021                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10022                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10023                                    // Since we changed the flags, we have to write.
10024                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10025                                            changedRuntimePermissionUserIds, userId);
10026                                }
10027                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10028                                    && !appSupportsRuntimePermissions) {
10029                                // For legacy apps that need a permission review, every new
10030                                // runtime permission is granted but it is pending a review.
10031                                // We also need to review only platform defined runtime
10032                                // permissions as these are the only ones the platform knows
10033                                // how to disable the API to simulate revocation as legacy
10034                                // apps don't expect to run with revoked permissions.
10035                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10036                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10037                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10038                                        // We changed the flags, hence have to write.
10039                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10040                                                changedRuntimePermissionUserIds, userId);
10041                                    }
10042                                }
10043                                if (permissionsState.grantRuntimePermission(bp, userId)
10044                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10045                                    // We changed the permission, hence have to write.
10046                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10047                                            changedRuntimePermissionUserIds, userId);
10048                                }
10049                            }
10050                            // Propagate the permission flags.
10051                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10052                        }
10053                    } break;
10054
10055                    case GRANT_UPGRADE: {
10056                        // Grant runtime permissions for a previously held install permission.
10057                        PermissionState permissionState = origPermissions
10058                                .getInstallPermissionState(bp.name);
10059                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10060
10061                        if (origPermissions.revokeInstallPermission(bp)
10062                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10063                            // We will be transferring the permission flags, so clear them.
10064                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10065                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10066                            changedInstallPermission = true;
10067                        }
10068
10069                        // If the permission is not to be promoted to runtime we ignore it and
10070                        // also its other flags as they are not applicable to install permissions.
10071                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10072                            for (int userId : currentUserIds) {
10073                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10074                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10075                                    // Transfer the permission flags.
10076                                    permissionsState.updatePermissionFlags(bp, userId,
10077                                            flags, flags);
10078                                    // If we granted the permission, we have to write.
10079                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10080                                            changedRuntimePermissionUserIds, userId);
10081                                }
10082                            }
10083                        }
10084                    } break;
10085
10086                    default: {
10087                        if (packageOfInterest == null
10088                                || packageOfInterest.equals(pkg.packageName)) {
10089                            Slog.w(TAG, "Not granting permission " + perm
10090                                    + " to package " + pkg.packageName
10091                                    + " because it was previously installed without");
10092                        }
10093                    } break;
10094                }
10095            } else {
10096                if (permissionsState.revokeInstallPermission(bp) !=
10097                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10098                    // Also drop the permission flags.
10099                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10100                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10101                    changedInstallPermission = true;
10102                    Slog.i(TAG, "Un-granting permission " + perm
10103                            + " from package " + pkg.packageName
10104                            + " (protectionLevel=" + bp.protectionLevel
10105                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10106                            + ")");
10107                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10108                    // Don't print warning for app op permissions, since it is fine for them
10109                    // not to be granted, there is a UI for the user to decide.
10110                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10111                        Slog.w(TAG, "Not granting permission " + perm
10112                                + " to package " + pkg.packageName
10113                                + " (protectionLevel=" + bp.protectionLevel
10114                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10115                                + ")");
10116                    }
10117                }
10118            }
10119        }
10120
10121        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10122                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10123            // This is the first that we have heard about this package, so the
10124            // permissions we have now selected are fixed until explicitly
10125            // changed.
10126            ps.installPermissionsFixed = true;
10127        }
10128
10129        // Persist the runtime permissions state for users with changes. If permissions
10130        // were revoked because no app in the shared user declares them we have to
10131        // write synchronously to avoid losing runtime permissions state.
10132        for (int userId : changedRuntimePermissionUserIds) {
10133            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10134        }
10135
10136        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10137    }
10138
10139    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10140        boolean allowed = false;
10141        final int NP = PackageParser.NEW_PERMISSIONS.length;
10142        for (int ip=0; ip<NP; ip++) {
10143            final PackageParser.NewPermissionInfo npi
10144                    = PackageParser.NEW_PERMISSIONS[ip];
10145            if (npi.name.equals(perm)
10146                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10147                allowed = true;
10148                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10149                        + pkg.packageName);
10150                break;
10151            }
10152        }
10153        return allowed;
10154    }
10155
10156    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10157            BasePermission bp, PermissionsState origPermissions) {
10158        boolean allowed;
10159        allowed = (compareSignatures(
10160                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10161                        == PackageManager.SIGNATURE_MATCH)
10162                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10163                        == PackageManager.SIGNATURE_MATCH);
10164        if (!allowed && (bp.protectionLevel
10165                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10166            if (isSystemApp(pkg)) {
10167                // For updated system applications, a system permission
10168                // is granted only if it had been defined by the original application.
10169                if (pkg.isUpdatedSystemApp()) {
10170                    final PackageSetting sysPs = mSettings
10171                            .getDisabledSystemPkgLPr(pkg.packageName);
10172                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10173                        // If the original was granted this permission, we take
10174                        // that grant decision as read and propagate it to the
10175                        // update.
10176                        if (sysPs.isPrivileged()) {
10177                            allowed = true;
10178                        }
10179                    } else {
10180                        // The system apk may have been updated with an older
10181                        // version of the one on the data partition, but which
10182                        // granted a new system permission that it didn't have
10183                        // before.  In this case we do want to allow the app to
10184                        // now get the new permission if the ancestral apk is
10185                        // privileged to get it.
10186                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10187                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10188                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10189                                    allowed = true;
10190                                    break;
10191                                }
10192                            }
10193                        }
10194                        // Also if a privileged parent package on the system image or any of
10195                        // its children requested a privileged permission, the updated child
10196                        // packages can also get the permission.
10197                        if (pkg.parentPackage != null) {
10198                            final PackageSetting disabledSysParentPs = mSettings
10199                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10200                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10201                                    && disabledSysParentPs.isPrivileged()) {
10202                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10203                                    allowed = true;
10204                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10205                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10206                                    for (int i = 0; i < count; i++) {
10207                                        PackageParser.Package disabledSysChildPkg =
10208                                                disabledSysParentPs.pkg.childPackages.get(i);
10209                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10210                                                perm)) {
10211                                            allowed = true;
10212                                            break;
10213                                        }
10214                                    }
10215                                }
10216                            }
10217                        }
10218                    }
10219                } else {
10220                    allowed = isPrivilegedApp(pkg);
10221                }
10222            }
10223        }
10224        if (!allowed) {
10225            if (!allowed && (bp.protectionLevel
10226                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10227                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10228                // If this was a previously normal/dangerous permission that got moved
10229                // to a system permission as part of the runtime permission redesign, then
10230                // we still want to blindly grant it to old apps.
10231                allowed = true;
10232            }
10233            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10234                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10235                // If this permission is to be granted to the system installer and
10236                // this app is an installer, then it gets the permission.
10237                allowed = true;
10238            }
10239            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10240                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10241                // If this permission is to be granted to the system verifier and
10242                // this app is a verifier, then it gets the permission.
10243                allowed = true;
10244            }
10245            if (!allowed && (bp.protectionLevel
10246                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10247                    && isSystemApp(pkg)) {
10248                // Any pre-installed system app is allowed to get this permission.
10249                allowed = true;
10250            }
10251            if (!allowed && (bp.protectionLevel
10252                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10253                // For development permissions, a development permission
10254                // is granted only if it was already granted.
10255                allowed = origPermissions.hasInstallPermission(perm);
10256            }
10257            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10258                    && pkg.packageName.equals(mSetupWizardPackage)) {
10259                // If this permission is to be granted to the system setup wizard and
10260                // this app is a setup wizard, then it gets the permission.
10261                allowed = true;
10262            }
10263        }
10264        return allowed;
10265    }
10266
10267    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10268        final int permCount = pkg.requestedPermissions.size();
10269        for (int j = 0; j < permCount; j++) {
10270            String requestedPermission = pkg.requestedPermissions.get(j);
10271            if (permission.equals(requestedPermission)) {
10272                return true;
10273            }
10274        }
10275        return false;
10276    }
10277
10278    final class ActivityIntentResolver
10279            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10280        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10281                boolean defaultOnly, int userId) {
10282            if (!sUserManager.exists(userId)) return null;
10283            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10284            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10285        }
10286
10287        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10288                int userId) {
10289            if (!sUserManager.exists(userId)) return null;
10290            mFlags = flags;
10291            return super.queryIntent(intent, resolvedType,
10292                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10293        }
10294
10295        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10296                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10297            if (!sUserManager.exists(userId)) return null;
10298            if (packageActivities == null) {
10299                return null;
10300            }
10301            mFlags = flags;
10302            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10303            final int N = packageActivities.size();
10304            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10305                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10306
10307            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10308            for (int i = 0; i < N; ++i) {
10309                intentFilters = packageActivities.get(i).intents;
10310                if (intentFilters != null && intentFilters.size() > 0) {
10311                    PackageParser.ActivityIntentInfo[] array =
10312                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10313                    intentFilters.toArray(array);
10314                    listCut.add(array);
10315                }
10316            }
10317            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10318        }
10319
10320        /**
10321         * Finds a privileged activity that matches the specified activity names.
10322         */
10323        private PackageParser.Activity findMatchingActivity(
10324                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10325            for (PackageParser.Activity sysActivity : activityList) {
10326                if (sysActivity.info.name.equals(activityInfo.name)) {
10327                    return sysActivity;
10328                }
10329                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10330                    return sysActivity;
10331                }
10332                if (sysActivity.info.targetActivity != null) {
10333                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10334                        return sysActivity;
10335                    }
10336                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10337                        return sysActivity;
10338                    }
10339                }
10340            }
10341            return null;
10342        }
10343
10344        public class IterGenerator<E> {
10345            public Iterator<E> generate(ActivityIntentInfo info) {
10346                return null;
10347            }
10348        }
10349
10350        public class ActionIterGenerator extends IterGenerator<String> {
10351            @Override
10352            public Iterator<String> generate(ActivityIntentInfo info) {
10353                return info.actionsIterator();
10354            }
10355        }
10356
10357        public class CategoriesIterGenerator extends IterGenerator<String> {
10358            @Override
10359            public Iterator<String> generate(ActivityIntentInfo info) {
10360                return info.categoriesIterator();
10361            }
10362        }
10363
10364        public class SchemesIterGenerator extends IterGenerator<String> {
10365            @Override
10366            public Iterator<String> generate(ActivityIntentInfo info) {
10367                return info.schemesIterator();
10368            }
10369        }
10370
10371        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10372            @Override
10373            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10374                return info.authoritiesIterator();
10375            }
10376        }
10377
10378        /**
10379         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10380         * MODIFIED. Do not pass in a list that should not be changed.
10381         */
10382        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10383                IterGenerator<T> generator, Iterator<T> searchIterator) {
10384            // loop through the set of actions; every one must be found in the intent filter
10385            while (searchIterator.hasNext()) {
10386                // we must have at least one filter in the list to consider a match
10387                if (intentList.size() == 0) {
10388                    break;
10389                }
10390
10391                final T searchAction = searchIterator.next();
10392
10393                // loop through the set of intent filters
10394                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10395                while (intentIter.hasNext()) {
10396                    final ActivityIntentInfo intentInfo = intentIter.next();
10397                    boolean selectionFound = false;
10398
10399                    // loop through the intent filter's selection criteria; at least one
10400                    // of them must match the searched criteria
10401                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10402                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10403                        final T intentSelection = intentSelectionIter.next();
10404                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10405                            selectionFound = true;
10406                            break;
10407                        }
10408                    }
10409
10410                    // the selection criteria wasn't found in this filter's set; this filter
10411                    // is not a potential match
10412                    if (!selectionFound) {
10413                        intentIter.remove();
10414                    }
10415                }
10416            }
10417        }
10418
10419        private boolean isProtectedAction(ActivityIntentInfo filter) {
10420            final Iterator<String> actionsIter = filter.actionsIterator();
10421            while (actionsIter != null && actionsIter.hasNext()) {
10422                final String filterAction = actionsIter.next();
10423                if (PROTECTED_ACTIONS.contains(filterAction)) {
10424                    return true;
10425                }
10426            }
10427            return false;
10428        }
10429
10430        /**
10431         * Adjusts the priority of the given intent filter according to policy.
10432         * <p>
10433         * <ul>
10434         * <li>The priority for non privileged applications is capped to '0'</li>
10435         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10436         * <li>The priority for unbundled updates to privileged applications is capped to the
10437         *      priority defined on the system partition</li>
10438         * </ul>
10439         * <p>
10440         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10441         * allowed to obtain any priority on any action.
10442         */
10443        private void adjustPriority(
10444                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10445            // nothing to do; priority is fine as-is
10446            if (intent.getPriority() <= 0) {
10447                return;
10448            }
10449
10450            final ActivityInfo activityInfo = intent.activity.info;
10451            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10452
10453            final boolean privilegedApp =
10454                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10455            if (!privilegedApp) {
10456                // non-privileged applications can never define a priority >0
10457                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10458                        + " package: " + applicationInfo.packageName
10459                        + " activity: " + intent.activity.className
10460                        + " origPrio: " + intent.getPriority());
10461                intent.setPriority(0);
10462                return;
10463            }
10464
10465            if (systemActivities == null) {
10466                // the system package is not disabled; we're parsing the system partition
10467                if (isProtectedAction(intent)) {
10468                    if (mDeferProtectedFilters) {
10469                        // We can't deal with these just yet. No component should ever obtain a
10470                        // >0 priority for a protected actions, with ONE exception -- the setup
10471                        // wizard. The setup wizard, however, cannot be known until we're able to
10472                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10473                        // until all intent filters have been processed. Chicken, meet egg.
10474                        // Let the filter temporarily have a high priority and rectify the
10475                        // priorities after all system packages have been scanned.
10476                        mProtectedFilters.add(intent);
10477                        if (DEBUG_FILTERS) {
10478                            Slog.i(TAG, "Protected action; save for later;"
10479                                    + " package: " + applicationInfo.packageName
10480                                    + " activity: " + intent.activity.className
10481                                    + " origPrio: " + intent.getPriority());
10482                        }
10483                        return;
10484                    } else {
10485                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10486                            Slog.i(TAG, "No setup wizard;"
10487                                + " All protected intents capped to priority 0");
10488                        }
10489                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10490                            if (DEBUG_FILTERS) {
10491                                Slog.i(TAG, "Found setup wizard;"
10492                                    + " allow priority " + intent.getPriority() + ";"
10493                                    + " package: " + intent.activity.info.packageName
10494                                    + " activity: " + intent.activity.className
10495                                    + " priority: " + intent.getPriority());
10496                            }
10497                            // setup wizard gets whatever it wants
10498                            return;
10499                        }
10500                        Slog.w(TAG, "Protected action; cap priority to 0;"
10501                                + " package: " + intent.activity.info.packageName
10502                                + " activity: " + intent.activity.className
10503                                + " origPrio: " + intent.getPriority());
10504                        intent.setPriority(0);
10505                        return;
10506                    }
10507                }
10508                // privileged apps on the system image get whatever priority they request
10509                return;
10510            }
10511
10512            // privileged app unbundled update ... try to find the same activity
10513            final PackageParser.Activity foundActivity =
10514                    findMatchingActivity(systemActivities, activityInfo);
10515            if (foundActivity == null) {
10516                // this is a new activity; it cannot obtain >0 priority
10517                if (DEBUG_FILTERS) {
10518                    Slog.i(TAG, "New activity; cap priority to 0;"
10519                            + " package: " + applicationInfo.packageName
10520                            + " activity: " + intent.activity.className
10521                            + " origPrio: " + intent.getPriority());
10522                }
10523                intent.setPriority(0);
10524                return;
10525            }
10526
10527            // found activity, now check for filter equivalence
10528
10529            // a shallow copy is enough; we modify the list, not its contents
10530            final List<ActivityIntentInfo> intentListCopy =
10531                    new ArrayList<>(foundActivity.intents);
10532            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10533
10534            // find matching action subsets
10535            final Iterator<String> actionsIterator = intent.actionsIterator();
10536            if (actionsIterator != null) {
10537                getIntentListSubset(
10538                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10539                if (intentListCopy.size() == 0) {
10540                    // no more intents to match; we're not equivalent
10541                    if (DEBUG_FILTERS) {
10542                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10543                                + " package: " + applicationInfo.packageName
10544                                + " activity: " + intent.activity.className
10545                                + " origPrio: " + intent.getPriority());
10546                    }
10547                    intent.setPriority(0);
10548                    return;
10549                }
10550            }
10551
10552            // find matching category subsets
10553            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10554            if (categoriesIterator != null) {
10555                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10556                        categoriesIterator);
10557                if (intentListCopy.size() == 0) {
10558                    // no more intents to match; we're not equivalent
10559                    if (DEBUG_FILTERS) {
10560                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10561                                + " package: " + applicationInfo.packageName
10562                                + " activity: " + intent.activity.className
10563                                + " origPrio: " + intent.getPriority());
10564                    }
10565                    intent.setPriority(0);
10566                    return;
10567                }
10568            }
10569
10570            // find matching schemes subsets
10571            final Iterator<String> schemesIterator = intent.schemesIterator();
10572            if (schemesIterator != null) {
10573                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10574                        schemesIterator);
10575                if (intentListCopy.size() == 0) {
10576                    // no more intents to match; we're not equivalent
10577                    if (DEBUG_FILTERS) {
10578                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10579                                + " package: " + applicationInfo.packageName
10580                                + " activity: " + intent.activity.className
10581                                + " origPrio: " + intent.getPriority());
10582                    }
10583                    intent.setPriority(0);
10584                    return;
10585                }
10586            }
10587
10588            // find matching authorities subsets
10589            final Iterator<IntentFilter.AuthorityEntry>
10590                    authoritiesIterator = intent.authoritiesIterator();
10591            if (authoritiesIterator != null) {
10592                getIntentListSubset(intentListCopy,
10593                        new AuthoritiesIterGenerator(),
10594                        authoritiesIterator);
10595                if (intentListCopy.size() == 0) {
10596                    // no more intents to match; we're not equivalent
10597                    if (DEBUG_FILTERS) {
10598                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10599                                + " package: " + applicationInfo.packageName
10600                                + " activity: " + intent.activity.className
10601                                + " origPrio: " + intent.getPriority());
10602                    }
10603                    intent.setPriority(0);
10604                    return;
10605                }
10606            }
10607
10608            // we found matching filter(s); app gets the max priority of all intents
10609            int cappedPriority = 0;
10610            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10611                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10612            }
10613            if (intent.getPriority() > cappedPriority) {
10614                if (DEBUG_FILTERS) {
10615                    Slog.i(TAG, "Found matching filter(s);"
10616                            + " cap priority to " + cappedPriority + ";"
10617                            + " package: " + applicationInfo.packageName
10618                            + " activity: " + intent.activity.className
10619                            + " origPrio: " + intent.getPriority());
10620                }
10621                intent.setPriority(cappedPriority);
10622                return;
10623            }
10624            // all this for nothing; the requested priority was <= what was on the system
10625        }
10626
10627        public final void addActivity(PackageParser.Activity a, String type) {
10628            mActivities.put(a.getComponentName(), a);
10629            if (DEBUG_SHOW_INFO)
10630                Log.v(
10631                TAG, "  " + type + " " +
10632                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10633            if (DEBUG_SHOW_INFO)
10634                Log.v(TAG, "    Class=" + a.info.name);
10635            final int NI = a.intents.size();
10636            for (int j=0; j<NI; j++) {
10637                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10638                if ("activity".equals(type)) {
10639                    final PackageSetting ps =
10640                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10641                    final List<PackageParser.Activity> systemActivities =
10642                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10643                    adjustPriority(systemActivities, intent);
10644                }
10645                if (DEBUG_SHOW_INFO) {
10646                    Log.v(TAG, "    IntentFilter:");
10647                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10648                }
10649                if (!intent.debugCheck()) {
10650                    Log.w(TAG, "==> For Activity " + a.info.name);
10651                }
10652                addFilter(intent);
10653            }
10654        }
10655
10656        public final void removeActivity(PackageParser.Activity a, String type) {
10657            mActivities.remove(a.getComponentName());
10658            if (DEBUG_SHOW_INFO) {
10659                Log.v(TAG, "  " + type + " "
10660                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10661                                : a.info.name) + ":");
10662                Log.v(TAG, "    Class=" + a.info.name);
10663            }
10664            final int NI = a.intents.size();
10665            for (int j=0; j<NI; j++) {
10666                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10667                if (DEBUG_SHOW_INFO) {
10668                    Log.v(TAG, "    IntentFilter:");
10669                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10670                }
10671                removeFilter(intent);
10672            }
10673        }
10674
10675        @Override
10676        protected boolean allowFilterResult(
10677                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10678            ActivityInfo filterAi = filter.activity.info;
10679            for (int i=dest.size()-1; i>=0; i--) {
10680                ActivityInfo destAi = dest.get(i).activityInfo;
10681                if (destAi.name == filterAi.name
10682                        && destAi.packageName == filterAi.packageName) {
10683                    return false;
10684                }
10685            }
10686            return true;
10687        }
10688
10689        @Override
10690        protected ActivityIntentInfo[] newArray(int size) {
10691            return new ActivityIntentInfo[size];
10692        }
10693
10694        @Override
10695        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10696            if (!sUserManager.exists(userId)) return true;
10697            PackageParser.Package p = filter.activity.owner;
10698            if (p != null) {
10699                PackageSetting ps = (PackageSetting)p.mExtras;
10700                if (ps != null) {
10701                    // System apps are never considered stopped for purposes of
10702                    // filtering, because there may be no way for the user to
10703                    // actually re-launch them.
10704                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10705                            && ps.getStopped(userId);
10706                }
10707            }
10708            return false;
10709        }
10710
10711        @Override
10712        protected boolean isPackageForFilter(String packageName,
10713                PackageParser.ActivityIntentInfo info) {
10714            return packageName.equals(info.activity.owner.packageName);
10715        }
10716
10717        @Override
10718        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10719                int match, int userId) {
10720            if (!sUserManager.exists(userId)) return null;
10721            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10722                return null;
10723            }
10724            final PackageParser.Activity activity = info.activity;
10725            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10726            if (ps == null) {
10727                return null;
10728            }
10729            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10730                    ps.readUserState(userId), userId);
10731            if (ai == null) {
10732                return null;
10733            }
10734            final ResolveInfo res = new ResolveInfo();
10735            res.activityInfo = ai;
10736            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10737                res.filter = info;
10738            }
10739            if (info != null) {
10740                res.handleAllWebDataURI = info.handleAllWebDataURI();
10741            }
10742            res.priority = info.getPriority();
10743            res.preferredOrder = activity.owner.mPreferredOrder;
10744            //System.out.println("Result: " + res.activityInfo.className +
10745            //                   " = " + res.priority);
10746            res.match = match;
10747            res.isDefault = info.hasDefault;
10748            res.labelRes = info.labelRes;
10749            res.nonLocalizedLabel = info.nonLocalizedLabel;
10750            if (userNeedsBadging(userId)) {
10751                res.noResourceId = true;
10752            } else {
10753                res.icon = info.icon;
10754            }
10755            res.iconResourceId = info.icon;
10756            res.system = res.activityInfo.applicationInfo.isSystemApp();
10757            return res;
10758        }
10759
10760        @Override
10761        protected void sortResults(List<ResolveInfo> results) {
10762            Collections.sort(results, mResolvePrioritySorter);
10763        }
10764
10765        @Override
10766        protected void dumpFilter(PrintWriter out, String prefix,
10767                PackageParser.ActivityIntentInfo filter) {
10768            out.print(prefix); out.print(
10769                    Integer.toHexString(System.identityHashCode(filter.activity)));
10770                    out.print(' ');
10771                    filter.activity.printComponentShortName(out);
10772                    out.print(" filter ");
10773                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10774        }
10775
10776        @Override
10777        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10778            return filter.activity;
10779        }
10780
10781        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10782            PackageParser.Activity activity = (PackageParser.Activity)label;
10783            out.print(prefix); out.print(
10784                    Integer.toHexString(System.identityHashCode(activity)));
10785                    out.print(' ');
10786                    activity.printComponentShortName(out);
10787            if (count > 1) {
10788                out.print(" ("); out.print(count); out.print(" filters)");
10789            }
10790            out.println();
10791        }
10792
10793        // Keys are String (activity class name), values are Activity.
10794        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10795                = new ArrayMap<ComponentName, PackageParser.Activity>();
10796        private int mFlags;
10797    }
10798
10799    private final class ServiceIntentResolver
10800            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10801        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10802                boolean defaultOnly, int userId) {
10803            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10804            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10805        }
10806
10807        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10808                int userId) {
10809            if (!sUserManager.exists(userId)) return null;
10810            mFlags = flags;
10811            return super.queryIntent(intent, resolvedType,
10812                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10813        }
10814
10815        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10816                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10817            if (!sUserManager.exists(userId)) return null;
10818            if (packageServices == null) {
10819                return null;
10820            }
10821            mFlags = flags;
10822            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10823            final int N = packageServices.size();
10824            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10825                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10826
10827            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10828            for (int i = 0; i < N; ++i) {
10829                intentFilters = packageServices.get(i).intents;
10830                if (intentFilters != null && intentFilters.size() > 0) {
10831                    PackageParser.ServiceIntentInfo[] array =
10832                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10833                    intentFilters.toArray(array);
10834                    listCut.add(array);
10835                }
10836            }
10837            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10838        }
10839
10840        public final void addService(PackageParser.Service s) {
10841            mServices.put(s.getComponentName(), s);
10842            if (DEBUG_SHOW_INFO) {
10843                Log.v(TAG, "  "
10844                        + (s.info.nonLocalizedLabel != null
10845                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10846                Log.v(TAG, "    Class=" + s.info.name);
10847            }
10848            final int NI = s.intents.size();
10849            int j;
10850            for (j=0; j<NI; j++) {
10851                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10852                if (DEBUG_SHOW_INFO) {
10853                    Log.v(TAG, "    IntentFilter:");
10854                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10855                }
10856                if (!intent.debugCheck()) {
10857                    Log.w(TAG, "==> For Service " + s.info.name);
10858                }
10859                addFilter(intent);
10860            }
10861        }
10862
10863        public final void removeService(PackageParser.Service s) {
10864            mServices.remove(s.getComponentName());
10865            if (DEBUG_SHOW_INFO) {
10866                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10867                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10868                Log.v(TAG, "    Class=" + s.info.name);
10869            }
10870            final int NI = s.intents.size();
10871            int j;
10872            for (j=0; j<NI; j++) {
10873                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10874                if (DEBUG_SHOW_INFO) {
10875                    Log.v(TAG, "    IntentFilter:");
10876                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10877                }
10878                removeFilter(intent);
10879            }
10880        }
10881
10882        @Override
10883        protected boolean allowFilterResult(
10884                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10885            ServiceInfo filterSi = filter.service.info;
10886            for (int i=dest.size()-1; i>=0; i--) {
10887                ServiceInfo destAi = dest.get(i).serviceInfo;
10888                if (destAi.name == filterSi.name
10889                        && destAi.packageName == filterSi.packageName) {
10890                    return false;
10891                }
10892            }
10893            return true;
10894        }
10895
10896        @Override
10897        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10898            return new PackageParser.ServiceIntentInfo[size];
10899        }
10900
10901        @Override
10902        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10903            if (!sUserManager.exists(userId)) return true;
10904            PackageParser.Package p = filter.service.owner;
10905            if (p != null) {
10906                PackageSetting ps = (PackageSetting)p.mExtras;
10907                if (ps != null) {
10908                    // System apps are never considered stopped for purposes of
10909                    // filtering, because there may be no way for the user to
10910                    // actually re-launch them.
10911                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10912                            && ps.getStopped(userId);
10913                }
10914            }
10915            return false;
10916        }
10917
10918        @Override
10919        protected boolean isPackageForFilter(String packageName,
10920                PackageParser.ServiceIntentInfo info) {
10921            return packageName.equals(info.service.owner.packageName);
10922        }
10923
10924        @Override
10925        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10926                int match, int userId) {
10927            if (!sUserManager.exists(userId)) return null;
10928            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10929            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10930                return null;
10931            }
10932            final PackageParser.Service service = info.service;
10933            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10934            if (ps == null) {
10935                return null;
10936            }
10937            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10938                    ps.readUserState(userId), userId);
10939            if (si == null) {
10940                return null;
10941            }
10942            final ResolveInfo res = new ResolveInfo();
10943            res.serviceInfo = si;
10944            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10945                res.filter = filter;
10946            }
10947            res.priority = info.getPriority();
10948            res.preferredOrder = service.owner.mPreferredOrder;
10949            res.match = match;
10950            res.isDefault = info.hasDefault;
10951            res.labelRes = info.labelRes;
10952            res.nonLocalizedLabel = info.nonLocalizedLabel;
10953            res.icon = info.icon;
10954            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10955            return res;
10956        }
10957
10958        @Override
10959        protected void sortResults(List<ResolveInfo> results) {
10960            Collections.sort(results, mResolvePrioritySorter);
10961        }
10962
10963        @Override
10964        protected void dumpFilter(PrintWriter out, String prefix,
10965                PackageParser.ServiceIntentInfo filter) {
10966            out.print(prefix); out.print(
10967                    Integer.toHexString(System.identityHashCode(filter.service)));
10968                    out.print(' ');
10969                    filter.service.printComponentShortName(out);
10970                    out.print(" filter ");
10971                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10972        }
10973
10974        @Override
10975        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10976            return filter.service;
10977        }
10978
10979        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10980            PackageParser.Service service = (PackageParser.Service)label;
10981            out.print(prefix); out.print(
10982                    Integer.toHexString(System.identityHashCode(service)));
10983                    out.print(' ');
10984                    service.printComponentShortName(out);
10985            if (count > 1) {
10986                out.print(" ("); out.print(count); out.print(" filters)");
10987            }
10988            out.println();
10989        }
10990
10991//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10992//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10993//            final List<ResolveInfo> retList = Lists.newArrayList();
10994//            while (i.hasNext()) {
10995//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10996//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10997//                    retList.add(resolveInfo);
10998//                }
10999//            }
11000//            return retList;
11001//        }
11002
11003        // Keys are String (activity class name), values are Activity.
11004        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11005                = new ArrayMap<ComponentName, PackageParser.Service>();
11006        private int mFlags;
11007    };
11008
11009    private final class ProviderIntentResolver
11010            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11011        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11012                boolean defaultOnly, int userId) {
11013            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11014            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11015        }
11016
11017        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11018                int userId) {
11019            if (!sUserManager.exists(userId))
11020                return null;
11021            mFlags = flags;
11022            return super.queryIntent(intent, resolvedType,
11023                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11024        }
11025
11026        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11027                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11028            if (!sUserManager.exists(userId))
11029                return null;
11030            if (packageProviders == null) {
11031                return null;
11032            }
11033            mFlags = flags;
11034            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11035            final int N = packageProviders.size();
11036            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11037                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11038
11039            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11040            for (int i = 0; i < N; ++i) {
11041                intentFilters = packageProviders.get(i).intents;
11042                if (intentFilters != null && intentFilters.size() > 0) {
11043                    PackageParser.ProviderIntentInfo[] array =
11044                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11045                    intentFilters.toArray(array);
11046                    listCut.add(array);
11047                }
11048            }
11049            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11050        }
11051
11052        public final void addProvider(PackageParser.Provider p) {
11053            if (mProviders.containsKey(p.getComponentName())) {
11054                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11055                return;
11056            }
11057
11058            mProviders.put(p.getComponentName(), p);
11059            if (DEBUG_SHOW_INFO) {
11060                Log.v(TAG, "  "
11061                        + (p.info.nonLocalizedLabel != null
11062                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11063                Log.v(TAG, "    Class=" + p.info.name);
11064            }
11065            final int NI = p.intents.size();
11066            int j;
11067            for (j = 0; j < NI; j++) {
11068                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11069                if (DEBUG_SHOW_INFO) {
11070                    Log.v(TAG, "    IntentFilter:");
11071                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11072                }
11073                if (!intent.debugCheck()) {
11074                    Log.w(TAG, "==> For Provider " + p.info.name);
11075                }
11076                addFilter(intent);
11077            }
11078        }
11079
11080        public final void removeProvider(PackageParser.Provider p) {
11081            mProviders.remove(p.getComponentName());
11082            if (DEBUG_SHOW_INFO) {
11083                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11084                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11085                Log.v(TAG, "    Class=" + p.info.name);
11086            }
11087            final int NI = p.intents.size();
11088            int j;
11089            for (j = 0; j < NI; j++) {
11090                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11091                if (DEBUG_SHOW_INFO) {
11092                    Log.v(TAG, "    IntentFilter:");
11093                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11094                }
11095                removeFilter(intent);
11096            }
11097        }
11098
11099        @Override
11100        protected boolean allowFilterResult(
11101                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11102            ProviderInfo filterPi = filter.provider.info;
11103            for (int i = dest.size() - 1; i >= 0; i--) {
11104                ProviderInfo destPi = dest.get(i).providerInfo;
11105                if (destPi.name == filterPi.name
11106                        && destPi.packageName == filterPi.packageName) {
11107                    return false;
11108                }
11109            }
11110            return true;
11111        }
11112
11113        @Override
11114        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11115            return new PackageParser.ProviderIntentInfo[size];
11116        }
11117
11118        @Override
11119        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11120            if (!sUserManager.exists(userId))
11121                return true;
11122            PackageParser.Package p = filter.provider.owner;
11123            if (p != null) {
11124                PackageSetting ps = (PackageSetting) p.mExtras;
11125                if (ps != null) {
11126                    // System apps are never considered stopped for purposes of
11127                    // filtering, because there may be no way for the user to
11128                    // actually re-launch them.
11129                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11130                            && ps.getStopped(userId);
11131                }
11132            }
11133            return false;
11134        }
11135
11136        @Override
11137        protected boolean isPackageForFilter(String packageName,
11138                PackageParser.ProviderIntentInfo info) {
11139            return packageName.equals(info.provider.owner.packageName);
11140        }
11141
11142        @Override
11143        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11144                int match, int userId) {
11145            if (!sUserManager.exists(userId))
11146                return null;
11147            final PackageParser.ProviderIntentInfo info = filter;
11148            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11149                return null;
11150            }
11151            final PackageParser.Provider provider = info.provider;
11152            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11153            if (ps == null) {
11154                return null;
11155            }
11156            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11157                    ps.readUserState(userId), userId);
11158            if (pi == null) {
11159                return null;
11160            }
11161            final ResolveInfo res = new ResolveInfo();
11162            res.providerInfo = pi;
11163            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11164                res.filter = filter;
11165            }
11166            res.priority = info.getPriority();
11167            res.preferredOrder = provider.owner.mPreferredOrder;
11168            res.match = match;
11169            res.isDefault = info.hasDefault;
11170            res.labelRes = info.labelRes;
11171            res.nonLocalizedLabel = info.nonLocalizedLabel;
11172            res.icon = info.icon;
11173            res.system = res.providerInfo.applicationInfo.isSystemApp();
11174            return res;
11175        }
11176
11177        @Override
11178        protected void sortResults(List<ResolveInfo> results) {
11179            Collections.sort(results, mResolvePrioritySorter);
11180        }
11181
11182        @Override
11183        protected void dumpFilter(PrintWriter out, String prefix,
11184                PackageParser.ProviderIntentInfo filter) {
11185            out.print(prefix);
11186            out.print(
11187                    Integer.toHexString(System.identityHashCode(filter.provider)));
11188            out.print(' ');
11189            filter.provider.printComponentShortName(out);
11190            out.print(" filter ");
11191            out.println(Integer.toHexString(System.identityHashCode(filter)));
11192        }
11193
11194        @Override
11195        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11196            return filter.provider;
11197        }
11198
11199        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11200            PackageParser.Provider provider = (PackageParser.Provider)label;
11201            out.print(prefix); out.print(
11202                    Integer.toHexString(System.identityHashCode(provider)));
11203                    out.print(' ');
11204                    provider.printComponentShortName(out);
11205            if (count > 1) {
11206                out.print(" ("); out.print(count); out.print(" filters)");
11207            }
11208            out.println();
11209        }
11210
11211        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11212                = new ArrayMap<ComponentName, PackageParser.Provider>();
11213        private int mFlags;
11214    }
11215
11216    private static final class EphemeralIntentResolver
11217            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11218        @Override
11219        protected EphemeralResolveIntentInfo[] newArray(int size) {
11220            return new EphemeralResolveIntentInfo[size];
11221        }
11222
11223        @Override
11224        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11225            return true;
11226        }
11227
11228        @Override
11229        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11230                int userId) {
11231            if (!sUserManager.exists(userId)) {
11232                return null;
11233            }
11234            return info.getEphemeralResolveInfo();
11235        }
11236    }
11237
11238    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11239            new Comparator<ResolveInfo>() {
11240        public int compare(ResolveInfo r1, ResolveInfo r2) {
11241            int v1 = r1.priority;
11242            int v2 = r2.priority;
11243            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11244            if (v1 != v2) {
11245                return (v1 > v2) ? -1 : 1;
11246            }
11247            v1 = r1.preferredOrder;
11248            v2 = r2.preferredOrder;
11249            if (v1 != v2) {
11250                return (v1 > v2) ? -1 : 1;
11251            }
11252            if (r1.isDefault != r2.isDefault) {
11253                return r1.isDefault ? -1 : 1;
11254            }
11255            v1 = r1.match;
11256            v2 = r2.match;
11257            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11258            if (v1 != v2) {
11259                return (v1 > v2) ? -1 : 1;
11260            }
11261            if (r1.system != r2.system) {
11262                return r1.system ? -1 : 1;
11263            }
11264            if (r1.activityInfo != null) {
11265                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11266            }
11267            if (r1.serviceInfo != null) {
11268                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11269            }
11270            if (r1.providerInfo != null) {
11271                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11272            }
11273            return 0;
11274        }
11275    };
11276
11277    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11278            new Comparator<ProviderInfo>() {
11279        public int compare(ProviderInfo p1, ProviderInfo p2) {
11280            final int v1 = p1.initOrder;
11281            final int v2 = p2.initOrder;
11282            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11283        }
11284    };
11285
11286    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11287            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11288            final int[] userIds) {
11289        mHandler.post(new Runnable() {
11290            @Override
11291            public void run() {
11292                try {
11293                    final IActivityManager am = ActivityManagerNative.getDefault();
11294                    if (am == null) return;
11295                    final int[] resolvedUserIds;
11296                    if (userIds == null) {
11297                        resolvedUserIds = am.getRunningUserIds();
11298                    } else {
11299                        resolvedUserIds = userIds;
11300                    }
11301                    for (int id : resolvedUserIds) {
11302                        final Intent intent = new Intent(action,
11303                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11304                        if (extras != null) {
11305                            intent.putExtras(extras);
11306                        }
11307                        if (targetPkg != null) {
11308                            intent.setPackage(targetPkg);
11309                        }
11310                        // Modify the UID when posting to other users
11311                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11312                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11313                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11314                            intent.putExtra(Intent.EXTRA_UID, uid);
11315                        }
11316                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11317                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11318                        if (DEBUG_BROADCASTS) {
11319                            RuntimeException here = new RuntimeException("here");
11320                            here.fillInStackTrace();
11321                            Slog.d(TAG, "Sending to user " + id + ": "
11322                                    + intent.toShortString(false, true, false, false)
11323                                    + " " + intent.getExtras(), here);
11324                        }
11325                        am.broadcastIntent(null, intent, null, finishedReceiver,
11326                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11327                                null, finishedReceiver != null, false, id);
11328                    }
11329                } catch (RemoteException ex) {
11330                }
11331            }
11332        });
11333    }
11334
11335    /**
11336     * Check if the external storage media is available. This is true if there
11337     * is a mounted external storage medium or if the external storage is
11338     * emulated.
11339     */
11340    private boolean isExternalMediaAvailable() {
11341        return mMediaMounted || Environment.isExternalStorageEmulated();
11342    }
11343
11344    @Override
11345    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11346        // writer
11347        synchronized (mPackages) {
11348            if (!isExternalMediaAvailable()) {
11349                // If the external storage is no longer mounted at this point,
11350                // the caller may not have been able to delete all of this
11351                // packages files and can not delete any more.  Bail.
11352                return null;
11353            }
11354            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11355            if (lastPackage != null) {
11356                pkgs.remove(lastPackage);
11357            }
11358            if (pkgs.size() > 0) {
11359                return pkgs.get(0);
11360            }
11361        }
11362        return null;
11363    }
11364
11365    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11366        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11367                userId, andCode ? 1 : 0, packageName);
11368        if (mSystemReady) {
11369            msg.sendToTarget();
11370        } else {
11371            if (mPostSystemReadyMessages == null) {
11372                mPostSystemReadyMessages = new ArrayList<>();
11373            }
11374            mPostSystemReadyMessages.add(msg);
11375        }
11376    }
11377
11378    void startCleaningPackages() {
11379        // reader
11380        if (!isExternalMediaAvailable()) {
11381            return;
11382        }
11383        synchronized (mPackages) {
11384            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11385                return;
11386            }
11387        }
11388        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11389        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11390        IActivityManager am = ActivityManagerNative.getDefault();
11391        if (am != null) {
11392            try {
11393                am.startService(null, intent, null, mContext.getOpPackageName(),
11394                        UserHandle.USER_SYSTEM);
11395            } catch (RemoteException e) {
11396            }
11397        }
11398    }
11399
11400    @Override
11401    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11402            int installFlags, String installerPackageName, int userId) {
11403        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11404
11405        final int callingUid = Binder.getCallingUid();
11406        enforceCrossUserPermission(callingUid, userId,
11407                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11408
11409        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11410            try {
11411                if (observer != null) {
11412                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11413                }
11414            } catch (RemoteException re) {
11415            }
11416            return;
11417        }
11418
11419        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11420            installFlags |= PackageManager.INSTALL_FROM_ADB;
11421
11422        } else {
11423            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11424            // about installerPackageName.
11425
11426            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11427            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11428        }
11429
11430        UserHandle user;
11431        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11432            user = UserHandle.ALL;
11433        } else {
11434            user = new UserHandle(userId);
11435        }
11436
11437        // Only system components can circumvent runtime permissions when installing.
11438        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11439                && mContext.checkCallingOrSelfPermission(Manifest.permission
11440                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11441            throw new SecurityException("You need the "
11442                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11443                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11444        }
11445
11446        final File originFile = new File(originPath);
11447        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11448
11449        final Message msg = mHandler.obtainMessage(INIT_COPY);
11450        final VerificationInfo verificationInfo = new VerificationInfo(
11451                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11452        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11453                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11454                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11455                null /*certificates*/);
11456        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11457        msg.obj = params;
11458
11459        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11460                System.identityHashCode(msg.obj));
11461        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11462                System.identityHashCode(msg.obj));
11463
11464        mHandler.sendMessage(msg);
11465    }
11466
11467    void installStage(String packageName, File stagedDir, String stagedCid,
11468            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11469            String installerPackageName, int installerUid, UserHandle user,
11470            Certificate[][] certificates) {
11471        if (DEBUG_EPHEMERAL) {
11472            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11473                Slog.d(TAG, "Ephemeral install of " + packageName);
11474            }
11475        }
11476        final VerificationInfo verificationInfo = new VerificationInfo(
11477                sessionParams.originatingUri, sessionParams.referrerUri,
11478                sessionParams.originatingUid, installerUid);
11479
11480        final OriginInfo origin;
11481        if (stagedDir != null) {
11482            origin = OriginInfo.fromStagedFile(stagedDir);
11483        } else {
11484            origin = OriginInfo.fromStagedContainer(stagedCid);
11485        }
11486
11487        final Message msg = mHandler.obtainMessage(INIT_COPY);
11488        final InstallParams params = new InstallParams(origin, null, observer,
11489                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11490                verificationInfo, user, sessionParams.abiOverride,
11491                sessionParams.grantedRuntimePermissions, certificates);
11492        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11493        msg.obj = params;
11494
11495        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11496                System.identityHashCode(msg.obj));
11497        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11498                System.identityHashCode(msg.obj));
11499
11500        mHandler.sendMessage(msg);
11501    }
11502
11503    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11504            int userId) {
11505        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11506        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11507    }
11508
11509    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11510            int appId, int userId) {
11511        Bundle extras = new Bundle(1);
11512        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11513
11514        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11515                packageName, extras, 0, null, null, new int[] {userId});
11516        try {
11517            IActivityManager am = ActivityManagerNative.getDefault();
11518            if (isSystem && am.isUserRunning(userId, 0)) {
11519                // The just-installed/enabled app is bundled on the system, so presumed
11520                // to be able to run automatically without needing an explicit launch.
11521                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11522                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11523                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11524                        .setPackage(packageName);
11525                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11526                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11527            }
11528        } catch (RemoteException e) {
11529            // shouldn't happen
11530            Slog.w(TAG, "Unable to bootstrap installed package", e);
11531        }
11532    }
11533
11534    @Override
11535    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11536            int userId) {
11537        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11538        PackageSetting pkgSetting;
11539        final int uid = Binder.getCallingUid();
11540        enforceCrossUserPermission(uid, userId,
11541                true /* requireFullPermission */, true /* checkShell */,
11542                "setApplicationHiddenSetting for user " + userId);
11543
11544        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11545            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11546            return false;
11547        }
11548
11549        long callingId = Binder.clearCallingIdentity();
11550        try {
11551            boolean sendAdded = false;
11552            boolean sendRemoved = false;
11553            // writer
11554            synchronized (mPackages) {
11555                pkgSetting = mSettings.mPackages.get(packageName);
11556                if (pkgSetting == null) {
11557                    return false;
11558                }
11559                if (pkgSetting.getHidden(userId) != hidden) {
11560                    pkgSetting.setHidden(hidden, userId);
11561                    mSettings.writePackageRestrictionsLPr(userId);
11562                    if (hidden) {
11563                        sendRemoved = true;
11564                    } else {
11565                        sendAdded = true;
11566                    }
11567                }
11568            }
11569            if (sendAdded) {
11570                sendPackageAddedForUser(packageName, pkgSetting, userId);
11571                return true;
11572            }
11573            if (sendRemoved) {
11574                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11575                        "hiding pkg");
11576                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11577                return true;
11578            }
11579        } finally {
11580            Binder.restoreCallingIdentity(callingId);
11581        }
11582        return false;
11583    }
11584
11585    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11586            int userId) {
11587        final PackageRemovedInfo info = new PackageRemovedInfo();
11588        info.removedPackage = packageName;
11589        info.removedUsers = new int[] {userId};
11590        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11591        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11592    }
11593
11594    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11595        if (pkgList.length > 0) {
11596            Bundle extras = new Bundle(1);
11597            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11598
11599            sendPackageBroadcast(
11600                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11601                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11602                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11603                    new int[] {userId});
11604        }
11605    }
11606
11607    /**
11608     * Returns true if application is not found or there was an error. Otherwise it returns
11609     * the hidden state of the package for the given user.
11610     */
11611    @Override
11612    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11613        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11614        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11615                true /* requireFullPermission */, false /* checkShell */,
11616                "getApplicationHidden for user " + userId);
11617        PackageSetting pkgSetting;
11618        long callingId = Binder.clearCallingIdentity();
11619        try {
11620            // writer
11621            synchronized (mPackages) {
11622                pkgSetting = mSettings.mPackages.get(packageName);
11623                if (pkgSetting == null) {
11624                    return true;
11625                }
11626                return pkgSetting.getHidden(userId);
11627            }
11628        } finally {
11629            Binder.restoreCallingIdentity(callingId);
11630        }
11631    }
11632
11633    /**
11634     * @hide
11635     */
11636    @Override
11637    public int installExistingPackageAsUser(String packageName, int userId) {
11638        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11639                null);
11640        PackageSetting pkgSetting;
11641        final int uid = Binder.getCallingUid();
11642        enforceCrossUserPermission(uid, userId,
11643                true /* requireFullPermission */, true /* checkShell */,
11644                "installExistingPackage for user " + userId);
11645        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11646            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11647        }
11648
11649        long callingId = Binder.clearCallingIdentity();
11650        try {
11651            boolean installed = false;
11652
11653            // writer
11654            synchronized (mPackages) {
11655                pkgSetting = mSettings.mPackages.get(packageName);
11656                if (pkgSetting == null) {
11657                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11658                }
11659                if (!pkgSetting.getInstalled(userId)) {
11660                    pkgSetting.setInstalled(true, userId);
11661                    pkgSetting.setHidden(false, userId);
11662                    mSettings.writePackageRestrictionsLPr(userId);
11663                    installed = true;
11664                }
11665            }
11666
11667            if (installed) {
11668                if (pkgSetting.pkg != null) {
11669                    synchronized (mInstallLock) {
11670                        // We don't need to freeze for a brand new install
11671                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11672                    }
11673                }
11674                sendPackageAddedForUser(packageName, pkgSetting, userId);
11675            }
11676        } finally {
11677            Binder.restoreCallingIdentity(callingId);
11678        }
11679
11680        return PackageManager.INSTALL_SUCCEEDED;
11681    }
11682
11683    boolean isUserRestricted(int userId, String restrictionKey) {
11684        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11685        if (restrictions.getBoolean(restrictionKey, false)) {
11686            Log.w(TAG, "User is restricted: " + restrictionKey);
11687            return true;
11688        }
11689        return false;
11690    }
11691
11692    @Override
11693    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11694            int userId) {
11695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11696        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11697                true /* requireFullPermission */, true /* checkShell */,
11698                "setPackagesSuspended for user " + userId);
11699
11700        if (ArrayUtils.isEmpty(packageNames)) {
11701            return packageNames;
11702        }
11703
11704        // List of package names for whom the suspended state has changed.
11705        List<String> changedPackages = new ArrayList<>(packageNames.length);
11706        // List of package names for whom the suspended state is not set as requested in this
11707        // method.
11708        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11709        long callingId = Binder.clearCallingIdentity();
11710        try {
11711            for (int i = 0; i < packageNames.length; i++) {
11712                String packageName = packageNames[i];
11713                boolean changed = false;
11714                final int appId;
11715                synchronized (mPackages) {
11716                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11717                    if (pkgSetting == null) {
11718                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11719                                + "\". Skipping suspending/un-suspending.");
11720                        unactionedPackages.add(packageName);
11721                        continue;
11722                    }
11723                    appId = pkgSetting.appId;
11724                    if (pkgSetting.getSuspended(userId) != suspended) {
11725                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11726                            unactionedPackages.add(packageName);
11727                            continue;
11728                        }
11729                        pkgSetting.setSuspended(suspended, userId);
11730                        mSettings.writePackageRestrictionsLPr(userId);
11731                        changed = true;
11732                        changedPackages.add(packageName);
11733                    }
11734                }
11735
11736                if (changed && suspended) {
11737                    killApplication(packageName, UserHandle.getUid(userId, appId),
11738                            "suspending package");
11739                }
11740            }
11741        } finally {
11742            Binder.restoreCallingIdentity(callingId);
11743        }
11744
11745        if (!changedPackages.isEmpty()) {
11746            sendPackagesSuspendedForUser(changedPackages.toArray(
11747                    new String[changedPackages.size()]), userId, suspended);
11748        }
11749
11750        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11751    }
11752
11753    @Override
11754    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11755        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11756                true /* requireFullPermission */, false /* checkShell */,
11757                "isPackageSuspendedForUser for user " + userId);
11758        synchronized (mPackages) {
11759            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11760            if (pkgSetting == null) {
11761                throw new IllegalArgumentException("Unknown target package: " + packageName);
11762            }
11763            return pkgSetting.getSuspended(userId);
11764        }
11765    }
11766
11767    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11768        if (isPackageDeviceAdmin(packageName, userId)) {
11769            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11770                    + "\": has an active device admin");
11771            return false;
11772        }
11773
11774        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11775        if (packageName.equals(activeLauncherPackageName)) {
11776            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11777                    + "\": contains the active launcher");
11778            return false;
11779        }
11780
11781        if (packageName.equals(mRequiredInstallerPackage)) {
11782            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11783                    + "\": required for package installation");
11784            return false;
11785        }
11786
11787        if (packageName.equals(mRequiredVerifierPackage)) {
11788            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11789                    + "\": required for package verification");
11790            return false;
11791        }
11792
11793        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11794            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11795                    + "\": is the default dialer");
11796            return false;
11797        }
11798
11799        return true;
11800    }
11801
11802    private String getActiveLauncherPackageName(int userId) {
11803        Intent intent = new Intent(Intent.ACTION_MAIN);
11804        intent.addCategory(Intent.CATEGORY_HOME);
11805        ResolveInfo resolveInfo = resolveIntent(
11806                intent,
11807                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11808                PackageManager.MATCH_DEFAULT_ONLY,
11809                userId);
11810
11811        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11812    }
11813
11814    private String getDefaultDialerPackageName(int userId) {
11815        synchronized (mPackages) {
11816            return mSettings.getDefaultDialerPackageNameLPw(userId);
11817        }
11818    }
11819
11820    @Override
11821    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11822        mContext.enforceCallingOrSelfPermission(
11823                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11824                "Only package verification agents can verify applications");
11825
11826        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11827        final PackageVerificationResponse response = new PackageVerificationResponse(
11828                verificationCode, Binder.getCallingUid());
11829        msg.arg1 = id;
11830        msg.obj = response;
11831        mHandler.sendMessage(msg);
11832    }
11833
11834    @Override
11835    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11836            long millisecondsToDelay) {
11837        mContext.enforceCallingOrSelfPermission(
11838                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11839                "Only package verification agents can extend verification timeouts");
11840
11841        final PackageVerificationState state = mPendingVerification.get(id);
11842        final PackageVerificationResponse response = new PackageVerificationResponse(
11843                verificationCodeAtTimeout, Binder.getCallingUid());
11844
11845        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11846            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11847        }
11848        if (millisecondsToDelay < 0) {
11849            millisecondsToDelay = 0;
11850        }
11851        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11852                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11853            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11854        }
11855
11856        if ((state != null) && !state.timeoutExtended()) {
11857            state.extendTimeout();
11858
11859            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11860            msg.arg1 = id;
11861            msg.obj = response;
11862            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11863        }
11864    }
11865
11866    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11867            int verificationCode, UserHandle user) {
11868        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11869        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11870        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11871        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11872        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11873
11874        mContext.sendBroadcastAsUser(intent, user,
11875                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11876    }
11877
11878    private ComponentName matchComponentForVerifier(String packageName,
11879            List<ResolveInfo> receivers) {
11880        ActivityInfo targetReceiver = null;
11881
11882        final int NR = receivers.size();
11883        for (int i = 0; i < NR; i++) {
11884            final ResolveInfo info = receivers.get(i);
11885            if (info.activityInfo == null) {
11886                continue;
11887            }
11888
11889            if (packageName.equals(info.activityInfo.packageName)) {
11890                targetReceiver = info.activityInfo;
11891                break;
11892            }
11893        }
11894
11895        if (targetReceiver == null) {
11896            return null;
11897        }
11898
11899        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11900    }
11901
11902    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11903            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11904        if (pkgInfo.verifiers.length == 0) {
11905            return null;
11906        }
11907
11908        final int N = pkgInfo.verifiers.length;
11909        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11910        for (int i = 0; i < N; i++) {
11911            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11912
11913            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11914                    receivers);
11915            if (comp == null) {
11916                continue;
11917            }
11918
11919            final int verifierUid = getUidForVerifier(verifierInfo);
11920            if (verifierUid == -1) {
11921                continue;
11922            }
11923
11924            if (DEBUG_VERIFY) {
11925                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11926                        + " with the correct signature");
11927            }
11928            sufficientVerifiers.add(comp);
11929            verificationState.addSufficientVerifier(verifierUid);
11930        }
11931
11932        return sufficientVerifiers;
11933    }
11934
11935    private int getUidForVerifier(VerifierInfo verifierInfo) {
11936        synchronized (mPackages) {
11937            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11938            if (pkg == null) {
11939                return -1;
11940            } else if (pkg.mSignatures.length != 1) {
11941                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11942                        + " has more than one signature; ignoring");
11943                return -1;
11944            }
11945
11946            /*
11947             * If the public key of the package's signature does not match
11948             * our expected public key, then this is a different package and
11949             * we should skip.
11950             */
11951
11952            final byte[] expectedPublicKey;
11953            try {
11954                final Signature verifierSig = pkg.mSignatures[0];
11955                final PublicKey publicKey = verifierSig.getPublicKey();
11956                expectedPublicKey = publicKey.getEncoded();
11957            } catch (CertificateException e) {
11958                return -1;
11959            }
11960
11961            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11962
11963            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11964                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11965                        + " does not have the expected public key; ignoring");
11966                return -1;
11967            }
11968
11969            return pkg.applicationInfo.uid;
11970        }
11971    }
11972
11973    @Override
11974    public void finishPackageInstall(int token, boolean didLaunch) {
11975        enforceSystemOrRoot("Only the system is allowed to finish installs");
11976
11977        if (DEBUG_INSTALL) {
11978            Slog.v(TAG, "BM finishing package install for " + token);
11979        }
11980        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11981
11982        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11983        mHandler.sendMessage(msg);
11984    }
11985
11986    /**
11987     * Get the verification agent timeout.
11988     *
11989     * @return verification timeout in milliseconds
11990     */
11991    private long getVerificationTimeout() {
11992        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11993                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11994                DEFAULT_VERIFICATION_TIMEOUT);
11995    }
11996
11997    /**
11998     * Get the default verification agent response code.
11999     *
12000     * @return default verification response code
12001     */
12002    private int getDefaultVerificationResponse() {
12003        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12004                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12005                DEFAULT_VERIFICATION_RESPONSE);
12006    }
12007
12008    /**
12009     * Check whether or not package verification has been enabled.
12010     *
12011     * @return true if verification should be performed
12012     */
12013    private boolean isVerificationEnabled(int userId, int installFlags) {
12014        if (!DEFAULT_VERIFY_ENABLE) {
12015            return false;
12016        }
12017        // Ephemeral apps don't get the full verification treatment
12018        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12019            if (DEBUG_EPHEMERAL) {
12020                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12021            }
12022            return false;
12023        }
12024
12025        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12026
12027        // Check if installing from ADB
12028        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12029            // Do not run verification in a test harness environment
12030            if (ActivityManager.isRunningInTestHarness()) {
12031                return false;
12032            }
12033            if (ensureVerifyAppsEnabled) {
12034                return true;
12035            }
12036            // Check if the developer does not want package verification for ADB installs
12037            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12038                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12039                return false;
12040            }
12041        }
12042
12043        if (ensureVerifyAppsEnabled) {
12044            return true;
12045        }
12046
12047        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12048                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12049    }
12050
12051    @Override
12052    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12053            throws RemoteException {
12054        mContext.enforceCallingOrSelfPermission(
12055                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12056                "Only intentfilter verification agents can verify applications");
12057
12058        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12059        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12060                Binder.getCallingUid(), verificationCode, failedDomains);
12061        msg.arg1 = id;
12062        msg.obj = response;
12063        mHandler.sendMessage(msg);
12064    }
12065
12066    @Override
12067    public int getIntentVerificationStatus(String packageName, int userId) {
12068        synchronized (mPackages) {
12069            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12070        }
12071    }
12072
12073    @Override
12074    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12075        mContext.enforceCallingOrSelfPermission(
12076                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12077
12078        boolean result = false;
12079        synchronized (mPackages) {
12080            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12081        }
12082        if (result) {
12083            scheduleWritePackageRestrictionsLocked(userId);
12084        }
12085        return result;
12086    }
12087
12088    @Override
12089    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12090            String packageName) {
12091        synchronized (mPackages) {
12092            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12093        }
12094    }
12095
12096    @Override
12097    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12098        if (TextUtils.isEmpty(packageName)) {
12099            return ParceledListSlice.emptyList();
12100        }
12101        synchronized (mPackages) {
12102            PackageParser.Package pkg = mPackages.get(packageName);
12103            if (pkg == null || pkg.activities == null) {
12104                return ParceledListSlice.emptyList();
12105            }
12106            final int count = pkg.activities.size();
12107            ArrayList<IntentFilter> result = new ArrayList<>();
12108            for (int n=0; n<count; n++) {
12109                PackageParser.Activity activity = pkg.activities.get(n);
12110                if (activity.intents != null && activity.intents.size() > 0) {
12111                    result.addAll(activity.intents);
12112                }
12113            }
12114            return new ParceledListSlice<>(result);
12115        }
12116    }
12117
12118    @Override
12119    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12120        mContext.enforceCallingOrSelfPermission(
12121                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12122
12123        synchronized (mPackages) {
12124            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12125            if (packageName != null) {
12126                result |= updateIntentVerificationStatus(packageName,
12127                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12128                        userId);
12129                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12130                        packageName, userId);
12131            }
12132            return result;
12133        }
12134    }
12135
12136    @Override
12137    public String getDefaultBrowserPackageName(int userId) {
12138        synchronized (mPackages) {
12139            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12140        }
12141    }
12142
12143    /**
12144     * Get the "allow unknown sources" setting.
12145     *
12146     * @return the current "allow unknown sources" setting
12147     */
12148    private int getUnknownSourcesSettings() {
12149        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12150                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12151                -1);
12152    }
12153
12154    @Override
12155    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12156        final int uid = Binder.getCallingUid();
12157        // writer
12158        synchronized (mPackages) {
12159            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12160            if (targetPackageSetting == null) {
12161                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12162            }
12163
12164            PackageSetting installerPackageSetting;
12165            if (installerPackageName != null) {
12166                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12167                if (installerPackageSetting == null) {
12168                    throw new IllegalArgumentException("Unknown installer package: "
12169                            + installerPackageName);
12170                }
12171            } else {
12172                installerPackageSetting = null;
12173            }
12174
12175            Signature[] callerSignature;
12176            Object obj = mSettings.getUserIdLPr(uid);
12177            if (obj != null) {
12178                if (obj instanceof SharedUserSetting) {
12179                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12180                } else if (obj instanceof PackageSetting) {
12181                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12182                } else {
12183                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12184                }
12185            } else {
12186                throw new SecurityException("Unknown calling UID: " + uid);
12187            }
12188
12189            // Verify: can't set installerPackageName to a package that is
12190            // not signed with the same cert as the caller.
12191            if (installerPackageSetting != null) {
12192                if (compareSignatures(callerSignature,
12193                        installerPackageSetting.signatures.mSignatures)
12194                        != PackageManager.SIGNATURE_MATCH) {
12195                    throw new SecurityException(
12196                            "Caller does not have same cert as new installer package "
12197                            + installerPackageName);
12198                }
12199            }
12200
12201            // Verify: if target already has an installer package, it must
12202            // be signed with the same cert as the caller.
12203            if (targetPackageSetting.installerPackageName != null) {
12204                PackageSetting setting = mSettings.mPackages.get(
12205                        targetPackageSetting.installerPackageName);
12206                // If the currently set package isn't valid, then it's always
12207                // okay to change it.
12208                if (setting != null) {
12209                    if (compareSignatures(callerSignature,
12210                            setting.signatures.mSignatures)
12211                            != PackageManager.SIGNATURE_MATCH) {
12212                        throw new SecurityException(
12213                                "Caller does not have same cert as old installer package "
12214                                + targetPackageSetting.installerPackageName);
12215                    }
12216                }
12217            }
12218
12219            // Okay!
12220            targetPackageSetting.installerPackageName = installerPackageName;
12221            if (installerPackageName != null) {
12222                mSettings.mInstallerPackages.add(installerPackageName);
12223            }
12224            scheduleWriteSettingsLocked();
12225        }
12226    }
12227
12228    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12229        // Queue up an async operation since the package installation may take a little while.
12230        mHandler.post(new Runnable() {
12231            public void run() {
12232                mHandler.removeCallbacks(this);
12233                 // Result object to be returned
12234                PackageInstalledInfo res = new PackageInstalledInfo();
12235                res.setReturnCode(currentStatus);
12236                res.uid = -1;
12237                res.pkg = null;
12238                res.removedInfo = null;
12239                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12240                    args.doPreInstall(res.returnCode);
12241                    synchronized (mInstallLock) {
12242                        installPackageTracedLI(args, res);
12243                    }
12244                    args.doPostInstall(res.returnCode, res.uid);
12245                }
12246
12247                // A restore should be performed at this point if (a) the install
12248                // succeeded, (b) the operation is not an update, and (c) the new
12249                // package has not opted out of backup participation.
12250                final boolean update = res.removedInfo != null
12251                        && res.removedInfo.removedPackage != null;
12252                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12253                boolean doRestore = !update
12254                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12255
12256                // Set up the post-install work request bookkeeping.  This will be used
12257                // and cleaned up by the post-install event handling regardless of whether
12258                // there's a restore pass performed.  Token values are >= 1.
12259                int token;
12260                if (mNextInstallToken < 0) mNextInstallToken = 1;
12261                token = mNextInstallToken++;
12262
12263                PostInstallData data = new PostInstallData(args, res);
12264                mRunningInstalls.put(token, data);
12265                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12266
12267                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12268                    // Pass responsibility to the Backup Manager.  It will perform a
12269                    // restore if appropriate, then pass responsibility back to the
12270                    // Package Manager to run the post-install observer callbacks
12271                    // and broadcasts.
12272                    IBackupManager bm = IBackupManager.Stub.asInterface(
12273                            ServiceManager.getService(Context.BACKUP_SERVICE));
12274                    if (bm != null) {
12275                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12276                                + " to BM for possible restore");
12277                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12278                        try {
12279                            // TODO: http://b/22388012
12280                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12281                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12282                            } else {
12283                                doRestore = false;
12284                            }
12285                        } catch (RemoteException e) {
12286                            // can't happen; the backup manager is local
12287                        } catch (Exception e) {
12288                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12289                            doRestore = false;
12290                        }
12291                    } else {
12292                        Slog.e(TAG, "Backup Manager not found!");
12293                        doRestore = false;
12294                    }
12295                }
12296
12297                if (!doRestore) {
12298                    // No restore possible, or the Backup Manager was mysteriously not
12299                    // available -- just fire the post-install work request directly.
12300                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12301
12302                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12303
12304                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12305                    mHandler.sendMessage(msg);
12306                }
12307            }
12308        });
12309    }
12310
12311    /**
12312     * Callback from PackageSettings whenever an app is first transitioned out of the
12313     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12314     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12315     * here whether the app is the target of an ongoing install, and only send the
12316     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12317     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12318     * handling.
12319     */
12320    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12321        // Serialize this with the rest of the install-process message chain.  In the
12322        // restore-at-install case, this Runnable will necessarily run before the
12323        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12324        // are coherent.  In the non-restore case, the app has already completed install
12325        // and been launched through some other means, so it is not in a problematic
12326        // state for observers to see the FIRST_LAUNCH signal.
12327        mHandler.post(new Runnable() {
12328            @Override
12329            public void run() {
12330                for (int i = 0; i < mRunningInstalls.size(); i++) {
12331                    final PostInstallData data = mRunningInstalls.valueAt(i);
12332                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12333                        // right package; but is it for the right user?
12334                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12335                            if (userId == data.res.newUsers[uIndex]) {
12336                                if (DEBUG_BACKUP) {
12337                                    Slog.i(TAG, "Package " + pkgName
12338                                            + " being restored so deferring FIRST_LAUNCH");
12339                                }
12340                                return;
12341                            }
12342                        }
12343                    }
12344                }
12345                // didn't find it, so not being restored
12346                if (DEBUG_BACKUP) {
12347                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12348                }
12349                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12350            }
12351        });
12352    }
12353
12354    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12355        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12356                installerPkg, null, userIds);
12357    }
12358
12359    private abstract class HandlerParams {
12360        private static final int MAX_RETRIES = 4;
12361
12362        /**
12363         * Number of times startCopy() has been attempted and had a non-fatal
12364         * error.
12365         */
12366        private int mRetries = 0;
12367
12368        /** User handle for the user requesting the information or installation. */
12369        private final UserHandle mUser;
12370        String traceMethod;
12371        int traceCookie;
12372
12373        HandlerParams(UserHandle user) {
12374            mUser = user;
12375        }
12376
12377        UserHandle getUser() {
12378            return mUser;
12379        }
12380
12381        HandlerParams setTraceMethod(String traceMethod) {
12382            this.traceMethod = traceMethod;
12383            return this;
12384        }
12385
12386        HandlerParams setTraceCookie(int traceCookie) {
12387            this.traceCookie = traceCookie;
12388            return this;
12389        }
12390
12391        final boolean startCopy() {
12392            boolean res;
12393            try {
12394                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12395
12396                if (++mRetries > MAX_RETRIES) {
12397                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12398                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12399                    handleServiceError();
12400                    return false;
12401                } else {
12402                    handleStartCopy();
12403                    res = true;
12404                }
12405            } catch (RemoteException e) {
12406                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12407                mHandler.sendEmptyMessage(MCS_RECONNECT);
12408                res = false;
12409            }
12410            handleReturnCode();
12411            return res;
12412        }
12413
12414        final void serviceError() {
12415            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12416            handleServiceError();
12417            handleReturnCode();
12418        }
12419
12420        abstract void handleStartCopy() throws RemoteException;
12421        abstract void handleServiceError();
12422        abstract void handleReturnCode();
12423    }
12424
12425    class MeasureParams extends HandlerParams {
12426        private final PackageStats mStats;
12427        private boolean mSuccess;
12428
12429        private final IPackageStatsObserver mObserver;
12430
12431        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12432            super(new UserHandle(stats.userHandle));
12433            mObserver = observer;
12434            mStats = stats;
12435        }
12436
12437        @Override
12438        public String toString() {
12439            return "MeasureParams{"
12440                + Integer.toHexString(System.identityHashCode(this))
12441                + " " + mStats.packageName + "}";
12442        }
12443
12444        @Override
12445        void handleStartCopy() throws RemoteException {
12446            synchronized (mInstallLock) {
12447                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12448            }
12449
12450            if (mSuccess) {
12451                final boolean mounted;
12452                if (Environment.isExternalStorageEmulated()) {
12453                    mounted = true;
12454                } else {
12455                    final String status = Environment.getExternalStorageState();
12456                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12457                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12458                }
12459
12460                if (mounted) {
12461                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12462
12463                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12464                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12465
12466                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12467                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12468
12469                    // Always subtract cache size, since it's a subdirectory
12470                    mStats.externalDataSize -= mStats.externalCacheSize;
12471
12472                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12473                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12474
12475                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12476                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12477                }
12478            }
12479        }
12480
12481        @Override
12482        void handleReturnCode() {
12483            if (mObserver != null) {
12484                try {
12485                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12486                } catch (RemoteException e) {
12487                    Slog.i(TAG, "Observer no longer exists.");
12488                }
12489            }
12490        }
12491
12492        @Override
12493        void handleServiceError() {
12494            Slog.e(TAG, "Could not measure application " + mStats.packageName
12495                            + " external storage");
12496        }
12497    }
12498
12499    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12500            throws RemoteException {
12501        long result = 0;
12502        for (File path : paths) {
12503            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12504        }
12505        return result;
12506    }
12507
12508    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12509        for (File path : paths) {
12510            try {
12511                mcs.clearDirectory(path.getAbsolutePath());
12512            } catch (RemoteException e) {
12513            }
12514        }
12515    }
12516
12517    static class OriginInfo {
12518        /**
12519         * Location where install is coming from, before it has been
12520         * copied/renamed into place. This could be a single monolithic APK
12521         * file, or a cluster directory. This location may be untrusted.
12522         */
12523        final File file;
12524        final String cid;
12525
12526        /**
12527         * Flag indicating that {@link #file} or {@link #cid} has already been
12528         * staged, meaning downstream users don't need to defensively copy the
12529         * contents.
12530         */
12531        final boolean staged;
12532
12533        /**
12534         * Flag indicating that {@link #file} or {@link #cid} is an already
12535         * installed app that is being moved.
12536         */
12537        final boolean existing;
12538
12539        final String resolvedPath;
12540        final File resolvedFile;
12541
12542        static OriginInfo fromNothing() {
12543            return new OriginInfo(null, null, false, false);
12544        }
12545
12546        static OriginInfo fromUntrustedFile(File file) {
12547            return new OriginInfo(file, null, false, false);
12548        }
12549
12550        static OriginInfo fromExistingFile(File file) {
12551            return new OriginInfo(file, null, false, true);
12552        }
12553
12554        static OriginInfo fromStagedFile(File file) {
12555            return new OriginInfo(file, null, true, false);
12556        }
12557
12558        static OriginInfo fromStagedContainer(String cid) {
12559            return new OriginInfo(null, cid, true, false);
12560        }
12561
12562        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12563            this.file = file;
12564            this.cid = cid;
12565            this.staged = staged;
12566            this.existing = existing;
12567
12568            if (cid != null) {
12569                resolvedPath = PackageHelper.getSdDir(cid);
12570                resolvedFile = new File(resolvedPath);
12571            } else if (file != null) {
12572                resolvedPath = file.getAbsolutePath();
12573                resolvedFile = file;
12574            } else {
12575                resolvedPath = null;
12576                resolvedFile = null;
12577            }
12578        }
12579    }
12580
12581    static class MoveInfo {
12582        final int moveId;
12583        final String fromUuid;
12584        final String toUuid;
12585        final String packageName;
12586        final String dataAppName;
12587        final int appId;
12588        final String seinfo;
12589        final int targetSdkVersion;
12590
12591        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12592                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12593            this.moveId = moveId;
12594            this.fromUuid = fromUuid;
12595            this.toUuid = toUuid;
12596            this.packageName = packageName;
12597            this.dataAppName = dataAppName;
12598            this.appId = appId;
12599            this.seinfo = seinfo;
12600            this.targetSdkVersion = targetSdkVersion;
12601        }
12602    }
12603
12604    static class VerificationInfo {
12605        /** A constant used to indicate that a uid value is not present. */
12606        public static final int NO_UID = -1;
12607
12608        /** URI referencing where the package was downloaded from. */
12609        final Uri originatingUri;
12610
12611        /** HTTP referrer URI associated with the originatingURI. */
12612        final Uri referrer;
12613
12614        /** UID of the application that the install request originated from. */
12615        final int originatingUid;
12616
12617        /** UID of application requesting the install */
12618        final int installerUid;
12619
12620        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12621            this.originatingUri = originatingUri;
12622            this.referrer = referrer;
12623            this.originatingUid = originatingUid;
12624            this.installerUid = installerUid;
12625        }
12626    }
12627
12628    class InstallParams extends HandlerParams {
12629        final OriginInfo origin;
12630        final MoveInfo move;
12631        final IPackageInstallObserver2 observer;
12632        int installFlags;
12633        final String installerPackageName;
12634        final String volumeUuid;
12635        private InstallArgs mArgs;
12636        private int mRet;
12637        final String packageAbiOverride;
12638        final String[] grantedRuntimePermissions;
12639        final VerificationInfo verificationInfo;
12640        final Certificate[][] certificates;
12641
12642        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12643                int installFlags, String installerPackageName, String volumeUuid,
12644                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12645                String[] grantedPermissions, Certificate[][] certificates) {
12646            super(user);
12647            this.origin = origin;
12648            this.move = move;
12649            this.observer = observer;
12650            this.installFlags = installFlags;
12651            this.installerPackageName = installerPackageName;
12652            this.volumeUuid = volumeUuid;
12653            this.verificationInfo = verificationInfo;
12654            this.packageAbiOverride = packageAbiOverride;
12655            this.grantedRuntimePermissions = grantedPermissions;
12656            this.certificates = certificates;
12657        }
12658
12659        @Override
12660        public String toString() {
12661            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12662                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12663        }
12664
12665        private int installLocationPolicy(PackageInfoLite pkgLite) {
12666            String packageName = pkgLite.packageName;
12667            int installLocation = pkgLite.installLocation;
12668            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12669            // reader
12670            synchronized (mPackages) {
12671                // Currently installed package which the new package is attempting to replace or
12672                // null if no such package is installed.
12673                PackageParser.Package installedPkg = mPackages.get(packageName);
12674                // Package which currently owns the data which the new package will own if installed.
12675                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12676                // will be null whereas dataOwnerPkg will contain information about the package
12677                // which was uninstalled while keeping its data.
12678                PackageParser.Package dataOwnerPkg = installedPkg;
12679                if (dataOwnerPkg  == null) {
12680                    PackageSetting ps = mSettings.mPackages.get(packageName);
12681                    if (ps != null) {
12682                        dataOwnerPkg = ps.pkg;
12683                    }
12684                }
12685
12686                if (dataOwnerPkg != null) {
12687                    // If installed, the package will get access to data left on the device by its
12688                    // predecessor. As a security measure, this is permited only if this is not a
12689                    // version downgrade or if the predecessor package is marked as debuggable and
12690                    // a downgrade is explicitly requested.
12691                    //
12692                    // On debuggable platform builds, downgrades are permitted even for
12693                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12694                    // not offer security guarantees and thus it's OK to disable some security
12695                    // mechanisms to make debugging/testing easier on those builds. However, even on
12696                    // debuggable builds downgrades of packages are permitted only if requested via
12697                    // installFlags. This is because we aim to keep the behavior of debuggable
12698                    // platform builds as close as possible to the behavior of non-debuggable
12699                    // platform builds.
12700                    final boolean downgradeRequested =
12701                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12702                    final boolean packageDebuggable =
12703                                (dataOwnerPkg.applicationInfo.flags
12704                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12705                    final boolean downgradePermitted =
12706                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12707                    if (!downgradePermitted) {
12708                        try {
12709                            checkDowngrade(dataOwnerPkg, pkgLite);
12710                        } catch (PackageManagerException e) {
12711                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12712                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12713                        }
12714                    }
12715                }
12716
12717                if (installedPkg != null) {
12718                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12719                        // Check for updated system application.
12720                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12721                            if (onSd) {
12722                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12723                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12724                            }
12725                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12726                        } else {
12727                            if (onSd) {
12728                                // Install flag overrides everything.
12729                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12730                            }
12731                            // If current upgrade specifies particular preference
12732                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12733                                // Application explicitly specified internal.
12734                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12735                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12736                                // App explictly prefers external. Let policy decide
12737                            } else {
12738                                // Prefer previous location
12739                                if (isExternal(installedPkg)) {
12740                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12741                                }
12742                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12743                            }
12744                        }
12745                    } else {
12746                        // Invalid install. Return error code
12747                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12748                    }
12749                }
12750            }
12751            // All the special cases have been taken care of.
12752            // Return result based on recommended install location.
12753            if (onSd) {
12754                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12755            }
12756            return pkgLite.recommendedInstallLocation;
12757        }
12758
12759        /*
12760         * Invoke remote method to get package information and install
12761         * location values. Override install location based on default
12762         * policy if needed and then create install arguments based
12763         * on the install location.
12764         */
12765        public void handleStartCopy() throws RemoteException {
12766            int ret = PackageManager.INSTALL_SUCCEEDED;
12767
12768            // If we're already staged, we've firmly committed to an install location
12769            if (origin.staged) {
12770                if (origin.file != null) {
12771                    installFlags |= PackageManager.INSTALL_INTERNAL;
12772                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12773                } else if (origin.cid != null) {
12774                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12775                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12776                } else {
12777                    throw new IllegalStateException("Invalid stage location");
12778                }
12779            }
12780
12781            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12782            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12783            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12784            PackageInfoLite pkgLite = null;
12785
12786            if (onInt && onSd) {
12787                // Check if both bits are set.
12788                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12789                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12790            } else if (onSd && ephemeral) {
12791                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12792                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12793            } else {
12794                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12795                        packageAbiOverride);
12796
12797                if (DEBUG_EPHEMERAL && ephemeral) {
12798                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12799                }
12800
12801                /*
12802                 * If we have too little free space, try to free cache
12803                 * before giving up.
12804                 */
12805                if (!origin.staged && pkgLite.recommendedInstallLocation
12806                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12807                    // TODO: focus freeing disk space on the target device
12808                    final StorageManager storage = StorageManager.from(mContext);
12809                    final long lowThreshold = storage.getStorageLowBytes(
12810                            Environment.getDataDirectory());
12811
12812                    final long sizeBytes = mContainerService.calculateInstalledSize(
12813                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12814
12815                    try {
12816                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12817                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12818                                installFlags, packageAbiOverride);
12819                    } catch (InstallerException e) {
12820                        Slog.w(TAG, "Failed to free cache", e);
12821                    }
12822
12823                    /*
12824                     * The cache free must have deleted the file we
12825                     * downloaded to install.
12826                     *
12827                     * TODO: fix the "freeCache" call to not delete
12828                     *       the file we care about.
12829                     */
12830                    if (pkgLite.recommendedInstallLocation
12831                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12832                        pkgLite.recommendedInstallLocation
12833                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12834                    }
12835                }
12836            }
12837
12838            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12839                int loc = pkgLite.recommendedInstallLocation;
12840                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12841                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12842                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12843                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12845                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12846                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12847                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12848                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12849                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12850                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12851                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12852                } else {
12853                    // Override with defaults if needed.
12854                    loc = installLocationPolicy(pkgLite);
12855                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12856                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12857                    } else if (!onSd && !onInt) {
12858                        // Override install location with flags
12859                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12860                            // Set the flag to install on external media.
12861                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12862                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12863                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12864                            if (DEBUG_EPHEMERAL) {
12865                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12866                            }
12867                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12868                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12869                                    |PackageManager.INSTALL_INTERNAL);
12870                        } else {
12871                            // Make sure the flag for installing on external
12872                            // media is unset
12873                            installFlags |= PackageManager.INSTALL_INTERNAL;
12874                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12875                        }
12876                    }
12877                }
12878            }
12879
12880            final InstallArgs args = createInstallArgs(this);
12881            mArgs = args;
12882
12883            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12884                // TODO: http://b/22976637
12885                // Apps installed for "all" users use the device owner to verify the app
12886                UserHandle verifierUser = getUser();
12887                if (verifierUser == UserHandle.ALL) {
12888                    verifierUser = UserHandle.SYSTEM;
12889                }
12890
12891                /*
12892                 * Determine if we have any installed package verifiers. If we
12893                 * do, then we'll defer to them to verify the packages.
12894                 */
12895                final int requiredUid = mRequiredVerifierPackage == null ? -1
12896                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12897                                verifierUser.getIdentifier());
12898                if (!origin.existing && requiredUid != -1
12899                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12900                    final Intent verification = new Intent(
12901                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12902                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12903                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12904                            PACKAGE_MIME_TYPE);
12905                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12906
12907                    // Query all live verifiers based on current user state
12908                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12909                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12910
12911                    if (DEBUG_VERIFY) {
12912                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12913                                + verification.toString() + " with " + pkgLite.verifiers.length
12914                                + " optional verifiers");
12915                    }
12916
12917                    final int verificationId = mPendingVerificationToken++;
12918
12919                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12920
12921                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12922                            installerPackageName);
12923
12924                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12925                            installFlags);
12926
12927                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12928                            pkgLite.packageName);
12929
12930                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12931                            pkgLite.versionCode);
12932
12933                    if (verificationInfo != null) {
12934                        if (verificationInfo.originatingUri != null) {
12935                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12936                                    verificationInfo.originatingUri);
12937                        }
12938                        if (verificationInfo.referrer != null) {
12939                            verification.putExtra(Intent.EXTRA_REFERRER,
12940                                    verificationInfo.referrer);
12941                        }
12942                        if (verificationInfo.originatingUid >= 0) {
12943                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12944                                    verificationInfo.originatingUid);
12945                        }
12946                        if (verificationInfo.installerUid >= 0) {
12947                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12948                                    verificationInfo.installerUid);
12949                        }
12950                    }
12951
12952                    final PackageVerificationState verificationState = new PackageVerificationState(
12953                            requiredUid, args);
12954
12955                    mPendingVerification.append(verificationId, verificationState);
12956
12957                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12958                            receivers, verificationState);
12959
12960                    /*
12961                     * If any sufficient verifiers were listed in the package
12962                     * manifest, attempt to ask them.
12963                     */
12964                    if (sufficientVerifiers != null) {
12965                        final int N = sufficientVerifiers.size();
12966                        if (N == 0) {
12967                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12968                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12969                        } else {
12970                            for (int i = 0; i < N; i++) {
12971                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12972
12973                                final Intent sufficientIntent = new Intent(verification);
12974                                sufficientIntent.setComponent(verifierComponent);
12975                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12976                            }
12977                        }
12978                    }
12979
12980                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12981                            mRequiredVerifierPackage, receivers);
12982                    if (ret == PackageManager.INSTALL_SUCCEEDED
12983                            && mRequiredVerifierPackage != null) {
12984                        Trace.asyncTraceBegin(
12985                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12986                        /*
12987                         * Send the intent to the required verification agent,
12988                         * but only start the verification timeout after the
12989                         * target BroadcastReceivers have run.
12990                         */
12991                        verification.setComponent(requiredVerifierComponent);
12992                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12993                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12994                                new BroadcastReceiver() {
12995                                    @Override
12996                                    public void onReceive(Context context, Intent intent) {
12997                                        final Message msg = mHandler
12998                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12999                                        msg.arg1 = verificationId;
13000                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13001                                    }
13002                                }, null, 0, null, null);
13003
13004                        /*
13005                         * We don't want the copy to proceed until verification
13006                         * succeeds, so null out this field.
13007                         */
13008                        mArgs = null;
13009                    }
13010                } else {
13011                    /*
13012                     * No package verification is enabled, so immediately start
13013                     * the remote call to initiate copy using temporary file.
13014                     */
13015                    ret = args.copyApk(mContainerService, true);
13016                }
13017            }
13018
13019            mRet = ret;
13020        }
13021
13022        @Override
13023        void handleReturnCode() {
13024            // If mArgs is null, then MCS couldn't be reached. When it
13025            // reconnects, it will try again to install. At that point, this
13026            // will succeed.
13027            if (mArgs != null) {
13028                processPendingInstall(mArgs, mRet);
13029            }
13030        }
13031
13032        @Override
13033        void handleServiceError() {
13034            mArgs = createInstallArgs(this);
13035            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13036        }
13037
13038        public boolean isForwardLocked() {
13039            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13040        }
13041    }
13042
13043    /**
13044     * Used during creation of InstallArgs
13045     *
13046     * @param installFlags package installation flags
13047     * @return true if should be installed on external storage
13048     */
13049    private static boolean installOnExternalAsec(int installFlags) {
13050        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13051            return false;
13052        }
13053        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13054            return true;
13055        }
13056        return false;
13057    }
13058
13059    /**
13060     * Used during creation of InstallArgs
13061     *
13062     * @param installFlags package installation flags
13063     * @return true if should be installed as forward locked
13064     */
13065    private static boolean installForwardLocked(int installFlags) {
13066        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13067    }
13068
13069    private InstallArgs createInstallArgs(InstallParams params) {
13070        if (params.move != null) {
13071            return new MoveInstallArgs(params);
13072        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13073            return new AsecInstallArgs(params);
13074        } else {
13075            return new FileInstallArgs(params);
13076        }
13077    }
13078
13079    /**
13080     * Create args that describe an existing installed package. Typically used
13081     * when cleaning up old installs, or used as a move source.
13082     */
13083    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13084            String resourcePath, String[] instructionSets) {
13085        final boolean isInAsec;
13086        if (installOnExternalAsec(installFlags)) {
13087            /* Apps on SD card are always in ASEC containers. */
13088            isInAsec = true;
13089        } else if (installForwardLocked(installFlags)
13090                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13091            /*
13092             * Forward-locked apps are only in ASEC containers if they're the
13093             * new style
13094             */
13095            isInAsec = true;
13096        } else {
13097            isInAsec = false;
13098        }
13099
13100        if (isInAsec) {
13101            return new AsecInstallArgs(codePath, instructionSets,
13102                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13103        } else {
13104            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13105        }
13106    }
13107
13108    static abstract class InstallArgs {
13109        /** @see InstallParams#origin */
13110        final OriginInfo origin;
13111        /** @see InstallParams#move */
13112        final MoveInfo move;
13113
13114        final IPackageInstallObserver2 observer;
13115        // Always refers to PackageManager flags only
13116        final int installFlags;
13117        final String installerPackageName;
13118        final String volumeUuid;
13119        final UserHandle user;
13120        final String abiOverride;
13121        final String[] installGrantPermissions;
13122        /** If non-null, drop an async trace when the install completes */
13123        final String traceMethod;
13124        final int traceCookie;
13125        final Certificate[][] certificates;
13126
13127        // The list of instruction sets supported by this app. This is currently
13128        // only used during the rmdex() phase to clean up resources. We can get rid of this
13129        // if we move dex files under the common app path.
13130        /* nullable */ String[] instructionSets;
13131
13132        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13133                int installFlags, String installerPackageName, String volumeUuid,
13134                UserHandle user, String[] instructionSets,
13135                String abiOverride, String[] installGrantPermissions,
13136                String traceMethod, int traceCookie, Certificate[][] certificates) {
13137            this.origin = origin;
13138            this.move = move;
13139            this.installFlags = installFlags;
13140            this.observer = observer;
13141            this.installerPackageName = installerPackageName;
13142            this.volumeUuid = volumeUuid;
13143            this.user = user;
13144            this.instructionSets = instructionSets;
13145            this.abiOverride = abiOverride;
13146            this.installGrantPermissions = installGrantPermissions;
13147            this.traceMethod = traceMethod;
13148            this.traceCookie = traceCookie;
13149            this.certificates = certificates;
13150        }
13151
13152        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13153        abstract int doPreInstall(int status);
13154
13155        /**
13156         * Rename package into final resting place. All paths on the given
13157         * scanned package should be updated to reflect the rename.
13158         */
13159        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13160        abstract int doPostInstall(int status, int uid);
13161
13162        /** @see PackageSettingBase#codePathString */
13163        abstract String getCodePath();
13164        /** @see PackageSettingBase#resourcePathString */
13165        abstract String getResourcePath();
13166
13167        // Need installer lock especially for dex file removal.
13168        abstract void cleanUpResourcesLI();
13169        abstract boolean doPostDeleteLI(boolean delete);
13170
13171        /**
13172         * Called before the source arguments are copied. This is used mostly
13173         * for MoveParams when it needs to read the source file to put it in the
13174         * destination.
13175         */
13176        int doPreCopy() {
13177            return PackageManager.INSTALL_SUCCEEDED;
13178        }
13179
13180        /**
13181         * Called after the source arguments are copied. This is used mostly for
13182         * MoveParams when it needs to read the source file to put it in the
13183         * destination.
13184         */
13185        int doPostCopy(int uid) {
13186            return PackageManager.INSTALL_SUCCEEDED;
13187        }
13188
13189        protected boolean isFwdLocked() {
13190            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13191        }
13192
13193        protected boolean isExternalAsec() {
13194            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13195        }
13196
13197        protected boolean isEphemeral() {
13198            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13199        }
13200
13201        UserHandle getUser() {
13202            return user;
13203        }
13204    }
13205
13206    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13207        if (!allCodePaths.isEmpty()) {
13208            if (instructionSets == null) {
13209                throw new IllegalStateException("instructionSet == null");
13210            }
13211            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13212            for (String codePath : allCodePaths) {
13213                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13214                    try {
13215                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13216                    } catch (InstallerException ignored) {
13217                    }
13218                }
13219            }
13220        }
13221    }
13222
13223    /**
13224     * Logic to handle installation of non-ASEC applications, including copying
13225     * and renaming logic.
13226     */
13227    class FileInstallArgs extends InstallArgs {
13228        private File codeFile;
13229        private File resourceFile;
13230
13231        // Example topology:
13232        // /data/app/com.example/base.apk
13233        // /data/app/com.example/split_foo.apk
13234        // /data/app/com.example/lib/arm/libfoo.so
13235        // /data/app/com.example/lib/arm64/libfoo.so
13236        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13237
13238        /** New install */
13239        FileInstallArgs(InstallParams params) {
13240            super(params.origin, params.move, params.observer, params.installFlags,
13241                    params.installerPackageName, params.volumeUuid,
13242                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13243                    params.grantedRuntimePermissions,
13244                    params.traceMethod, params.traceCookie, params.certificates);
13245            if (isFwdLocked()) {
13246                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13247            }
13248        }
13249
13250        /** Existing install */
13251        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13252            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13253                    null, null, null, 0, null /*certificates*/);
13254            this.codeFile = (codePath != null) ? new File(codePath) : null;
13255            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13256        }
13257
13258        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13259            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13260            try {
13261                return doCopyApk(imcs, temp);
13262            } finally {
13263                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13264            }
13265        }
13266
13267        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13268            if (origin.staged) {
13269                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13270                codeFile = origin.file;
13271                resourceFile = origin.file;
13272                return PackageManager.INSTALL_SUCCEEDED;
13273            }
13274
13275            try {
13276                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13277                final File tempDir =
13278                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13279                codeFile = tempDir;
13280                resourceFile = tempDir;
13281            } catch (IOException e) {
13282                Slog.w(TAG, "Failed to create copy file: " + e);
13283                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13284            }
13285
13286            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13287                @Override
13288                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13289                    if (!FileUtils.isValidExtFilename(name)) {
13290                        throw new IllegalArgumentException("Invalid filename: " + name);
13291                    }
13292                    try {
13293                        final File file = new File(codeFile, name);
13294                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13295                                O_RDWR | O_CREAT, 0644);
13296                        Os.chmod(file.getAbsolutePath(), 0644);
13297                        return new ParcelFileDescriptor(fd);
13298                    } catch (ErrnoException e) {
13299                        throw new RemoteException("Failed to open: " + e.getMessage());
13300                    }
13301                }
13302            };
13303
13304            int ret = PackageManager.INSTALL_SUCCEEDED;
13305            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13306            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13307                Slog.e(TAG, "Failed to copy package");
13308                return ret;
13309            }
13310
13311            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13312            NativeLibraryHelper.Handle handle = null;
13313            try {
13314                handle = NativeLibraryHelper.Handle.create(codeFile);
13315                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13316                        abiOverride);
13317            } catch (IOException e) {
13318                Slog.e(TAG, "Copying native libraries failed", e);
13319                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13320            } finally {
13321                IoUtils.closeQuietly(handle);
13322            }
13323
13324            return ret;
13325        }
13326
13327        int doPreInstall(int status) {
13328            if (status != PackageManager.INSTALL_SUCCEEDED) {
13329                cleanUp();
13330            }
13331            return status;
13332        }
13333
13334        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13335            if (status != PackageManager.INSTALL_SUCCEEDED) {
13336                cleanUp();
13337                return false;
13338            }
13339
13340            final File targetDir = codeFile.getParentFile();
13341            final File beforeCodeFile = codeFile;
13342            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13343
13344            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13345            try {
13346                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13347            } catch (ErrnoException e) {
13348                Slog.w(TAG, "Failed to rename", e);
13349                return false;
13350            }
13351
13352            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13353                Slog.w(TAG, "Failed to restorecon");
13354                return false;
13355            }
13356
13357            // Reflect the rename internally
13358            codeFile = afterCodeFile;
13359            resourceFile = afterCodeFile;
13360
13361            // Reflect the rename in scanned details
13362            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13363            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13364                    afterCodeFile, pkg.baseCodePath));
13365            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13366                    afterCodeFile, pkg.splitCodePaths));
13367
13368            // Reflect the rename in app info
13369            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13370            pkg.setApplicationInfoCodePath(pkg.codePath);
13371            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13372            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13373            pkg.setApplicationInfoResourcePath(pkg.codePath);
13374            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13375            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13376
13377            return true;
13378        }
13379
13380        int doPostInstall(int status, int uid) {
13381            if (status != PackageManager.INSTALL_SUCCEEDED) {
13382                cleanUp();
13383            }
13384            return status;
13385        }
13386
13387        @Override
13388        String getCodePath() {
13389            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13390        }
13391
13392        @Override
13393        String getResourcePath() {
13394            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13395        }
13396
13397        private boolean cleanUp() {
13398            if (codeFile == null || !codeFile.exists()) {
13399                return false;
13400            }
13401
13402            removeCodePathLI(codeFile);
13403
13404            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13405                resourceFile.delete();
13406            }
13407
13408            return true;
13409        }
13410
13411        void cleanUpResourcesLI() {
13412            // Try enumerating all code paths before deleting
13413            List<String> allCodePaths = Collections.EMPTY_LIST;
13414            if (codeFile != null && codeFile.exists()) {
13415                try {
13416                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13417                    allCodePaths = pkg.getAllCodePaths();
13418                } catch (PackageParserException e) {
13419                    // Ignored; we tried our best
13420                }
13421            }
13422
13423            cleanUp();
13424            removeDexFiles(allCodePaths, instructionSets);
13425        }
13426
13427        boolean doPostDeleteLI(boolean delete) {
13428            // XXX err, shouldn't we respect the delete flag?
13429            cleanUpResourcesLI();
13430            return true;
13431        }
13432    }
13433
13434    private boolean isAsecExternal(String cid) {
13435        final String asecPath = PackageHelper.getSdFilesystem(cid);
13436        return !asecPath.startsWith(mAsecInternalPath);
13437    }
13438
13439    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13440            PackageManagerException {
13441        if (copyRet < 0) {
13442            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13443                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13444                throw new PackageManagerException(copyRet, message);
13445            }
13446        }
13447    }
13448
13449    /**
13450     * Extract the MountService "container ID" from the full code path of an
13451     * .apk.
13452     */
13453    static String cidFromCodePath(String fullCodePath) {
13454        int eidx = fullCodePath.lastIndexOf("/");
13455        String subStr1 = fullCodePath.substring(0, eidx);
13456        int sidx = subStr1.lastIndexOf("/");
13457        return subStr1.substring(sidx+1, eidx);
13458    }
13459
13460    /**
13461     * Logic to handle installation of ASEC applications, including copying and
13462     * renaming logic.
13463     */
13464    class AsecInstallArgs extends InstallArgs {
13465        static final String RES_FILE_NAME = "pkg.apk";
13466        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13467
13468        String cid;
13469        String packagePath;
13470        String resourcePath;
13471
13472        /** New install */
13473        AsecInstallArgs(InstallParams params) {
13474            super(params.origin, params.move, params.observer, params.installFlags,
13475                    params.installerPackageName, params.volumeUuid,
13476                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13477                    params.grantedRuntimePermissions,
13478                    params.traceMethod, params.traceCookie, params.certificates);
13479        }
13480
13481        /** Existing install */
13482        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13483                        boolean isExternal, boolean isForwardLocked) {
13484            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13485              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13486                    instructionSets, null, null, null, 0, null /*certificates*/);
13487            // Hackily pretend we're still looking at a full code path
13488            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13489                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13490            }
13491
13492            // Extract cid from fullCodePath
13493            int eidx = fullCodePath.lastIndexOf("/");
13494            String subStr1 = fullCodePath.substring(0, eidx);
13495            int sidx = subStr1.lastIndexOf("/");
13496            cid = subStr1.substring(sidx+1, eidx);
13497            setMountPath(subStr1);
13498        }
13499
13500        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13501            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13502              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13503                    instructionSets, null, null, null, 0, null /*certificates*/);
13504            this.cid = cid;
13505            setMountPath(PackageHelper.getSdDir(cid));
13506        }
13507
13508        void createCopyFile() {
13509            cid = mInstallerService.allocateExternalStageCidLegacy();
13510        }
13511
13512        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13513            if (origin.staged && origin.cid != null) {
13514                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13515                cid = origin.cid;
13516                setMountPath(PackageHelper.getSdDir(cid));
13517                return PackageManager.INSTALL_SUCCEEDED;
13518            }
13519
13520            if (temp) {
13521                createCopyFile();
13522            } else {
13523                /*
13524                 * Pre-emptively destroy the container since it's destroyed if
13525                 * copying fails due to it existing anyway.
13526                 */
13527                PackageHelper.destroySdDir(cid);
13528            }
13529
13530            final String newMountPath = imcs.copyPackageToContainer(
13531                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13532                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13533
13534            if (newMountPath != null) {
13535                setMountPath(newMountPath);
13536                return PackageManager.INSTALL_SUCCEEDED;
13537            } else {
13538                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13539            }
13540        }
13541
13542        @Override
13543        String getCodePath() {
13544            return packagePath;
13545        }
13546
13547        @Override
13548        String getResourcePath() {
13549            return resourcePath;
13550        }
13551
13552        int doPreInstall(int status) {
13553            if (status != PackageManager.INSTALL_SUCCEEDED) {
13554                // Destroy container
13555                PackageHelper.destroySdDir(cid);
13556            } else {
13557                boolean mounted = PackageHelper.isContainerMounted(cid);
13558                if (!mounted) {
13559                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13560                            Process.SYSTEM_UID);
13561                    if (newMountPath != null) {
13562                        setMountPath(newMountPath);
13563                    } else {
13564                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13565                    }
13566                }
13567            }
13568            return status;
13569        }
13570
13571        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13572            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13573            String newMountPath = null;
13574            if (PackageHelper.isContainerMounted(cid)) {
13575                // Unmount the container
13576                if (!PackageHelper.unMountSdDir(cid)) {
13577                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13578                    return false;
13579                }
13580            }
13581            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13582                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13583                        " which might be stale. Will try to clean up.");
13584                // Clean up the stale container and proceed to recreate.
13585                if (!PackageHelper.destroySdDir(newCacheId)) {
13586                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13587                    return false;
13588                }
13589                // Successfully cleaned up stale container. Try to rename again.
13590                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13591                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13592                            + " inspite of cleaning it up.");
13593                    return false;
13594                }
13595            }
13596            if (!PackageHelper.isContainerMounted(newCacheId)) {
13597                Slog.w(TAG, "Mounting container " + newCacheId);
13598                newMountPath = PackageHelper.mountSdDir(newCacheId,
13599                        getEncryptKey(), Process.SYSTEM_UID);
13600            } else {
13601                newMountPath = PackageHelper.getSdDir(newCacheId);
13602            }
13603            if (newMountPath == null) {
13604                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13605                return false;
13606            }
13607            Log.i(TAG, "Succesfully renamed " + cid +
13608                    " to " + newCacheId +
13609                    " at new path: " + newMountPath);
13610            cid = newCacheId;
13611
13612            final File beforeCodeFile = new File(packagePath);
13613            setMountPath(newMountPath);
13614            final File afterCodeFile = new File(packagePath);
13615
13616            // Reflect the rename in scanned details
13617            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13618            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13619                    afterCodeFile, pkg.baseCodePath));
13620            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13621                    afterCodeFile, pkg.splitCodePaths));
13622
13623            // Reflect the rename in app info
13624            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13625            pkg.setApplicationInfoCodePath(pkg.codePath);
13626            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13627            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13628            pkg.setApplicationInfoResourcePath(pkg.codePath);
13629            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13630            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13631
13632            return true;
13633        }
13634
13635        private void setMountPath(String mountPath) {
13636            final File mountFile = new File(mountPath);
13637
13638            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13639            if (monolithicFile.exists()) {
13640                packagePath = monolithicFile.getAbsolutePath();
13641                if (isFwdLocked()) {
13642                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13643                } else {
13644                    resourcePath = packagePath;
13645                }
13646            } else {
13647                packagePath = mountFile.getAbsolutePath();
13648                resourcePath = packagePath;
13649            }
13650        }
13651
13652        int doPostInstall(int status, int uid) {
13653            if (status != PackageManager.INSTALL_SUCCEEDED) {
13654                cleanUp();
13655            } else {
13656                final int groupOwner;
13657                final String protectedFile;
13658                if (isFwdLocked()) {
13659                    groupOwner = UserHandle.getSharedAppGid(uid);
13660                    protectedFile = RES_FILE_NAME;
13661                } else {
13662                    groupOwner = -1;
13663                    protectedFile = null;
13664                }
13665
13666                if (uid < Process.FIRST_APPLICATION_UID
13667                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13668                    Slog.e(TAG, "Failed to finalize " + cid);
13669                    PackageHelper.destroySdDir(cid);
13670                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13671                }
13672
13673                boolean mounted = PackageHelper.isContainerMounted(cid);
13674                if (!mounted) {
13675                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13676                }
13677            }
13678            return status;
13679        }
13680
13681        private void cleanUp() {
13682            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13683
13684            // Destroy secure container
13685            PackageHelper.destroySdDir(cid);
13686        }
13687
13688        private List<String> getAllCodePaths() {
13689            final File codeFile = new File(getCodePath());
13690            if (codeFile != null && codeFile.exists()) {
13691                try {
13692                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13693                    return pkg.getAllCodePaths();
13694                } catch (PackageParserException e) {
13695                    // Ignored; we tried our best
13696                }
13697            }
13698            return Collections.EMPTY_LIST;
13699        }
13700
13701        void cleanUpResourcesLI() {
13702            // Enumerate all code paths before deleting
13703            cleanUpResourcesLI(getAllCodePaths());
13704        }
13705
13706        private void cleanUpResourcesLI(List<String> allCodePaths) {
13707            cleanUp();
13708            removeDexFiles(allCodePaths, instructionSets);
13709        }
13710
13711        String getPackageName() {
13712            return getAsecPackageName(cid);
13713        }
13714
13715        boolean doPostDeleteLI(boolean delete) {
13716            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13717            final List<String> allCodePaths = getAllCodePaths();
13718            boolean mounted = PackageHelper.isContainerMounted(cid);
13719            if (mounted) {
13720                // Unmount first
13721                if (PackageHelper.unMountSdDir(cid)) {
13722                    mounted = false;
13723                }
13724            }
13725            if (!mounted && delete) {
13726                cleanUpResourcesLI(allCodePaths);
13727            }
13728            return !mounted;
13729        }
13730
13731        @Override
13732        int doPreCopy() {
13733            if (isFwdLocked()) {
13734                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13735                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13736                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13737                }
13738            }
13739
13740            return PackageManager.INSTALL_SUCCEEDED;
13741        }
13742
13743        @Override
13744        int doPostCopy(int uid) {
13745            if (isFwdLocked()) {
13746                if (uid < Process.FIRST_APPLICATION_UID
13747                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13748                                RES_FILE_NAME)) {
13749                    Slog.e(TAG, "Failed to finalize " + cid);
13750                    PackageHelper.destroySdDir(cid);
13751                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13752                }
13753            }
13754
13755            return PackageManager.INSTALL_SUCCEEDED;
13756        }
13757    }
13758
13759    /**
13760     * Logic to handle movement of existing installed applications.
13761     */
13762    class MoveInstallArgs extends InstallArgs {
13763        private File codeFile;
13764        private File resourceFile;
13765
13766        /** New install */
13767        MoveInstallArgs(InstallParams params) {
13768            super(params.origin, params.move, params.observer, params.installFlags,
13769                    params.installerPackageName, params.volumeUuid,
13770                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13771                    params.grantedRuntimePermissions,
13772                    params.traceMethod, params.traceCookie, params.certificates);
13773        }
13774
13775        int copyApk(IMediaContainerService imcs, boolean temp) {
13776            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13777                    + move.fromUuid + " to " + move.toUuid);
13778            synchronized (mInstaller) {
13779                try {
13780                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13781                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13782                } catch (InstallerException e) {
13783                    Slog.w(TAG, "Failed to move app", e);
13784                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13785                }
13786            }
13787
13788            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13789            resourceFile = codeFile;
13790            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13791
13792            return PackageManager.INSTALL_SUCCEEDED;
13793        }
13794
13795        int doPreInstall(int status) {
13796            if (status != PackageManager.INSTALL_SUCCEEDED) {
13797                cleanUp(move.toUuid);
13798            }
13799            return status;
13800        }
13801
13802        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13803            if (status != PackageManager.INSTALL_SUCCEEDED) {
13804                cleanUp(move.toUuid);
13805                return false;
13806            }
13807
13808            // Reflect the move in app info
13809            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13810            pkg.setApplicationInfoCodePath(pkg.codePath);
13811            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13812            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13813            pkg.setApplicationInfoResourcePath(pkg.codePath);
13814            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13815            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13816
13817            return true;
13818        }
13819
13820        int doPostInstall(int status, int uid) {
13821            if (status == PackageManager.INSTALL_SUCCEEDED) {
13822                cleanUp(move.fromUuid);
13823            } else {
13824                cleanUp(move.toUuid);
13825            }
13826            return status;
13827        }
13828
13829        @Override
13830        String getCodePath() {
13831            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13832        }
13833
13834        @Override
13835        String getResourcePath() {
13836            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13837        }
13838
13839        private boolean cleanUp(String volumeUuid) {
13840            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13841                    move.dataAppName);
13842            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13843            final int[] userIds = sUserManager.getUserIds();
13844            synchronized (mInstallLock) {
13845                // Clean up both app data and code
13846                // All package moves are frozen until finished
13847                for (int userId : userIds) {
13848                    try {
13849                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13850                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13851                    } catch (InstallerException e) {
13852                        Slog.w(TAG, String.valueOf(e));
13853                    }
13854                }
13855                removeCodePathLI(codeFile);
13856            }
13857            return true;
13858        }
13859
13860        void cleanUpResourcesLI() {
13861            throw new UnsupportedOperationException();
13862        }
13863
13864        boolean doPostDeleteLI(boolean delete) {
13865            throw new UnsupportedOperationException();
13866        }
13867    }
13868
13869    static String getAsecPackageName(String packageCid) {
13870        int idx = packageCid.lastIndexOf("-");
13871        if (idx == -1) {
13872            return packageCid;
13873        }
13874        return packageCid.substring(0, idx);
13875    }
13876
13877    // Utility method used to create code paths based on package name and available index.
13878    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13879        String idxStr = "";
13880        int idx = 1;
13881        // Fall back to default value of idx=1 if prefix is not
13882        // part of oldCodePath
13883        if (oldCodePath != null) {
13884            String subStr = oldCodePath;
13885            // Drop the suffix right away
13886            if (suffix != null && subStr.endsWith(suffix)) {
13887                subStr = subStr.substring(0, subStr.length() - suffix.length());
13888            }
13889            // If oldCodePath already contains prefix find out the
13890            // ending index to either increment or decrement.
13891            int sidx = subStr.lastIndexOf(prefix);
13892            if (sidx != -1) {
13893                subStr = subStr.substring(sidx + prefix.length());
13894                if (subStr != null) {
13895                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13896                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13897                    }
13898                    try {
13899                        idx = Integer.parseInt(subStr);
13900                        if (idx <= 1) {
13901                            idx++;
13902                        } else {
13903                            idx--;
13904                        }
13905                    } catch(NumberFormatException e) {
13906                    }
13907                }
13908            }
13909        }
13910        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13911        return prefix + idxStr;
13912    }
13913
13914    private File getNextCodePath(File targetDir, String packageName) {
13915        int suffix = 1;
13916        File result;
13917        do {
13918            result = new File(targetDir, packageName + "-" + suffix);
13919            suffix++;
13920        } while (result.exists());
13921        return result;
13922    }
13923
13924    // Utility method that returns the relative package path with respect
13925    // to the installation directory. Like say for /data/data/com.test-1.apk
13926    // string com.test-1 is returned.
13927    static String deriveCodePathName(String codePath) {
13928        if (codePath == null) {
13929            return null;
13930        }
13931        final File codeFile = new File(codePath);
13932        final String name = codeFile.getName();
13933        if (codeFile.isDirectory()) {
13934            return name;
13935        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13936            final int lastDot = name.lastIndexOf('.');
13937            return name.substring(0, lastDot);
13938        } else {
13939            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13940            return null;
13941        }
13942    }
13943
13944    static class PackageInstalledInfo {
13945        String name;
13946        int uid;
13947        // The set of users that originally had this package installed.
13948        int[] origUsers;
13949        // The set of users that now have this package installed.
13950        int[] newUsers;
13951        PackageParser.Package pkg;
13952        int returnCode;
13953        String returnMsg;
13954        PackageRemovedInfo removedInfo;
13955        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13956
13957        public void setError(int code, String msg) {
13958            setReturnCode(code);
13959            setReturnMessage(msg);
13960            Slog.w(TAG, msg);
13961        }
13962
13963        public void setError(String msg, PackageParserException e) {
13964            setReturnCode(e.error);
13965            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13966            Slog.w(TAG, msg, e);
13967        }
13968
13969        public void setError(String msg, PackageManagerException e) {
13970            returnCode = e.error;
13971            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13972            Slog.w(TAG, msg, e);
13973        }
13974
13975        public void setReturnCode(int returnCode) {
13976            this.returnCode = returnCode;
13977            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13978            for (int i = 0; i < childCount; i++) {
13979                addedChildPackages.valueAt(i).returnCode = returnCode;
13980            }
13981        }
13982
13983        private void setReturnMessage(String returnMsg) {
13984            this.returnMsg = returnMsg;
13985            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13986            for (int i = 0; i < childCount; i++) {
13987                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13988            }
13989        }
13990
13991        // In some error cases we want to convey more info back to the observer
13992        String origPackage;
13993        String origPermission;
13994    }
13995
13996    /*
13997     * Install a non-existing package.
13998     */
13999    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14000            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14001            PackageInstalledInfo res) {
14002        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14003
14004        // Remember this for later, in case we need to rollback this install
14005        String pkgName = pkg.packageName;
14006
14007        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14008
14009        synchronized(mPackages) {
14010            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14011                // A package with the same name is already installed, though
14012                // it has been renamed to an older name.  The package we
14013                // are trying to install should be installed as an update to
14014                // the existing one, but that has not been requested, so bail.
14015                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14016                        + " without first uninstalling package running as "
14017                        + mSettings.mRenamedPackages.get(pkgName));
14018                return;
14019            }
14020            if (mPackages.containsKey(pkgName)) {
14021                // Don't allow installation over an existing package with the same name.
14022                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14023                        + " without first uninstalling.");
14024                return;
14025            }
14026        }
14027
14028        try {
14029            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14030                    System.currentTimeMillis(), user);
14031
14032            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14033
14034            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14035                prepareAppDataAfterInstallLIF(newPackage);
14036
14037            } else {
14038                // Remove package from internal structures, but keep around any
14039                // data that might have already existed
14040                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14041                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14042            }
14043        } catch (PackageManagerException e) {
14044            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14045        }
14046
14047        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14048    }
14049
14050    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14051        // Can't rotate keys during boot or if sharedUser.
14052        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14053                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14054            return false;
14055        }
14056        // app is using upgradeKeySets; make sure all are valid
14057        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14058        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14059        for (int i = 0; i < upgradeKeySets.length; i++) {
14060            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14061                Slog.wtf(TAG, "Package "
14062                         + (oldPs.name != null ? oldPs.name : "<null>")
14063                         + " contains upgrade-key-set reference to unknown key-set: "
14064                         + upgradeKeySets[i]
14065                         + " reverting to signatures check.");
14066                return false;
14067            }
14068        }
14069        return true;
14070    }
14071
14072    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14073        // Upgrade keysets are being used.  Determine if new package has a superset of the
14074        // required keys.
14075        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14076        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14077        for (int i = 0; i < upgradeKeySets.length; i++) {
14078            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14079            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14080                return true;
14081            }
14082        }
14083        return false;
14084    }
14085
14086    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14087        try (DigestInputStream digestStream =
14088                new DigestInputStream(new FileInputStream(file), digest)) {
14089            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14090        }
14091    }
14092
14093    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14094            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14095        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14096
14097        final PackageParser.Package oldPackage;
14098        final String pkgName = pkg.packageName;
14099        final int[] allUsers;
14100        final int[] installedUsers;
14101
14102        synchronized(mPackages) {
14103            oldPackage = mPackages.get(pkgName);
14104            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14105
14106            // don't allow upgrade to target a release SDK from a pre-release SDK
14107            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14108                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14109            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14110                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14111            if (oldTargetsPreRelease
14112                    && !newTargetsPreRelease
14113                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14114                Slog.w(TAG, "Can't install package targeting released sdk");
14115                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14116                return;
14117            }
14118
14119            // don't allow an upgrade from full to ephemeral
14120            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14121            if (isEphemeral && !oldIsEphemeral) {
14122                // can't downgrade from full to ephemeral
14123                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14124                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14125                return;
14126            }
14127
14128            // verify signatures are valid
14129            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14130            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14131                if (!checkUpgradeKeySetLP(ps, pkg)) {
14132                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14133                            "New package not signed by keys specified by upgrade-keysets: "
14134                                    + pkgName);
14135                    return;
14136                }
14137            } else {
14138                // default to original signature matching
14139                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14140                        != PackageManager.SIGNATURE_MATCH) {
14141                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14142                            "New package has a different signature: " + pkgName);
14143                    return;
14144                }
14145            }
14146
14147            // don't allow a system upgrade unless the upgrade hash matches
14148            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14149                byte[] digestBytes = null;
14150                try {
14151                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14152                    updateDigest(digest, new File(pkg.baseCodePath));
14153                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14154                        for (String path : pkg.splitCodePaths) {
14155                            updateDigest(digest, new File(path));
14156                        }
14157                    }
14158                    digestBytes = digest.digest();
14159                } catch (NoSuchAlgorithmException | IOException e) {
14160                    res.setError(INSTALL_FAILED_INVALID_APK,
14161                            "Could not compute hash: " + pkgName);
14162                    return;
14163                }
14164                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14165                    res.setError(INSTALL_FAILED_INVALID_APK,
14166                            "New package fails restrict-update check: " + pkgName);
14167                    return;
14168                }
14169                // retain upgrade restriction
14170                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14171            }
14172
14173            // Check for shared user id changes
14174            String invalidPackageName =
14175                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14176            if (invalidPackageName != null) {
14177                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14178                        "Package " + invalidPackageName + " tried to change user "
14179                                + oldPackage.mSharedUserId);
14180                return;
14181            }
14182
14183            // In case of rollback, remember per-user/profile install state
14184            allUsers = sUserManager.getUserIds();
14185            installedUsers = ps.queryInstalledUsers(allUsers, true);
14186        }
14187
14188        // Update what is removed
14189        res.removedInfo = new PackageRemovedInfo();
14190        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14191        res.removedInfo.removedPackage = oldPackage.packageName;
14192        res.removedInfo.isUpdate = true;
14193        res.removedInfo.origUsers = installedUsers;
14194        final int childCount = (oldPackage.childPackages != null)
14195                ? oldPackage.childPackages.size() : 0;
14196        for (int i = 0; i < childCount; i++) {
14197            boolean childPackageUpdated = false;
14198            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14199            if (res.addedChildPackages != null) {
14200                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14201                if (childRes != null) {
14202                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14203                    childRes.removedInfo.removedPackage = childPkg.packageName;
14204                    childRes.removedInfo.isUpdate = true;
14205                    childPackageUpdated = true;
14206                }
14207            }
14208            if (!childPackageUpdated) {
14209                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14210                childRemovedRes.removedPackage = childPkg.packageName;
14211                childRemovedRes.isUpdate = false;
14212                childRemovedRes.dataRemoved = true;
14213                synchronized (mPackages) {
14214                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14215                    if (childPs != null) {
14216                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14217                    }
14218                }
14219                if (res.removedInfo.removedChildPackages == null) {
14220                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14221                }
14222                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14223            }
14224        }
14225
14226        boolean sysPkg = (isSystemApp(oldPackage));
14227        if (sysPkg) {
14228            // Set the system/privileged flags as needed
14229            final boolean privileged =
14230                    (oldPackage.applicationInfo.privateFlags
14231                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14232            final int systemPolicyFlags = policyFlags
14233                    | PackageParser.PARSE_IS_SYSTEM
14234                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14235
14236            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14237                    user, allUsers, installerPackageName, res);
14238        } else {
14239            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14240                    user, allUsers, installerPackageName, res);
14241        }
14242    }
14243
14244    public List<String> getPreviousCodePaths(String packageName) {
14245        final PackageSetting ps = mSettings.mPackages.get(packageName);
14246        final List<String> result = new ArrayList<String>();
14247        if (ps != null && ps.oldCodePaths != null) {
14248            result.addAll(ps.oldCodePaths);
14249        }
14250        return result;
14251    }
14252
14253    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14254            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14255            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14256        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14257                + deletedPackage);
14258
14259        String pkgName = deletedPackage.packageName;
14260        boolean deletedPkg = true;
14261        boolean addedPkg = false;
14262        boolean updatedSettings = false;
14263        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14264        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14265                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14266
14267        final long origUpdateTime = (pkg.mExtras != null)
14268                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14269
14270        // First delete the existing package while retaining the data directory
14271        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14272                res.removedInfo, true, pkg)) {
14273            // If the existing package wasn't successfully deleted
14274            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14275            deletedPkg = false;
14276        } else {
14277            // Successfully deleted the old package; proceed with replace.
14278
14279            // If deleted package lived in a container, give users a chance to
14280            // relinquish resources before killing.
14281            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14282                if (DEBUG_INSTALL) {
14283                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14284                }
14285                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14286                final ArrayList<String> pkgList = new ArrayList<String>(1);
14287                pkgList.add(deletedPackage.applicationInfo.packageName);
14288                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14289            }
14290
14291            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14292                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14293            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14294
14295            try {
14296                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14297                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14298                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14299
14300                // Update the in-memory copy of the previous code paths.
14301                PackageSetting ps = mSettings.mPackages.get(pkgName);
14302                if (!killApp) {
14303                    if (ps.oldCodePaths == null) {
14304                        ps.oldCodePaths = new ArraySet<>();
14305                    }
14306                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14307                    if (deletedPackage.splitCodePaths != null) {
14308                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14309                    }
14310                } else {
14311                    ps.oldCodePaths = null;
14312                }
14313                if (ps.childPackageNames != null) {
14314                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14315                        final String childPkgName = ps.childPackageNames.get(i);
14316                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14317                        childPs.oldCodePaths = ps.oldCodePaths;
14318                    }
14319                }
14320                prepareAppDataAfterInstallLIF(newPackage);
14321                addedPkg = true;
14322            } catch (PackageManagerException e) {
14323                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14324            }
14325        }
14326
14327        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14328            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14329
14330            // Revert all internal state mutations and added folders for the failed install
14331            if (addedPkg) {
14332                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14333                        res.removedInfo, true, null);
14334            }
14335
14336            // Restore the old package
14337            if (deletedPkg) {
14338                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14339                File restoreFile = new File(deletedPackage.codePath);
14340                // Parse old package
14341                boolean oldExternal = isExternal(deletedPackage);
14342                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14343                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14344                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14345                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14346                try {
14347                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14348                            null);
14349                } catch (PackageManagerException e) {
14350                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14351                            + e.getMessage());
14352                    return;
14353                }
14354
14355                synchronized (mPackages) {
14356                    // Ensure the installer package name up to date
14357                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14358
14359                    // Update permissions for restored package
14360                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14361
14362                    mSettings.writeLPr();
14363                }
14364
14365                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14366            }
14367        } else {
14368            synchronized (mPackages) {
14369                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14370                if (ps != null) {
14371                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14372                    if (res.removedInfo.removedChildPackages != null) {
14373                        final int childCount = res.removedInfo.removedChildPackages.size();
14374                        // Iterate in reverse as we may modify the collection
14375                        for (int i = childCount - 1; i >= 0; i--) {
14376                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14377                            if (res.addedChildPackages.containsKey(childPackageName)) {
14378                                res.removedInfo.removedChildPackages.removeAt(i);
14379                            } else {
14380                                PackageRemovedInfo childInfo = res.removedInfo
14381                                        .removedChildPackages.valueAt(i);
14382                                childInfo.removedForAllUsers = mPackages.get(
14383                                        childInfo.removedPackage) == null;
14384                            }
14385                        }
14386                    }
14387                }
14388            }
14389        }
14390    }
14391
14392    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14393            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14394            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14395        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14396                + ", old=" + deletedPackage);
14397
14398        final boolean disabledSystem;
14399
14400        // Remove existing system package
14401        removePackageLI(deletedPackage, true);
14402
14403        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14404        if (!disabledSystem) {
14405            // We didn't need to disable the .apk as a current system package,
14406            // which means we are replacing another update that is already
14407            // installed.  We need to make sure to delete the older one's .apk.
14408            res.removedInfo.args = createInstallArgsForExisting(0,
14409                    deletedPackage.applicationInfo.getCodePath(),
14410                    deletedPackage.applicationInfo.getResourcePath(),
14411                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14412        } else {
14413            res.removedInfo.args = null;
14414        }
14415
14416        // Successfully disabled the old package. Now proceed with re-installation
14417        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14418                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14419        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14420
14421        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14422        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14423                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14424
14425        PackageParser.Package newPackage = null;
14426        try {
14427            // Add the package to the internal data structures
14428            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14429
14430            // Set the update and install times
14431            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14432            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14433                    System.currentTimeMillis());
14434
14435            // Update the package dynamic state if succeeded
14436            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14437                // Now that the install succeeded make sure we remove data
14438                // directories for any child package the update removed.
14439                final int deletedChildCount = (deletedPackage.childPackages != null)
14440                        ? deletedPackage.childPackages.size() : 0;
14441                final int newChildCount = (newPackage.childPackages != null)
14442                        ? newPackage.childPackages.size() : 0;
14443                for (int i = 0; i < deletedChildCount; i++) {
14444                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14445                    boolean childPackageDeleted = true;
14446                    for (int j = 0; j < newChildCount; j++) {
14447                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14448                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14449                            childPackageDeleted = false;
14450                            break;
14451                        }
14452                    }
14453                    if (childPackageDeleted) {
14454                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14455                                deletedChildPkg.packageName);
14456                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14457                            PackageRemovedInfo removedChildRes = res.removedInfo
14458                                    .removedChildPackages.get(deletedChildPkg.packageName);
14459                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14460                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14461                        }
14462                    }
14463                }
14464
14465                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14466                prepareAppDataAfterInstallLIF(newPackage);
14467            }
14468        } catch (PackageManagerException e) {
14469            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14470            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14471        }
14472
14473        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14474            // Re installation failed. Restore old information
14475            // Remove new pkg information
14476            if (newPackage != null) {
14477                removeInstalledPackageLI(newPackage, true);
14478            }
14479            // Add back the old system package
14480            try {
14481                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14482            } catch (PackageManagerException e) {
14483                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14484            }
14485
14486            synchronized (mPackages) {
14487                if (disabledSystem) {
14488                    enableSystemPackageLPw(deletedPackage);
14489                }
14490
14491                // Ensure the installer package name up to date
14492                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14493
14494                // Update permissions for restored package
14495                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14496
14497                mSettings.writeLPr();
14498            }
14499
14500            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14501                    + " after failed upgrade");
14502        }
14503    }
14504
14505    /**
14506     * Checks whether the parent or any of the child packages have a change shared
14507     * user. For a package to be a valid update the shred users of the parent and
14508     * the children should match. We may later support changing child shared users.
14509     * @param oldPkg The updated package.
14510     * @param newPkg The update package.
14511     * @return The shared user that change between the versions.
14512     */
14513    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14514            PackageParser.Package newPkg) {
14515        // Check parent shared user
14516        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14517            return newPkg.packageName;
14518        }
14519        // Check child shared users
14520        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14521        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14522        for (int i = 0; i < newChildCount; i++) {
14523            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14524            // If this child was present, did it have the same shared user?
14525            for (int j = 0; j < oldChildCount; j++) {
14526                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14527                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14528                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14529                    return newChildPkg.packageName;
14530                }
14531            }
14532        }
14533        return null;
14534    }
14535
14536    private void removeNativeBinariesLI(PackageSetting ps) {
14537        // Remove the lib path for the parent package
14538        if (ps != null) {
14539            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14540            // Remove the lib path for the child packages
14541            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14542            for (int i = 0; i < childCount; i++) {
14543                PackageSetting childPs = null;
14544                synchronized (mPackages) {
14545                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14546                }
14547                if (childPs != null) {
14548                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14549                            .legacyNativeLibraryPathString);
14550                }
14551            }
14552        }
14553    }
14554
14555    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14556        // Enable the parent package
14557        mSettings.enableSystemPackageLPw(pkg.packageName);
14558        // Enable the child packages
14559        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14560        for (int i = 0; i < childCount; i++) {
14561            PackageParser.Package childPkg = pkg.childPackages.get(i);
14562            mSettings.enableSystemPackageLPw(childPkg.packageName);
14563        }
14564    }
14565
14566    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14567            PackageParser.Package newPkg) {
14568        // Disable the parent package (parent always replaced)
14569        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14570        // Disable the child packages
14571        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14572        for (int i = 0; i < childCount; i++) {
14573            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14574            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14575            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14576        }
14577        return disabled;
14578    }
14579
14580    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14581            String installerPackageName) {
14582        // Enable the parent package
14583        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14584        // Enable the child packages
14585        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14586        for (int i = 0; i < childCount; i++) {
14587            PackageParser.Package childPkg = pkg.childPackages.get(i);
14588            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14589        }
14590    }
14591
14592    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14593        // Collect all used permissions in the UID
14594        ArraySet<String> usedPermissions = new ArraySet<>();
14595        final int packageCount = su.packages.size();
14596        for (int i = 0; i < packageCount; i++) {
14597            PackageSetting ps = su.packages.valueAt(i);
14598            if (ps.pkg == null) {
14599                continue;
14600            }
14601            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14602            for (int j = 0; j < requestedPermCount; j++) {
14603                String permission = ps.pkg.requestedPermissions.get(j);
14604                BasePermission bp = mSettings.mPermissions.get(permission);
14605                if (bp != null) {
14606                    usedPermissions.add(permission);
14607                }
14608            }
14609        }
14610
14611        PermissionsState permissionsState = su.getPermissionsState();
14612        // Prune install permissions
14613        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14614        final int installPermCount = installPermStates.size();
14615        for (int i = installPermCount - 1; i >= 0;  i--) {
14616            PermissionState permissionState = installPermStates.get(i);
14617            if (!usedPermissions.contains(permissionState.getName())) {
14618                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14619                if (bp != null) {
14620                    permissionsState.revokeInstallPermission(bp);
14621                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14622                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14623                }
14624            }
14625        }
14626
14627        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14628
14629        // Prune runtime permissions
14630        for (int userId : allUserIds) {
14631            List<PermissionState> runtimePermStates = permissionsState
14632                    .getRuntimePermissionStates(userId);
14633            final int runtimePermCount = runtimePermStates.size();
14634            for (int i = runtimePermCount - 1; i >= 0; i--) {
14635                PermissionState permissionState = runtimePermStates.get(i);
14636                if (!usedPermissions.contains(permissionState.getName())) {
14637                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14638                    if (bp != null) {
14639                        permissionsState.revokeRuntimePermission(bp, userId);
14640                        permissionsState.updatePermissionFlags(bp, userId,
14641                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14642                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14643                                runtimePermissionChangedUserIds, userId);
14644                    }
14645                }
14646            }
14647        }
14648
14649        return runtimePermissionChangedUserIds;
14650    }
14651
14652    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14653            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14654        // Update the parent package setting
14655        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14656                res, user);
14657        // Update the child packages setting
14658        final int childCount = (newPackage.childPackages != null)
14659                ? newPackage.childPackages.size() : 0;
14660        for (int i = 0; i < childCount; i++) {
14661            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14662            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14663            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14664                    childRes.origUsers, childRes, user);
14665        }
14666    }
14667
14668    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14669            String installerPackageName, int[] allUsers, int[] installedForUsers,
14670            PackageInstalledInfo res, UserHandle user) {
14671        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14672
14673        String pkgName = newPackage.packageName;
14674        synchronized (mPackages) {
14675            //write settings. the installStatus will be incomplete at this stage.
14676            //note that the new package setting would have already been
14677            //added to mPackages. It hasn't been persisted yet.
14678            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14679            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14680            mSettings.writeLPr();
14681            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14682        }
14683
14684        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14685        synchronized (mPackages) {
14686            updatePermissionsLPw(newPackage.packageName, newPackage,
14687                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14688                            ? UPDATE_PERMISSIONS_ALL : 0));
14689            // For system-bundled packages, we assume that installing an upgraded version
14690            // of the package implies that the user actually wants to run that new code,
14691            // so we enable the package.
14692            PackageSetting ps = mSettings.mPackages.get(pkgName);
14693            final int userId = user.getIdentifier();
14694            if (ps != null) {
14695                if (isSystemApp(newPackage)) {
14696                    if (DEBUG_INSTALL) {
14697                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14698                    }
14699                    // Enable system package for requested users
14700                    if (res.origUsers != null) {
14701                        for (int origUserId : res.origUsers) {
14702                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14703                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14704                                        origUserId, installerPackageName);
14705                            }
14706                        }
14707                    }
14708                    // Also convey the prior install/uninstall state
14709                    if (allUsers != null && installedForUsers != null) {
14710                        for (int currentUserId : allUsers) {
14711                            final boolean installed = ArrayUtils.contains(
14712                                    installedForUsers, currentUserId);
14713                            if (DEBUG_INSTALL) {
14714                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14715                            }
14716                            ps.setInstalled(installed, currentUserId);
14717                        }
14718                        // these install state changes will be persisted in the
14719                        // upcoming call to mSettings.writeLPr().
14720                    }
14721                }
14722                // It's implied that when a user requests installation, they want the app to be
14723                // installed and enabled.
14724                if (userId != UserHandle.USER_ALL) {
14725                    ps.setInstalled(true, userId);
14726                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14727                }
14728            }
14729            res.name = pkgName;
14730            res.uid = newPackage.applicationInfo.uid;
14731            res.pkg = newPackage;
14732            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14733            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14734            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14735            //to update install status
14736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14737            mSettings.writeLPr();
14738            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14739        }
14740
14741        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14742    }
14743
14744    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14745        try {
14746            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14747            installPackageLI(args, res);
14748        } finally {
14749            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14750        }
14751    }
14752
14753    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14754        final int installFlags = args.installFlags;
14755        final String installerPackageName = args.installerPackageName;
14756        final String volumeUuid = args.volumeUuid;
14757        final File tmpPackageFile = new File(args.getCodePath());
14758        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14759        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14760                || (args.volumeUuid != null));
14761        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14762        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14763        boolean replace = false;
14764        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14765        if (args.move != null) {
14766            // moving a complete application; perform an initial scan on the new install location
14767            scanFlags |= SCAN_INITIAL;
14768        }
14769        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14770            scanFlags |= SCAN_DONT_KILL_APP;
14771        }
14772
14773        // Result object to be returned
14774        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14775
14776        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14777
14778        // Sanity check
14779        if (ephemeral && (forwardLocked || onExternal)) {
14780            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14781                    + " external=" + onExternal);
14782            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14783            return;
14784        }
14785
14786        // Retrieve PackageSettings and parse package
14787        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14788                | PackageParser.PARSE_ENFORCE_CODE
14789                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14790                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14791                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14792                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14793        PackageParser pp = new PackageParser();
14794        pp.setSeparateProcesses(mSeparateProcesses);
14795        pp.setDisplayMetrics(mMetrics);
14796
14797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14798        final PackageParser.Package pkg;
14799        try {
14800            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14801        } catch (PackageParserException e) {
14802            res.setError("Failed parse during installPackageLI", e);
14803            return;
14804        } finally {
14805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14806        }
14807
14808        // If we are installing a clustered package add results for the children
14809        if (pkg.childPackages != null) {
14810            synchronized (mPackages) {
14811                final int childCount = pkg.childPackages.size();
14812                for (int i = 0; i < childCount; i++) {
14813                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14814                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14815                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14816                    childRes.pkg = childPkg;
14817                    childRes.name = childPkg.packageName;
14818                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14819                    if (childPs != null) {
14820                        childRes.origUsers = childPs.queryInstalledUsers(
14821                                sUserManager.getUserIds(), true);
14822                    }
14823                    if ((mPackages.containsKey(childPkg.packageName))) {
14824                        childRes.removedInfo = new PackageRemovedInfo();
14825                        childRes.removedInfo.removedPackage = childPkg.packageName;
14826                    }
14827                    if (res.addedChildPackages == null) {
14828                        res.addedChildPackages = new ArrayMap<>();
14829                    }
14830                    res.addedChildPackages.put(childPkg.packageName, childRes);
14831                }
14832            }
14833        }
14834
14835        // If package doesn't declare API override, mark that we have an install
14836        // time CPU ABI override.
14837        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14838            pkg.cpuAbiOverride = args.abiOverride;
14839        }
14840
14841        String pkgName = res.name = pkg.packageName;
14842        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14843            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14844                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14845                return;
14846            }
14847        }
14848
14849        try {
14850            // either use what we've been given or parse directly from the APK
14851            if (args.certificates != null) {
14852                try {
14853                    PackageParser.populateCertificates(pkg, args.certificates);
14854                } catch (PackageParserException e) {
14855                    // there was something wrong with the certificates we were given;
14856                    // try to pull them from the APK
14857                    PackageParser.collectCertificates(pkg, parseFlags);
14858                }
14859            } else {
14860                PackageParser.collectCertificates(pkg, parseFlags);
14861            }
14862        } catch (PackageParserException e) {
14863            res.setError("Failed collect during installPackageLI", e);
14864            return;
14865        }
14866
14867        // Get rid of all references to package scan path via parser.
14868        pp = null;
14869        String oldCodePath = null;
14870        boolean systemApp = false;
14871        synchronized (mPackages) {
14872            // Check if installing already existing package
14873            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14874                String oldName = mSettings.mRenamedPackages.get(pkgName);
14875                if (pkg.mOriginalPackages != null
14876                        && pkg.mOriginalPackages.contains(oldName)
14877                        && mPackages.containsKey(oldName)) {
14878                    // This package is derived from an original package,
14879                    // and this device has been updating from that original
14880                    // name.  We must continue using the original name, so
14881                    // rename the new package here.
14882                    pkg.setPackageName(oldName);
14883                    pkgName = pkg.packageName;
14884                    replace = true;
14885                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14886                            + oldName + " pkgName=" + pkgName);
14887                } else if (mPackages.containsKey(pkgName)) {
14888                    // This package, under its official name, already exists
14889                    // on the device; we should replace it.
14890                    replace = true;
14891                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14892                }
14893
14894                // Child packages are installed through the parent package
14895                if (pkg.parentPackage != null) {
14896                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14897                            "Package " + pkg.packageName + " is child of package "
14898                                    + pkg.parentPackage.parentPackage + ". Child packages "
14899                                    + "can be updated only through the parent package.");
14900                    return;
14901                }
14902
14903                if (replace) {
14904                    // Prevent apps opting out from runtime permissions
14905                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14906                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14907                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14908                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14909                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14910                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14911                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14912                                        + " doesn't support runtime permissions but the old"
14913                                        + " target SDK " + oldTargetSdk + " does.");
14914                        return;
14915                    }
14916
14917                    // Prevent installing of child packages
14918                    if (oldPackage.parentPackage != null) {
14919                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14920                                "Package " + pkg.packageName + " is child of package "
14921                                        + oldPackage.parentPackage + ". Child packages "
14922                                        + "can be updated only through the parent package.");
14923                        return;
14924                    }
14925                }
14926            }
14927
14928            PackageSetting ps = mSettings.mPackages.get(pkgName);
14929            if (ps != null) {
14930                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14931
14932                // Quick sanity check that we're signed correctly if updating;
14933                // we'll check this again later when scanning, but we want to
14934                // bail early here before tripping over redefined permissions.
14935                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14936                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14937                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14938                                + pkg.packageName + " upgrade keys do not match the "
14939                                + "previously installed version");
14940                        return;
14941                    }
14942                } else {
14943                    try {
14944                        verifySignaturesLP(ps, pkg);
14945                    } catch (PackageManagerException e) {
14946                        res.setError(e.error, e.getMessage());
14947                        return;
14948                    }
14949                }
14950
14951                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14952                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14953                    systemApp = (ps.pkg.applicationInfo.flags &
14954                            ApplicationInfo.FLAG_SYSTEM) != 0;
14955                }
14956                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14957            }
14958
14959            // Check whether the newly-scanned package wants to define an already-defined perm
14960            int N = pkg.permissions.size();
14961            for (int i = N-1; i >= 0; i--) {
14962                PackageParser.Permission perm = pkg.permissions.get(i);
14963                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14964                if (bp != null) {
14965                    // If the defining package is signed with our cert, it's okay.  This
14966                    // also includes the "updating the same package" case, of course.
14967                    // "updating same package" could also involve key-rotation.
14968                    final boolean sigsOk;
14969                    if (bp.sourcePackage.equals(pkg.packageName)
14970                            && (bp.packageSetting instanceof PackageSetting)
14971                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14972                                    scanFlags))) {
14973                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14974                    } else {
14975                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14976                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14977                    }
14978                    if (!sigsOk) {
14979                        // If the owning package is the system itself, we log but allow
14980                        // install to proceed; we fail the install on all other permission
14981                        // redefinitions.
14982                        if (!bp.sourcePackage.equals("android")) {
14983                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14984                                    + pkg.packageName + " attempting to redeclare permission "
14985                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14986                            res.origPermission = perm.info.name;
14987                            res.origPackage = bp.sourcePackage;
14988                            return;
14989                        } else {
14990                            Slog.w(TAG, "Package " + pkg.packageName
14991                                    + " attempting to redeclare system permission "
14992                                    + perm.info.name + "; ignoring new declaration");
14993                            pkg.permissions.remove(i);
14994                        }
14995                    }
14996                }
14997            }
14998        }
14999
15000        if (systemApp) {
15001            if (onExternal) {
15002                // Abort update; system app can't be replaced with app on sdcard
15003                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15004                        "Cannot install updates to system apps on sdcard");
15005                return;
15006            } else if (ephemeral) {
15007                // Abort update; system app can't be replaced with an ephemeral app
15008                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15009                        "Cannot update a system app with an ephemeral app");
15010                return;
15011            }
15012        }
15013
15014        if (args.move != null) {
15015            // We did an in-place move, so dex is ready to roll
15016            scanFlags |= SCAN_NO_DEX;
15017            scanFlags |= SCAN_MOVE;
15018
15019            synchronized (mPackages) {
15020                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15021                if (ps == null) {
15022                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15023                            "Missing settings for moved package " + pkgName);
15024                }
15025
15026                // We moved the entire application as-is, so bring over the
15027                // previously derived ABI information.
15028                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15029                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15030            }
15031
15032        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15033            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15034            scanFlags |= SCAN_NO_DEX;
15035
15036            try {
15037                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15038                    args.abiOverride : pkg.cpuAbiOverride);
15039                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15040                        true /* extract libs */);
15041            } catch (PackageManagerException pme) {
15042                Slog.e(TAG, "Error deriving application ABI", pme);
15043                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15044                return;
15045            }
15046
15047            // Shared libraries for the package need to be updated.
15048            synchronized (mPackages) {
15049                try {
15050                    updateSharedLibrariesLPw(pkg, null);
15051                } catch (PackageManagerException e) {
15052                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15053                }
15054            }
15055            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15056            // Do not run PackageDexOptimizer through the local performDexOpt
15057            // method because `pkg` is not in `mPackages` yet.
15058            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15059                    null /* instructionSets */, false /* checkProfiles */,
15060                    getCompilerFilterForReason(REASON_INSTALL));
15061            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15062            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
15063                String msg = "Extracting package failed for " + pkgName;
15064                res.setError(INSTALL_FAILED_DEXOPT, msg);
15065                return;
15066            }
15067
15068            // Notify BackgroundDexOptService that the package has been changed.
15069            // If this is an update of a package which used to fail to compile,
15070            // BDOS will remove it from its blacklist.
15071            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15072        }
15073
15074        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15075            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15076            return;
15077        }
15078
15079        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15080
15081        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15082                "installPackageLI")) {
15083            if (replace) {
15084                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15085                        installerPackageName, res);
15086            } else {
15087                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15088                        args.user, installerPackageName, volumeUuid, res);
15089            }
15090        }
15091        synchronized (mPackages) {
15092            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15093            if (ps != null) {
15094                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15095            }
15096
15097            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15098            for (int i = 0; i < childCount; i++) {
15099                PackageParser.Package childPkg = pkg.childPackages.get(i);
15100                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15101                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15102                if (childPs != null) {
15103                    childRes.newUsers = childPs.queryInstalledUsers(
15104                            sUserManager.getUserIds(), true);
15105                }
15106            }
15107        }
15108    }
15109
15110    private void startIntentFilterVerifications(int userId, boolean replacing,
15111            PackageParser.Package pkg) {
15112        if (mIntentFilterVerifierComponent == null) {
15113            Slog.w(TAG, "No IntentFilter verification will not be done as "
15114                    + "there is no IntentFilterVerifier available!");
15115            return;
15116        }
15117
15118        final int verifierUid = getPackageUid(
15119                mIntentFilterVerifierComponent.getPackageName(),
15120                MATCH_DEBUG_TRIAGED_MISSING,
15121                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15122
15123        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15124        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15125        mHandler.sendMessage(msg);
15126
15127        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15128        for (int i = 0; i < childCount; i++) {
15129            PackageParser.Package childPkg = pkg.childPackages.get(i);
15130            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15131            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15132            mHandler.sendMessage(msg);
15133        }
15134    }
15135
15136    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15137            PackageParser.Package pkg) {
15138        int size = pkg.activities.size();
15139        if (size == 0) {
15140            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15141                    "No activity, so no need to verify any IntentFilter!");
15142            return;
15143        }
15144
15145        final boolean hasDomainURLs = hasDomainURLs(pkg);
15146        if (!hasDomainURLs) {
15147            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15148                    "No domain URLs, so no need to verify any IntentFilter!");
15149            return;
15150        }
15151
15152        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15153                + " if any IntentFilter from the " + size
15154                + " Activities needs verification ...");
15155
15156        int count = 0;
15157        final String packageName = pkg.packageName;
15158
15159        synchronized (mPackages) {
15160            // If this is a new install and we see that we've already run verification for this
15161            // package, we have nothing to do: it means the state was restored from backup.
15162            if (!replacing) {
15163                IntentFilterVerificationInfo ivi =
15164                        mSettings.getIntentFilterVerificationLPr(packageName);
15165                if (ivi != null) {
15166                    if (DEBUG_DOMAIN_VERIFICATION) {
15167                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15168                                + ivi.getStatusString());
15169                    }
15170                    return;
15171                }
15172            }
15173
15174            // If any filters need to be verified, then all need to be.
15175            boolean needToVerify = false;
15176            for (PackageParser.Activity a : pkg.activities) {
15177                for (ActivityIntentInfo filter : a.intents) {
15178                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15179                        if (DEBUG_DOMAIN_VERIFICATION) {
15180                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15181                        }
15182                        needToVerify = true;
15183                        break;
15184                    }
15185                }
15186            }
15187
15188            if (needToVerify) {
15189                final int verificationId = mIntentFilterVerificationToken++;
15190                for (PackageParser.Activity a : pkg.activities) {
15191                    for (ActivityIntentInfo filter : a.intents) {
15192                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15193                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15194                                    "Verification needed for IntentFilter:" + filter.toString());
15195                            mIntentFilterVerifier.addOneIntentFilterVerification(
15196                                    verifierUid, userId, verificationId, filter, packageName);
15197                            count++;
15198                        }
15199                    }
15200                }
15201            }
15202        }
15203
15204        if (count > 0) {
15205            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15206                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15207                    +  " for userId:" + userId);
15208            mIntentFilterVerifier.startVerifications(userId);
15209        } else {
15210            if (DEBUG_DOMAIN_VERIFICATION) {
15211                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15212            }
15213        }
15214    }
15215
15216    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15217        final ComponentName cn  = filter.activity.getComponentName();
15218        final String packageName = cn.getPackageName();
15219
15220        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15221                packageName);
15222        if (ivi == null) {
15223            return true;
15224        }
15225        int status = ivi.getStatus();
15226        switch (status) {
15227            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15228            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15229                return true;
15230
15231            default:
15232                // Nothing to do
15233                return false;
15234        }
15235    }
15236
15237    private static boolean isMultiArch(ApplicationInfo info) {
15238        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15239    }
15240
15241    private static boolean isExternal(PackageParser.Package pkg) {
15242        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15243    }
15244
15245    private static boolean isExternal(PackageSetting ps) {
15246        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15247    }
15248
15249    private static boolean isEphemeral(PackageParser.Package pkg) {
15250        return pkg.applicationInfo.isEphemeralApp();
15251    }
15252
15253    private static boolean isEphemeral(PackageSetting ps) {
15254        return ps.pkg != null && isEphemeral(ps.pkg);
15255    }
15256
15257    private static boolean isSystemApp(PackageParser.Package pkg) {
15258        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15259    }
15260
15261    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15262        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15263    }
15264
15265    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15266        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15267    }
15268
15269    private static boolean isSystemApp(PackageSetting ps) {
15270        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15271    }
15272
15273    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15274        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15275    }
15276
15277    private int packageFlagsToInstallFlags(PackageSetting ps) {
15278        int installFlags = 0;
15279        if (isEphemeral(ps)) {
15280            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15281        }
15282        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15283            // This existing package was an external ASEC install when we have
15284            // the external flag without a UUID
15285            installFlags |= PackageManager.INSTALL_EXTERNAL;
15286        }
15287        if (ps.isForwardLocked()) {
15288            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15289        }
15290        return installFlags;
15291    }
15292
15293    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15294        if (isExternal(pkg)) {
15295            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15296                return StorageManager.UUID_PRIMARY_PHYSICAL;
15297            } else {
15298                return pkg.volumeUuid;
15299            }
15300        } else {
15301            return StorageManager.UUID_PRIVATE_INTERNAL;
15302        }
15303    }
15304
15305    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15306        if (isExternal(pkg)) {
15307            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15308                return mSettings.getExternalVersion();
15309            } else {
15310                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15311            }
15312        } else {
15313            return mSettings.getInternalVersion();
15314        }
15315    }
15316
15317    private void deleteTempPackageFiles() {
15318        final FilenameFilter filter = new FilenameFilter() {
15319            public boolean accept(File dir, String name) {
15320                return name.startsWith("vmdl") && name.endsWith(".tmp");
15321            }
15322        };
15323        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15324            file.delete();
15325        }
15326    }
15327
15328    @Override
15329    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15330            int flags) {
15331        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15332                flags);
15333    }
15334
15335    @Override
15336    public void deletePackage(final String packageName,
15337            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15338        mContext.enforceCallingOrSelfPermission(
15339                android.Manifest.permission.DELETE_PACKAGES, null);
15340        Preconditions.checkNotNull(packageName);
15341        Preconditions.checkNotNull(observer);
15342        final int uid = Binder.getCallingUid();
15343        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15344        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15345        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15346            mContext.enforceCallingOrSelfPermission(
15347                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15348                    "deletePackage for user " + userId);
15349        }
15350
15351        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15352            try {
15353                observer.onPackageDeleted(packageName,
15354                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15355            } catch (RemoteException re) {
15356            }
15357            return;
15358        }
15359
15360        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15361            try {
15362                observer.onPackageDeleted(packageName,
15363                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15364            } catch (RemoteException re) {
15365            }
15366            return;
15367        }
15368
15369        if (DEBUG_REMOVE) {
15370            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15371                    + " deleteAllUsers: " + deleteAllUsers );
15372        }
15373        // Queue up an async operation since the package deletion may take a little while.
15374        mHandler.post(new Runnable() {
15375            public void run() {
15376                mHandler.removeCallbacks(this);
15377                int returnCode;
15378                if (!deleteAllUsers) {
15379                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15380                } else {
15381                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15382                    // If nobody is blocking uninstall, proceed with delete for all users
15383                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15384                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15385                    } else {
15386                        // Otherwise uninstall individually for users with blockUninstalls=false
15387                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15388                        for (int userId : users) {
15389                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15390                                returnCode = deletePackageX(packageName, userId, userFlags);
15391                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15392                                    Slog.w(TAG, "Package delete failed for user " + userId
15393                                            + ", returnCode " + returnCode);
15394                                }
15395                            }
15396                        }
15397                        // The app has only been marked uninstalled for certain users.
15398                        // We still need to report that delete was blocked
15399                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15400                    }
15401                }
15402                try {
15403                    observer.onPackageDeleted(packageName, returnCode, null);
15404                } catch (RemoteException e) {
15405                    Log.i(TAG, "Observer no longer exists.");
15406                } //end catch
15407            } //end run
15408        });
15409    }
15410
15411    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15412        int[] result = EMPTY_INT_ARRAY;
15413        for (int userId : userIds) {
15414            if (getBlockUninstallForUser(packageName, userId)) {
15415                result = ArrayUtils.appendInt(result, userId);
15416            }
15417        }
15418        return result;
15419    }
15420
15421    @Override
15422    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15423        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15424    }
15425
15426    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15427        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15428                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15429        try {
15430            if (dpm != null) {
15431                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15432                        /* callingUserOnly =*/ false);
15433                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15434                        : deviceOwnerComponentName.getPackageName();
15435                // Does the package contains the device owner?
15436                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15437                // this check is probably not needed, since DO should be registered as a device
15438                // admin on some user too. (Original bug for this: b/17657954)
15439                if (packageName.equals(deviceOwnerPackageName)) {
15440                    return true;
15441                }
15442                // Does it contain a device admin for any user?
15443                int[] users;
15444                if (userId == UserHandle.USER_ALL) {
15445                    users = sUserManager.getUserIds();
15446                } else {
15447                    users = new int[]{userId};
15448                }
15449                for (int i = 0; i < users.length; ++i) {
15450                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15451                        return true;
15452                    }
15453                }
15454            }
15455        } catch (RemoteException e) {
15456        }
15457        return false;
15458    }
15459
15460    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15461        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15462    }
15463
15464    /**
15465     *  This method is an internal method that could be get invoked either
15466     *  to delete an installed package or to clean up a failed installation.
15467     *  After deleting an installed package, a broadcast is sent to notify any
15468     *  listeners that the package has been removed. For cleaning up a failed
15469     *  installation, the broadcast is not necessary since the package's
15470     *  installation wouldn't have sent the initial broadcast either
15471     *  The key steps in deleting a package are
15472     *  deleting the package information in internal structures like mPackages,
15473     *  deleting the packages base directories through installd
15474     *  updating mSettings to reflect current status
15475     *  persisting settings for later use
15476     *  sending a broadcast if necessary
15477     */
15478    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15479        final PackageRemovedInfo info = new PackageRemovedInfo();
15480        final boolean res;
15481
15482        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15483                ? UserHandle.ALL : new UserHandle(userId);
15484
15485        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15486            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15487            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15488        }
15489
15490        PackageSetting uninstalledPs = null;
15491
15492        // for the uninstall-updates case and restricted profiles, remember the per-
15493        // user handle installed state
15494        int[] allUsers;
15495        synchronized (mPackages) {
15496            uninstalledPs = mSettings.mPackages.get(packageName);
15497            if (uninstalledPs == null) {
15498                Slog.w(TAG, "Not removing non-existent package " + packageName);
15499                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15500            }
15501            allUsers = sUserManager.getUserIds();
15502            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15503        }
15504
15505        synchronized (mInstallLock) {
15506            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15507            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15508                    "deletePackageX")) {
15509                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15510                        deleteFlags | REMOVE_CHATTY, info, true, null);
15511            }
15512            synchronized (mPackages) {
15513                if (res) {
15514                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15515                }
15516            }
15517        }
15518
15519        if (res) {
15520            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15521            info.sendPackageRemovedBroadcasts(killApp);
15522            info.sendSystemPackageUpdatedBroadcasts();
15523            info.sendSystemPackageAppearedBroadcasts();
15524        }
15525        // Force a gc here.
15526        Runtime.getRuntime().gc();
15527        // Delete the resources here after sending the broadcast to let
15528        // other processes clean up before deleting resources.
15529        if (info.args != null) {
15530            synchronized (mInstallLock) {
15531                info.args.doPostDeleteLI(true);
15532            }
15533        }
15534
15535        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15536    }
15537
15538    class PackageRemovedInfo {
15539        String removedPackage;
15540        int uid = -1;
15541        int removedAppId = -1;
15542        int[] origUsers;
15543        int[] removedUsers = null;
15544        boolean isRemovedPackageSystemUpdate = false;
15545        boolean isUpdate;
15546        boolean dataRemoved;
15547        boolean removedForAllUsers;
15548        // Clean up resources deleted packages.
15549        InstallArgs args = null;
15550        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15551        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15552
15553        void sendPackageRemovedBroadcasts(boolean killApp) {
15554            sendPackageRemovedBroadcastInternal(killApp);
15555            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15556            for (int i = 0; i < childCount; i++) {
15557                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15558                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15559            }
15560        }
15561
15562        void sendSystemPackageUpdatedBroadcasts() {
15563            if (isRemovedPackageSystemUpdate) {
15564                sendSystemPackageUpdatedBroadcastsInternal();
15565                final int childCount = (removedChildPackages != null)
15566                        ? removedChildPackages.size() : 0;
15567                for (int i = 0; i < childCount; i++) {
15568                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15569                    if (childInfo.isRemovedPackageSystemUpdate) {
15570                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15571                    }
15572                }
15573            }
15574        }
15575
15576        void sendSystemPackageAppearedBroadcasts() {
15577            final int packageCount = (appearedChildPackages != null)
15578                    ? appearedChildPackages.size() : 0;
15579            for (int i = 0; i < packageCount; i++) {
15580                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15581                for (int userId : installedInfo.newUsers) {
15582                    sendPackageAddedForUser(installedInfo.name, true,
15583                            UserHandle.getAppId(installedInfo.uid), userId);
15584                }
15585            }
15586        }
15587
15588        private void sendSystemPackageUpdatedBroadcastsInternal() {
15589            Bundle extras = new Bundle(2);
15590            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15591            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15592            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15593                    extras, 0, null, null, null);
15594            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15595                    extras, 0, null, null, null);
15596            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15597                    null, 0, removedPackage, null, null);
15598        }
15599
15600        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15601            Bundle extras = new Bundle(2);
15602            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15603            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15604            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15605            if (isUpdate || isRemovedPackageSystemUpdate) {
15606                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15607            }
15608            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15609            if (removedPackage != null) {
15610                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15611                        extras, 0, null, null, removedUsers);
15612                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15613                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15614                            removedPackage, extras, 0, null, null, removedUsers);
15615                }
15616            }
15617            if (removedAppId >= 0) {
15618                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15619                        removedUsers);
15620            }
15621        }
15622    }
15623
15624    /*
15625     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15626     * flag is not set, the data directory is removed as well.
15627     * make sure this flag is set for partially installed apps. If not its meaningless to
15628     * delete a partially installed application.
15629     */
15630    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15631            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15632        String packageName = ps.name;
15633        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15634        // Retrieve object to delete permissions for shared user later on
15635        final PackageParser.Package deletedPkg;
15636        final PackageSetting deletedPs;
15637        // reader
15638        synchronized (mPackages) {
15639            deletedPkg = mPackages.get(packageName);
15640            deletedPs = mSettings.mPackages.get(packageName);
15641            if (outInfo != null) {
15642                outInfo.removedPackage = packageName;
15643                outInfo.removedUsers = deletedPs != null
15644                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15645                        : null;
15646            }
15647        }
15648
15649        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15650
15651        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15652            final PackageParser.Package resolvedPkg;
15653            if (deletedPkg != null) {
15654                resolvedPkg = deletedPkg;
15655            } else {
15656                // We don't have a parsed package when it lives on an ejected
15657                // adopted storage device, so fake something together
15658                resolvedPkg = new PackageParser.Package(ps.name);
15659                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15660            }
15661            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15662                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15663            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15664            if (outInfo != null) {
15665                outInfo.dataRemoved = true;
15666            }
15667            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15668        }
15669
15670        // writer
15671        synchronized (mPackages) {
15672            if (deletedPs != null) {
15673                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15674                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15675                    clearDefaultBrowserIfNeeded(packageName);
15676                    if (outInfo != null) {
15677                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15678                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15679                    }
15680                    updatePermissionsLPw(deletedPs.name, null, 0);
15681                    if (deletedPs.sharedUser != null) {
15682                        // Remove permissions associated with package. Since runtime
15683                        // permissions are per user we have to kill the removed package
15684                        // or packages running under the shared user of the removed
15685                        // package if revoking the permissions requested only by the removed
15686                        // package is successful and this causes a change in gids.
15687                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15688                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15689                                    userId);
15690                            if (userIdToKill == UserHandle.USER_ALL
15691                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15692                                // If gids changed for this user, kill all affected packages.
15693                                mHandler.post(new Runnable() {
15694                                    @Override
15695                                    public void run() {
15696                                        // This has to happen with no lock held.
15697                                        killApplication(deletedPs.name, deletedPs.appId,
15698                                                KILL_APP_REASON_GIDS_CHANGED);
15699                                    }
15700                                });
15701                                break;
15702                            }
15703                        }
15704                    }
15705                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15706                }
15707                // make sure to preserve per-user disabled state if this removal was just
15708                // a downgrade of a system app to the factory package
15709                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15710                    if (DEBUG_REMOVE) {
15711                        Slog.d(TAG, "Propagating install state across downgrade");
15712                    }
15713                    for (int userId : allUserHandles) {
15714                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15715                        if (DEBUG_REMOVE) {
15716                            Slog.d(TAG, "    user " + userId + " => " + installed);
15717                        }
15718                        ps.setInstalled(installed, userId);
15719                    }
15720                }
15721            }
15722            // can downgrade to reader
15723            if (writeSettings) {
15724                // Save settings now
15725                mSettings.writeLPr();
15726            }
15727        }
15728        if (outInfo != null) {
15729            // A user ID was deleted here. Go through all users and remove it
15730            // from KeyStore.
15731            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15732        }
15733    }
15734
15735    static boolean locationIsPrivileged(File path) {
15736        try {
15737            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15738                    .getCanonicalPath();
15739            return path.getCanonicalPath().startsWith(privilegedAppDir);
15740        } catch (IOException e) {
15741            Slog.e(TAG, "Unable to access code path " + path);
15742        }
15743        return false;
15744    }
15745
15746    /*
15747     * Tries to delete system package.
15748     */
15749    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15750            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15751            boolean writeSettings) {
15752        if (deletedPs.parentPackageName != null) {
15753            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15754            return false;
15755        }
15756
15757        final boolean applyUserRestrictions
15758                = (allUserHandles != null) && (outInfo.origUsers != null);
15759        final PackageSetting disabledPs;
15760        // Confirm if the system package has been updated
15761        // An updated system app can be deleted. This will also have to restore
15762        // the system pkg from system partition
15763        // reader
15764        synchronized (mPackages) {
15765            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15766        }
15767
15768        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15769                + " disabledPs=" + disabledPs);
15770
15771        if (disabledPs == null) {
15772            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15773            return false;
15774        } else if (DEBUG_REMOVE) {
15775            Slog.d(TAG, "Deleting system pkg from data partition");
15776        }
15777
15778        if (DEBUG_REMOVE) {
15779            if (applyUserRestrictions) {
15780                Slog.d(TAG, "Remembering install states:");
15781                for (int userId : allUserHandles) {
15782                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15783                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15784                }
15785            }
15786        }
15787
15788        // Delete the updated package
15789        outInfo.isRemovedPackageSystemUpdate = true;
15790        if (outInfo.removedChildPackages != null) {
15791            final int childCount = (deletedPs.childPackageNames != null)
15792                    ? deletedPs.childPackageNames.size() : 0;
15793            for (int i = 0; i < childCount; i++) {
15794                String childPackageName = deletedPs.childPackageNames.get(i);
15795                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15796                        .contains(childPackageName)) {
15797                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15798                            childPackageName);
15799                    if (childInfo != null) {
15800                        childInfo.isRemovedPackageSystemUpdate = true;
15801                    }
15802                }
15803            }
15804        }
15805
15806        if (disabledPs.versionCode < deletedPs.versionCode) {
15807            // Delete data for downgrades
15808            flags &= ~PackageManager.DELETE_KEEP_DATA;
15809        } else {
15810            // Preserve data by setting flag
15811            flags |= PackageManager.DELETE_KEEP_DATA;
15812        }
15813
15814        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15815                outInfo, writeSettings, disabledPs.pkg);
15816        if (!ret) {
15817            return false;
15818        }
15819
15820        // writer
15821        synchronized (mPackages) {
15822            // Reinstate the old system package
15823            enableSystemPackageLPw(disabledPs.pkg);
15824            // Remove any native libraries from the upgraded package.
15825            removeNativeBinariesLI(deletedPs);
15826        }
15827
15828        // Install the system package
15829        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15830        int parseFlags = mDefParseFlags
15831                | PackageParser.PARSE_MUST_BE_APK
15832                | PackageParser.PARSE_IS_SYSTEM
15833                | PackageParser.PARSE_IS_SYSTEM_DIR;
15834        if (locationIsPrivileged(disabledPs.codePath)) {
15835            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15836        }
15837
15838        final PackageParser.Package newPkg;
15839        try {
15840            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15841        } catch (PackageManagerException e) {
15842            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15843                    + e.getMessage());
15844            return false;
15845        }
15846
15847        prepareAppDataAfterInstallLIF(newPkg);
15848
15849        // writer
15850        synchronized (mPackages) {
15851            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15852
15853            // Propagate the permissions state as we do not want to drop on the floor
15854            // runtime permissions. The update permissions method below will take
15855            // care of removing obsolete permissions and grant install permissions.
15856            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15857            updatePermissionsLPw(newPkg.packageName, newPkg,
15858                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15859
15860            if (applyUserRestrictions) {
15861                if (DEBUG_REMOVE) {
15862                    Slog.d(TAG, "Propagating install state across reinstall");
15863                }
15864                for (int userId : allUserHandles) {
15865                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15866                    if (DEBUG_REMOVE) {
15867                        Slog.d(TAG, "    user " + userId + " => " + installed);
15868                    }
15869                    ps.setInstalled(installed, userId);
15870
15871                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15872                }
15873                // Regardless of writeSettings we need to ensure that this restriction
15874                // state propagation is persisted
15875                mSettings.writeAllUsersPackageRestrictionsLPr();
15876            }
15877            // can downgrade to reader here
15878            if (writeSettings) {
15879                mSettings.writeLPr();
15880            }
15881        }
15882        return true;
15883    }
15884
15885    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15886            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15887            PackageRemovedInfo outInfo, boolean writeSettings,
15888            PackageParser.Package replacingPackage) {
15889        synchronized (mPackages) {
15890            if (outInfo != null) {
15891                outInfo.uid = ps.appId;
15892            }
15893
15894            if (outInfo != null && outInfo.removedChildPackages != null) {
15895                final int childCount = (ps.childPackageNames != null)
15896                        ? ps.childPackageNames.size() : 0;
15897                for (int i = 0; i < childCount; i++) {
15898                    String childPackageName = ps.childPackageNames.get(i);
15899                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15900                    if (childPs == null) {
15901                        return false;
15902                    }
15903                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15904                            childPackageName);
15905                    if (childInfo != null) {
15906                        childInfo.uid = childPs.appId;
15907                    }
15908                }
15909            }
15910        }
15911
15912        // Delete package data from internal structures and also remove data if flag is set
15913        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15914
15915        // Delete the child packages data
15916        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15917        for (int i = 0; i < childCount; i++) {
15918            PackageSetting childPs;
15919            synchronized (mPackages) {
15920                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15921            }
15922            if (childPs != null) {
15923                PackageRemovedInfo childOutInfo = (outInfo != null
15924                        && outInfo.removedChildPackages != null)
15925                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15926                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15927                        && (replacingPackage != null
15928                        && !replacingPackage.hasChildPackage(childPs.name))
15929                        ? flags & ~DELETE_KEEP_DATA : flags;
15930                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15931                        deleteFlags, writeSettings);
15932            }
15933        }
15934
15935        // Delete application code and resources only for parent packages
15936        if (ps.parentPackageName == null) {
15937            if (deleteCodeAndResources && (outInfo != null)) {
15938                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15939                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15940                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15941            }
15942        }
15943
15944        return true;
15945    }
15946
15947    @Override
15948    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15949            int userId) {
15950        mContext.enforceCallingOrSelfPermission(
15951                android.Manifest.permission.DELETE_PACKAGES, null);
15952        synchronized (mPackages) {
15953            PackageSetting ps = mSettings.mPackages.get(packageName);
15954            if (ps == null) {
15955                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15956                return false;
15957            }
15958            if (!ps.getInstalled(userId)) {
15959                // Can't block uninstall for an app that is not installed or enabled.
15960                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15961                return false;
15962            }
15963            ps.setBlockUninstall(blockUninstall, userId);
15964            mSettings.writePackageRestrictionsLPr(userId);
15965        }
15966        return true;
15967    }
15968
15969    @Override
15970    public boolean getBlockUninstallForUser(String packageName, int userId) {
15971        synchronized (mPackages) {
15972            PackageSetting ps = mSettings.mPackages.get(packageName);
15973            if (ps == null) {
15974                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15975                return false;
15976            }
15977            return ps.getBlockUninstall(userId);
15978        }
15979    }
15980
15981    @Override
15982    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15983        int callingUid = Binder.getCallingUid();
15984        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15985            throw new SecurityException(
15986                    "setRequiredForSystemUser can only be run by the system or root");
15987        }
15988        synchronized (mPackages) {
15989            PackageSetting ps = mSettings.mPackages.get(packageName);
15990            if (ps == null) {
15991                Log.w(TAG, "Package doesn't exist: " + packageName);
15992                return false;
15993            }
15994            if (systemUserApp) {
15995                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15996            } else {
15997                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15998            }
15999            mSettings.writeLPr();
16000        }
16001        return true;
16002    }
16003
16004    /*
16005     * This method handles package deletion in general
16006     */
16007    private boolean deletePackageLIF(String packageName, UserHandle user,
16008            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16009            PackageRemovedInfo outInfo, boolean writeSettings,
16010            PackageParser.Package replacingPackage) {
16011        if (packageName == null) {
16012            Slog.w(TAG, "Attempt to delete null packageName.");
16013            return false;
16014        }
16015
16016        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16017
16018        PackageSetting ps;
16019
16020        synchronized (mPackages) {
16021            ps = mSettings.mPackages.get(packageName);
16022            if (ps == null) {
16023                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16024                return false;
16025            }
16026
16027            if (ps.parentPackageName != null && (!isSystemApp(ps)
16028                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16029                if (DEBUG_REMOVE) {
16030                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16031                            + ((user == null) ? UserHandle.USER_ALL : user));
16032                }
16033                final int removedUserId = (user != null) ? user.getIdentifier()
16034                        : UserHandle.USER_ALL;
16035                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16036                    return false;
16037                }
16038                markPackageUninstalledForUserLPw(ps, user);
16039                scheduleWritePackageRestrictionsLocked(user);
16040                return true;
16041            }
16042        }
16043
16044        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16045                && user.getIdentifier() != UserHandle.USER_ALL)) {
16046            // The caller is asking that the package only be deleted for a single
16047            // user.  To do this, we just mark its uninstalled state and delete
16048            // its data. If this is a system app, we only allow this to happen if
16049            // they have set the special DELETE_SYSTEM_APP which requests different
16050            // semantics than normal for uninstalling system apps.
16051            markPackageUninstalledForUserLPw(ps, user);
16052
16053            if (!isSystemApp(ps)) {
16054                // Do not uninstall the APK if an app should be cached
16055                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16056                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16057                    // Other user still have this package installed, so all
16058                    // we need to do is clear this user's data and save that
16059                    // it is uninstalled.
16060                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16061                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16062                        return false;
16063                    }
16064                    scheduleWritePackageRestrictionsLocked(user);
16065                    return true;
16066                } else {
16067                    // We need to set it back to 'installed' so the uninstall
16068                    // broadcasts will be sent correctly.
16069                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16070                    ps.setInstalled(true, user.getIdentifier());
16071                }
16072            } else {
16073                // This is a system app, so we assume that the
16074                // other users still have this package installed, so all
16075                // we need to do is clear this user's data and save that
16076                // it is uninstalled.
16077                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16078                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16079                    return false;
16080                }
16081                scheduleWritePackageRestrictionsLocked(user);
16082                return true;
16083            }
16084        }
16085
16086        // If we are deleting a composite package for all users, keep track
16087        // of result for each child.
16088        if (ps.childPackageNames != null && outInfo != null) {
16089            synchronized (mPackages) {
16090                final int childCount = ps.childPackageNames.size();
16091                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16092                for (int i = 0; i < childCount; i++) {
16093                    String childPackageName = ps.childPackageNames.get(i);
16094                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16095                    childInfo.removedPackage = childPackageName;
16096                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16097                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16098                    if (childPs != null) {
16099                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16100                    }
16101                }
16102            }
16103        }
16104
16105        boolean ret = false;
16106        if (isSystemApp(ps)) {
16107            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16108            // When an updated system application is deleted we delete the existing resources
16109            // as well and fall back to existing code in system partition
16110            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16111        } else {
16112            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16113            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16114                    outInfo, writeSettings, replacingPackage);
16115        }
16116
16117        // Take a note whether we deleted the package for all users
16118        if (outInfo != null) {
16119            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16120            if (outInfo.removedChildPackages != null) {
16121                synchronized (mPackages) {
16122                    final int childCount = outInfo.removedChildPackages.size();
16123                    for (int i = 0; i < childCount; i++) {
16124                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16125                        if (childInfo != null) {
16126                            childInfo.removedForAllUsers = mPackages.get(
16127                                    childInfo.removedPackage) == null;
16128                        }
16129                    }
16130                }
16131            }
16132            // If we uninstalled an update to a system app there may be some
16133            // child packages that appeared as they are declared in the system
16134            // app but were not declared in the update.
16135            if (isSystemApp(ps)) {
16136                synchronized (mPackages) {
16137                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16138                    final int childCount = (updatedPs.childPackageNames != null)
16139                            ? updatedPs.childPackageNames.size() : 0;
16140                    for (int i = 0; i < childCount; i++) {
16141                        String childPackageName = updatedPs.childPackageNames.get(i);
16142                        if (outInfo.removedChildPackages == null
16143                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16144                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16145                            if (childPs == null) {
16146                                continue;
16147                            }
16148                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16149                            installRes.name = childPackageName;
16150                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16151                            installRes.pkg = mPackages.get(childPackageName);
16152                            installRes.uid = childPs.pkg.applicationInfo.uid;
16153                            if (outInfo.appearedChildPackages == null) {
16154                                outInfo.appearedChildPackages = new ArrayMap<>();
16155                            }
16156                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16157                        }
16158                    }
16159                }
16160            }
16161        }
16162
16163        return ret;
16164    }
16165
16166    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16167        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16168                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16169        for (int nextUserId : userIds) {
16170            if (DEBUG_REMOVE) {
16171                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16172            }
16173            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16174                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16175                    false /*hidden*/, false /*suspended*/, null, null, null,
16176                    false /*blockUninstall*/,
16177                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16178        }
16179    }
16180
16181    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16182            PackageRemovedInfo outInfo) {
16183        final PackageParser.Package pkg;
16184        synchronized (mPackages) {
16185            pkg = mPackages.get(ps.name);
16186        }
16187
16188        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16189                : new int[] {userId};
16190        for (int nextUserId : userIds) {
16191            if (DEBUG_REMOVE) {
16192                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16193                        + nextUserId);
16194            }
16195
16196            destroyAppDataLIF(pkg, userId,
16197                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16198            destroyAppProfilesLIF(pkg, userId);
16199            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16200            schedulePackageCleaning(ps.name, nextUserId, false);
16201            synchronized (mPackages) {
16202                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16203                    scheduleWritePackageRestrictionsLocked(nextUserId);
16204                }
16205                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16206            }
16207        }
16208
16209        if (outInfo != null) {
16210            outInfo.removedPackage = ps.name;
16211            outInfo.removedAppId = ps.appId;
16212            outInfo.removedUsers = userIds;
16213        }
16214
16215        return true;
16216    }
16217
16218    private final class ClearStorageConnection implements ServiceConnection {
16219        IMediaContainerService mContainerService;
16220
16221        @Override
16222        public void onServiceConnected(ComponentName name, IBinder service) {
16223            synchronized (this) {
16224                mContainerService = IMediaContainerService.Stub.asInterface(service);
16225                notifyAll();
16226            }
16227        }
16228
16229        @Override
16230        public void onServiceDisconnected(ComponentName name) {
16231        }
16232    }
16233
16234    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16235        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16236
16237        final boolean mounted;
16238        if (Environment.isExternalStorageEmulated()) {
16239            mounted = true;
16240        } else {
16241            final String status = Environment.getExternalStorageState();
16242
16243            mounted = status.equals(Environment.MEDIA_MOUNTED)
16244                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16245        }
16246
16247        if (!mounted) {
16248            return;
16249        }
16250
16251        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16252        int[] users;
16253        if (userId == UserHandle.USER_ALL) {
16254            users = sUserManager.getUserIds();
16255        } else {
16256            users = new int[] { userId };
16257        }
16258        final ClearStorageConnection conn = new ClearStorageConnection();
16259        if (mContext.bindServiceAsUser(
16260                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16261            try {
16262                for (int curUser : users) {
16263                    long timeout = SystemClock.uptimeMillis() + 5000;
16264                    synchronized (conn) {
16265                        long now = SystemClock.uptimeMillis();
16266                        while (conn.mContainerService == null && now < timeout) {
16267                            try {
16268                                conn.wait(timeout - now);
16269                            } catch (InterruptedException e) {
16270                            }
16271                        }
16272                    }
16273                    if (conn.mContainerService == null) {
16274                        return;
16275                    }
16276
16277                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16278                    clearDirectory(conn.mContainerService,
16279                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16280                    if (allData) {
16281                        clearDirectory(conn.mContainerService,
16282                                userEnv.buildExternalStorageAppDataDirs(packageName));
16283                        clearDirectory(conn.mContainerService,
16284                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16285                    }
16286                }
16287            } finally {
16288                mContext.unbindService(conn);
16289            }
16290        }
16291    }
16292
16293    @Override
16294    public void clearApplicationProfileData(String packageName) {
16295        enforceSystemOrRoot("Only the system can clear all profile data");
16296
16297        final PackageParser.Package pkg;
16298        synchronized (mPackages) {
16299            pkg = mPackages.get(packageName);
16300        }
16301
16302        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16303            synchronized (mInstallLock) {
16304                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16305            }
16306        }
16307    }
16308
16309    @Override
16310    public void clearApplicationUserData(final String packageName,
16311            final IPackageDataObserver observer, final int userId) {
16312        mContext.enforceCallingOrSelfPermission(
16313                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16314
16315        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16316                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16317
16318        final DevicePolicyManagerInternal dpmi = LocalServices
16319                .getService(DevicePolicyManagerInternal.class);
16320        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16321            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16322        }
16323        // Queue up an async operation since the package deletion may take a little while.
16324        mHandler.post(new Runnable() {
16325            public void run() {
16326                mHandler.removeCallbacks(this);
16327                final boolean succeeded;
16328                try (PackageFreezer freezer = freezePackage(packageName,
16329                        "clearApplicationUserData")) {
16330                    synchronized (mInstallLock) {
16331                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16332                    }
16333                    clearExternalStorageDataSync(packageName, userId, true);
16334                }
16335                if (succeeded) {
16336                    // invoke DeviceStorageMonitor's update method to clear any notifications
16337                    DeviceStorageMonitorInternal dsm = LocalServices
16338                            .getService(DeviceStorageMonitorInternal.class);
16339                    if (dsm != null) {
16340                        dsm.checkMemory();
16341                    }
16342                }
16343                if(observer != null) {
16344                    try {
16345                        observer.onRemoveCompleted(packageName, succeeded);
16346                    } catch (RemoteException e) {
16347                        Log.i(TAG, "Observer no longer exists.");
16348                    }
16349                } //end if observer
16350            } //end run
16351        });
16352    }
16353
16354    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16355        if (packageName == null) {
16356            Slog.w(TAG, "Attempt to delete null packageName.");
16357            return false;
16358        }
16359
16360        // Try finding details about the requested package
16361        PackageParser.Package pkg;
16362        synchronized (mPackages) {
16363            pkg = mPackages.get(packageName);
16364            if (pkg == null) {
16365                final PackageSetting ps = mSettings.mPackages.get(packageName);
16366                if (ps != null) {
16367                    pkg = ps.pkg;
16368                }
16369            }
16370
16371            if (pkg == null) {
16372                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16373                return false;
16374            }
16375
16376            PackageSetting ps = (PackageSetting) pkg.mExtras;
16377            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16378        }
16379
16380        clearAppDataLIF(pkg, userId,
16381                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16382
16383        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16384        removeKeystoreDataIfNeeded(userId, appId);
16385
16386        UserManagerInternal umInternal = getUserManagerInternal();
16387        final int flags;
16388        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16389            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16390        } else if (umInternal.isUserRunning(userId)) {
16391            flags = StorageManager.FLAG_STORAGE_DE;
16392        } else {
16393            flags = 0;
16394        }
16395        prepareAppDataContentsLIF(pkg, userId, flags);
16396
16397        return true;
16398    }
16399
16400    /**
16401     * Reverts user permission state changes (permissions and flags) in
16402     * all packages for a given user.
16403     *
16404     * @param userId The device user for which to do a reset.
16405     */
16406    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16407        final int packageCount = mPackages.size();
16408        for (int i = 0; i < packageCount; i++) {
16409            PackageParser.Package pkg = mPackages.valueAt(i);
16410            PackageSetting ps = (PackageSetting) pkg.mExtras;
16411            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16412        }
16413    }
16414
16415    private void resetNetworkPolicies(int userId) {
16416        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16417    }
16418
16419    /**
16420     * Reverts user permission state changes (permissions and flags).
16421     *
16422     * @param ps The package for which to reset.
16423     * @param userId The device user for which to do a reset.
16424     */
16425    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16426            final PackageSetting ps, final int userId) {
16427        if (ps.pkg == null) {
16428            return;
16429        }
16430
16431        // These are flags that can change base on user actions.
16432        final int userSettableMask = FLAG_PERMISSION_USER_SET
16433                | FLAG_PERMISSION_USER_FIXED
16434                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16435                | FLAG_PERMISSION_REVIEW_REQUIRED;
16436
16437        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16438                | FLAG_PERMISSION_POLICY_FIXED;
16439
16440        boolean writeInstallPermissions = false;
16441        boolean writeRuntimePermissions = false;
16442
16443        final int permissionCount = ps.pkg.requestedPermissions.size();
16444        for (int i = 0; i < permissionCount; i++) {
16445            String permission = ps.pkg.requestedPermissions.get(i);
16446
16447            BasePermission bp = mSettings.mPermissions.get(permission);
16448            if (bp == null) {
16449                continue;
16450            }
16451
16452            // If shared user we just reset the state to which only this app contributed.
16453            if (ps.sharedUser != null) {
16454                boolean used = false;
16455                final int packageCount = ps.sharedUser.packages.size();
16456                for (int j = 0; j < packageCount; j++) {
16457                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16458                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16459                            && pkg.pkg.requestedPermissions.contains(permission)) {
16460                        used = true;
16461                        break;
16462                    }
16463                }
16464                if (used) {
16465                    continue;
16466                }
16467            }
16468
16469            PermissionsState permissionsState = ps.getPermissionsState();
16470
16471            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16472
16473            // Always clear the user settable flags.
16474            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16475                    bp.name) != null;
16476            // If permission review is enabled and this is a legacy app, mark the
16477            // permission as requiring a review as this is the initial state.
16478            int flags = 0;
16479            if (Build.PERMISSIONS_REVIEW_REQUIRED
16480                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16481                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16482            }
16483            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16484                if (hasInstallState) {
16485                    writeInstallPermissions = true;
16486                } else {
16487                    writeRuntimePermissions = true;
16488                }
16489            }
16490
16491            // Below is only runtime permission handling.
16492            if (!bp.isRuntime()) {
16493                continue;
16494            }
16495
16496            // Never clobber system or policy.
16497            if ((oldFlags & policyOrSystemFlags) != 0) {
16498                continue;
16499            }
16500
16501            // If this permission was granted by default, make sure it is.
16502            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16503                if (permissionsState.grantRuntimePermission(bp, userId)
16504                        != PERMISSION_OPERATION_FAILURE) {
16505                    writeRuntimePermissions = true;
16506                }
16507            // If permission review is enabled the permissions for a legacy apps
16508            // are represented as constantly granted runtime ones, so don't revoke.
16509            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16510                // Otherwise, reset the permission.
16511                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16512                switch (revokeResult) {
16513                    case PERMISSION_OPERATION_SUCCESS:
16514                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16515                        writeRuntimePermissions = true;
16516                        final int appId = ps.appId;
16517                        mHandler.post(new Runnable() {
16518                            @Override
16519                            public void run() {
16520                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16521                            }
16522                        });
16523                    } break;
16524                }
16525            }
16526        }
16527
16528        // Synchronously write as we are taking permissions away.
16529        if (writeRuntimePermissions) {
16530            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16531        }
16532
16533        // Synchronously write as we are taking permissions away.
16534        if (writeInstallPermissions) {
16535            mSettings.writeLPr();
16536        }
16537    }
16538
16539    /**
16540     * Remove entries from the keystore daemon. Will only remove it if the
16541     * {@code appId} is valid.
16542     */
16543    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16544        if (appId < 0) {
16545            return;
16546        }
16547
16548        final KeyStore keyStore = KeyStore.getInstance();
16549        if (keyStore != null) {
16550            if (userId == UserHandle.USER_ALL) {
16551                for (final int individual : sUserManager.getUserIds()) {
16552                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16553                }
16554            } else {
16555                keyStore.clearUid(UserHandle.getUid(userId, appId));
16556            }
16557        } else {
16558            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16559        }
16560    }
16561
16562    @Override
16563    public void deleteApplicationCacheFiles(final String packageName,
16564            final IPackageDataObserver observer) {
16565        final int userId = UserHandle.getCallingUserId();
16566        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16567    }
16568
16569    @Override
16570    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16571            final IPackageDataObserver observer) {
16572        mContext.enforceCallingOrSelfPermission(
16573                android.Manifest.permission.DELETE_CACHE_FILES, null);
16574        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16575                /* requireFullPermission= */ true, /* checkShell= */ false,
16576                "delete application cache files");
16577
16578        final PackageParser.Package pkg;
16579        synchronized (mPackages) {
16580            pkg = mPackages.get(packageName);
16581        }
16582
16583        // Queue up an async operation since the package deletion may take a little while.
16584        mHandler.post(new Runnable() {
16585            public void run() {
16586                synchronized (mInstallLock) {
16587                    final int flags = StorageManager.FLAG_STORAGE_DE
16588                            | StorageManager.FLAG_STORAGE_CE;
16589                    // We're only clearing cache files, so we don't care if the
16590                    // app is unfrozen and still able to run
16591                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16592                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16593                }
16594                clearExternalStorageDataSync(packageName, userId, false);
16595                if (observer != null) {
16596                    try {
16597                        observer.onRemoveCompleted(packageName, true);
16598                    } catch (RemoteException e) {
16599                        Log.i(TAG, "Observer no longer exists.");
16600                    }
16601                }
16602            }
16603        });
16604    }
16605
16606    @Override
16607    public void getPackageSizeInfo(final String packageName, int userHandle,
16608            final IPackageStatsObserver observer) {
16609        mContext.enforceCallingOrSelfPermission(
16610                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16611        if (packageName == null) {
16612            throw new IllegalArgumentException("Attempt to get size of null packageName");
16613        }
16614
16615        PackageStats stats = new PackageStats(packageName, userHandle);
16616
16617        /*
16618         * Queue up an async operation since the package measurement may take a
16619         * little while.
16620         */
16621        Message msg = mHandler.obtainMessage(INIT_COPY);
16622        msg.obj = new MeasureParams(stats, observer);
16623        mHandler.sendMessage(msg);
16624    }
16625
16626    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16627        final PackageSetting ps;
16628        synchronized (mPackages) {
16629            ps = mSettings.mPackages.get(packageName);
16630            if (ps == null) {
16631                Slog.w(TAG, "Failed to find settings for " + packageName);
16632                return false;
16633            }
16634        }
16635        try {
16636            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16637                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16638                    ps.getCeDataInode(userId), ps.codePathString, stats);
16639        } catch (InstallerException e) {
16640            Slog.w(TAG, String.valueOf(e));
16641            return false;
16642        }
16643
16644        // For now, ignore code size of packages on system partition
16645        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16646            stats.codeSize = 0;
16647        }
16648
16649        return true;
16650    }
16651
16652    private int getUidTargetSdkVersionLockedLPr(int uid) {
16653        Object obj = mSettings.getUserIdLPr(uid);
16654        if (obj instanceof SharedUserSetting) {
16655            final SharedUserSetting sus = (SharedUserSetting) obj;
16656            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16657            final Iterator<PackageSetting> it = sus.packages.iterator();
16658            while (it.hasNext()) {
16659                final PackageSetting ps = it.next();
16660                if (ps.pkg != null) {
16661                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16662                    if (v < vers) vers = v;
16663                }
16664            }
16665            return vers;
16666        } else if (obj instanceof PackageSetting) {
16667            final PackageSetting ps = (PackageSetting) obj;
16668            if (ps.pkg != null) {
16669                return ps.pkg.applicationInfo.targetSdkVersion;
16670            }
16671        }
16672        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16673    }
16674
16675    @Override
16676    public void addPreferredActivity(IntentFilter filter, int match,
16677            ComponentName[] set, ComponentName activity, int userId) {
16678        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16679                "Adding preferred");
16680    }
16681
16682    private void addPreferredActivityInternal(IntentFilter filter, int match,
16683            ComponentName[] set, ComponentName activity, boolean always, int userId,
16684            String opname) {
16685        // writer
16686        int callingUid = Binder.getCallingUid();
16687        enforceCrossUserPermission(callingUid, userId,
16688                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16689        if (filter.countActions() == 0) {
16690            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16691            return;
16692        }
16693        synchronized (mPackages) {
16694            if (mContext.checkCallingOrSelfPermission(
16695                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16696                    != PackageManager.PERMISSION_GRANTED) {
16697                if (getUidTargetSdkVersionLockedLPr(callingUid)
16698                        < Build.VERSION_CODES.FROYO) {
16699                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16700                            + callingUid);
16701                    return;
16702                }
16703                mContext.enforceCallingOrSelfPermission(
16704                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16705            }
16706
16707            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16708            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16709                    + userId + ":");
16710            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16711            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16712            scheduleWritePackageRestrictionsLocked(userId);
16713        }
16714    }
16715
16716    @Override
16717    public void replacePreferredActivity(IntentFilter filter, int match,
16718            ComponentName[] set, ComponentName activity, int userId) {
16719        if (filter.countActions() != 1) {
16720            throw new IllegalArgumentException(
16721                    "replacePreferredActivity expects filter to have only 1 action.");
16722        }
16723        if (filter.countDataAuthorities() != 0
16724                || filter.countDataPaths() != 0
16725                || filter.countDataSchemes() > 1
16726                || filter.countDataTypes() != 0) {
16727            throw new IllegalArgumentException(
16728                    "replacePreferredActivity expects filter to have no data authorities, " +
16729                    "paths, or types; and at most one scheme.");
16730        }
16731
16732        final int callingUid = Binder.getCallingUid();
16733        enforceCrossUserPermission(callingUid, userId,
16734                true /* requireFullPermission */, false /* checkShell */,
16735                "replace preferred activity");
16736        synchronized (mPackages) {
16737            if (mContext.checkCallingOrSelfPermission(
16738                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16739                    != PackageManager.PERMISSION_GRANTED) {
16740                if (getUidTargetSdkVersionLockedLPr(callingUid)
16741                        < Build.VERSION_CODES.FROYO) {
16742                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16743                            + Binder.getCallingUid());
16744                    return;
16745                }
16746                mContext.enforceCallingOrSelfPermission(
16747                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16748            }
16749
16750            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16751            if (pir != null) {
16752                // Get all of the existing entries that exactly match this filter.
16753                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16754                if (existing != null && existing.size() == 1) {
16755                    PreferredActivity cur = existing.get(0);
16756                    if (DEBUG_PREFERRED) {
16757                        Slog.i(TAG, "Checking replace of preferred:");
16758                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16759                        if (!cur.mPref.mAlways) {
16760                            Slog.i(TAG, "  -- CUR; not mAlways!");
16761                        } else {
16762                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16763                            Slog.i(TAG, "  -- CUR: mSet="
16764                                    + Arrays.toString(cur.mPref.mSetComponents));
16765                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16766                            Slog.i(TAG, "  -- NEW: mMatch="
16767                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16768                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16769                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16770                        }
16771                    }
16772                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16773                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16774                            && cur.mPref.sameSet(set)) {
16775                        // Setting the preferred activity to what it happens to be already
16776                        if (DEBUG_PREFERRED) {
16777                            Slog.i(TAG, "Replacing with same preferred activity "
16778                                    + cur.mPref.mShortComponent + " for user "
16779                                    + userId + ":");
16780                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16781                        }
16782                        return;
16783                    }
16784                }
16785
16786                if (existing != null) {
16787                    if (DEBUG_PREFERRED) {
16788                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16789                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16790                    }
16791                    for (int i = 0; i < existing.size(); i++) {
16792                        PreferredActivity pa = existing.get(i);
16793                        if (DEBUG_PREFERRED) {
16794                            Slog.i(TAG, "Removing existing preferred activity "
16795                                    + pa.mPref.mComponent + ":");
16796                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16797                        }
16798                        pir.removeFilter(pa);
16799                    }
16800                }
16801            }
16802            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16803                    "Replacing preferred");
16804        }
16805    }
16806
16807    @Override
16808    public void clearPackagePreferredActivities(String packageName) {
16809        final int uid = Binder.getCallingUid();
16810        // writer
16811        synchronized (mPackages) {
16812            PackageParser.Package pkg = mPackages.get(packageName);
16813            if (pkg == null || pkg.applicationInfo.uid != uid) {
16814                if (mContext.checkCallingOrSelfPermission(
16815                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16816                        != PackageManager.PERMISSION_GRANTED) {
16817                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16818                            < Build.VERSION_CODES.FROYO) {
16819                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16820                                + Binder.getCallingUid());
16821                        return;
16822                    }
16823                    mContext.enforceCallingOrSelfPermission(
16824                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16825                }
16826            }
16827
16828            int user = UserHandle.getCallingUserId();
16829            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16830                scheduleWritePackageRestrictionsLocked(user);
16831            }
16832        }
16833    }
16834
16835    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16836    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16837        ArrayList<PreferredActivity> removed = null;
16838        boolean changed = false;
16839        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16840            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16841            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16842            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16843                continue;
16844            }
16845            Iterator<PreferredActivity> it = pir.filterIterator();
16846            while (it.hasNext()) {
16847                PreferredActivity pa = it.next();
16848                // Mark entry for removal only if it matches the package name
16849                // and the entry is of type "always".
16850                if (packageName == null ||
16851                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16852                                && pa.mPref.mAlways)) {
16853                    if (removed == null) {
16854                        removed = new ArrayList<PreferredActivity>();
16855                    }
16856                    removed.add(pa);
16857                }
16858            }
16859            if (removed != null) {
16860                for (int j=0; j<removed.size(); j++) {
16861                    PreferredActivity pa = removed.get(j);
16862                    pir.removeFilter(pa);
16863                }
16864                changed = true;
16865            }
16866        }
16867        return changed;
16868    }
16869
16870    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16871    private void clearIntentFilterVerificationsLPw(int userId) {
16872        final int packageCount = mPackages.size();
16873        for (int i = 0; i < packageCount; i++) {
16874            PackageParser.Package pkg = mPackages.valueAt(i);
16875            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16876        }
16877    }
16878
16879    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16880    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16881        if (userId == UserHandle.USER_ALL) {
16882            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16883                    sUserManager.getUserIds())) {
16884                for (int oneUserId : sUserManager.getUserIds()) {
16885                    scheduleWritePackageRestrictionsLocked(oneUserId);
16886                }
16887            }
16888        } else {
16889            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16890                scheduleWritePackageRestrictionsLocked(userId);
16891            }
16892        }
16893    }
16894
16895    void clearDefaultBrowserIfNeeded(String packageName) {
16896        for (int oneUserId : sUserManager.getUserIds()) {
16897            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16898            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16899            if (packageName.equals(defaultBrowserPackageName)) {
16900                setDefaultBrowserPackageName(null, oneUserId);
16901            }
16902        }
16903    }
16904
16905    @Override
16906    public void resetApplicationPreferences(int userId) {
16907        mContext.enforceCallingOrSelfPermission(
16908                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16909        final long identity = Binder.clearCallingIdentity();
16910        // writer
16911        try {
16912            synchronized (mPackages) {
16913                clearPackagePreferredActivitiesLPw(null, userId);
16914                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16915                // TODO: We have to reset the default SMS and Phone. This requires
16916                // significant refactoring to keep all default apps in the package
16917                // manager (cleaner but more work) or have the services provide
16918                // callbacks to the package manager to request a default app reset.
16919                applyFactoryDefaultBrowserLPw(userId);
16920                clearIntentFilterVerificationsLPw(userId);
16921                primeDomainVerificationsLPw(userId);
16922                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16923                scheduleWritePackageRestrictionsLocked(userId);
16924            }
16925            resetNetworkPolicies(userId);
16926        } finally {
16927            Binder.restoreCallingIdentity(identity);
16928        }
16929    }
16930
16931    @Override
16932    public int getPreferredActivities(List<IntentFilter> outFilters,
16933            List<ComponentName> outActivities, String packageName) {
16934
16935        int num = 0;
16936        final int userId = UserHandle.getCallingUserId();
16937        // reader
16938        synchronized (mPackages) {
16939            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16940            if (pir != null) {
16941                final Iterator<PreferredActivity> it = pir.filterIterator();
16942                while (it.hasNext()) {
16943                    final PreferredActivity pa = it.next();
16944                    if (packageName == null
16945                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16946                                    && pa.mPref.mAlways)) {
16947                        if (outFilters != null) {
16948                            outFilters.add(new IntentFilter(pa));
16949                        }
16950                        if (outActivities != null) {
16951                            outActivities.add(pa.mPref.mComponent);
16952                        }
16953                    }
16954                }
16955            }
16956        }
16957
16958        return num;
16959    }
16960
16961    @Override
16962    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16963            int userId) {
16964        int callingUid = Binder.getCallingUid();
16965        if (callingUid != Process.SYSTEM_UID) {
16966            throw new SecurityException(
16967                    "addPersistentPreferredActivity can only be run by the system");
16968        }
16969        if (filter.countActions() == 0) {
16970            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16971            return;
16972        }
16973        synchronized (mPackages) {
16974            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16975                    ":");
16976            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16977            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16978                    new PersistentPreferredActivity(filter, activity));
16979            scheduleWritePackageRestrictionsLocked(userId);
16980        }
16981    }
16982
16983    @Override
16984    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16985        int callingUid = Binder.getCallingUid();
16986        if (callingUid != Process.SYSTEM_UID) {
16987            throw new SecurityException(
16988                    "clearPackagePersistentPreferredActivities can only be run by the system");
16989        }
16990        ArrayList<PersistentPreferredActivity> removed = null;
16991        boolean changed = false;
16992        synchronized (mPackages) {
16993            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16994                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16995                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16996                        .valueAt(i);
16997                if (userId != thisUserId) {
16998                    continue;
16999                }
17000                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17001                while (it.hasNext()) {
17002                    PersistentPreferredActivity ppa = it.next();
17003                    // Mark entry for removal only if it matches the package name.
17004                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17005                        if (removed == null) {
17006                            removed = new ArrayList<PersistentPreferredActivity>();
17007                        }
17008                        removed.add(ppa);
17009                    }
17010                }
17011                if (removed != null) {
17012                    for (int j=0; j<removed.size(); j++) {
17013                        PersistentPreferredActivity ppa = removed.get(j);
17014                        ppir.removeFilter(ppa);
17015                    }
17016                    changed = true;
17017                }
17018            }
17019
17020            if (changed) {
17021                scheduleWritePackageRestrictionsLocked(userId);
17022            }
17023        }
17024    }
17025
17026    /**
17027     * Common machinery for picking apart a restored XML blob and passing
17028     * it to a caller-supplied functor to be applied to the running system.
17029     */
17030    private void restoreFromXml(XmlPullParser parser, int userId,
17031            String expectedStartTag, BlobXmlRestorer functor)
17032            throws IOException, XmlPullParserException {
17033        int type;
17034        while ((type = parser.next()) != XmlPullParser.START_TAG
17035                && type != XmlPullParser.END_DOCUMENT) {
17036        }
17037        if (type != XmlPullParser.START_TAG) {
17038            // oops didn't find a start tag?!
17039            if (DEBUG_BACKUP) {
17040                Slog.e(TAG, "Didn't find start tag during restore");
17041            }
17042            return;
17043        }
17044Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17045        // this is supposed to be TAG_PREFERRED_BACKUP
17046        if (!expectedStartTag.equals(parser.getName())) {
17047            if (DEBUG_BACKUP) {
17048                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17049            }
17050            return;
17051        }
17052
17053        // skip interfering stuff, then we're aligned with the backing implementation
17054        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17055Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17056        functor.apply(parser, userId);
17057    }
17058
17059    private interface BlobXmlRestorer {
17060        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17061    }
17062
17063    /**
17064     * Non-Binder method, support for the backup/restore mechanism: write the
17065     * full set of preferred activities in its canonical XML format.  Returns the
17066     * XML output as a byte array, or null if there is none.
17067     */
17068    @Override
17069    public byte[] getPreferredActivityBackup(int userId) {
17070        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17071            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17072        }
17073
17074        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17075        try {
17076            final XmlSerializer serializer = new FastXmlSerializer();
17077            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17078            serializer.startDocument(null, true);
17079            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17080
17081            synchronized (mPackages) {
17082                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17083            }
17084
17085            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17086            serializer.endDocument();
17087            serializer.flush();
17088        } catch (Exception e) {
17089            if (DEBUG_BACKUP) {
17090                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17091            }
17092            return null;
17093        }
17094
17095        return dataStream.toByteArray();
17096    }
17097
17098    @Override
17099    public void restorePreferredActivities(byte[] backup, int userId) {
17100        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17101            throw new SecurityException("Only the system may call restorePreferredActivities()");
17102        }
17103
17104        try {
17105            final XmlPullParser parser = Xml.newPullParser();
17106            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17107            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17108                    new BlobXmlRestorer() {
17109                        @Override
17110                        public void apply(XmlPullParser parser, int userId)
17111                                throws XmlPullParserException, IOException {
17112                            synchronized (mPackages) {
17113                                mSettings.readPreferredActivitiesLPw(parser, userId);
17114                            }
17115                        }
17116                    } );
17117        } catch (Exception e) {
17118            if (DEBUG_BACKUP) {
17119                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17120            }
17121        }
17122    }
17123
17124    /**
17125     * Non-Binder method, support for the backup/restore mechanism: write the
17126     * default browser (etc) settings in its canonical XML format.  Returns the default
17127     * browser XML representation as a byte array, or null if there is none.
17128     */
17129    @Override
17130    public byte[] getDefaultAppsBackup(int userId) {
17131        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17132            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17133        }
17134
17135        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17136        try {
17137            final XmlSerializer serializer = new FastXmlSerializer();
17138            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17139            serializer.startDocument(null, true);
17140            serializer.startTag(null, TAG_DEFAULT_APPS);
17141
17142            synchronized (mPackages) {
17143                mSettings.writeDefaultAppsLPr(serializer, userId);
17144            }
17145
17146            serializer.endTag(null, TAG_DEFAULT_APPS);
17147            serializer.endDocument();
17148            serializer.flush();
17149        } catch (Exception e) {
17150            if (DEBUG_BACKUP) {
17151                Slog.e(TAG, "Unable to write default apps for backup", e);
17152            }
17153            return null;
17154        }
17155
17156        return dataStream.toByteArray();
17157    }
17158
17159    @Override
17160    public void restoreDefaultApps(byte[] backup, int userId) {
17161        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17162            throw new SecurityException("Only the system may call restoreDefaultApps()");
17163        }
17164
17165        try {
17166            final XmlPullParser parser = Xml.newPullParser();
17167            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17168            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17169                    new BlobXmlRestorer() {
17170                        @Override
17171                        public void apply(XmlPullParser parser, int userId)
17172                                throws XmlPullParserException, IOException {
17173                            synchronized (mPackages) {
17174                                mSettings.readDefaultAppsLPw(parser, userId);
17175                            }
17176                        }
17177                    } );
17178        } catch (Exception e) {
17179            if (DEBUG_BACKUP) {
17180                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17181            }
17182        }
17183    }
17184
17185    @Override
17186    public byte[] getIntentFilterVerificationBackup(int userId) {
17187        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17188            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17189        }
17190
17191        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17192        try {
17193            final XmlSerializer serializer = new FastXmlSerializer();
17194            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17195            serializer.startDocument(null, true);
17196            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17197
17198            synchronized (mPackages) {
17199                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17200            }
17201
17202            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17203            serializer.endDocument();
17204            serializer.flush();
17205        } catch (Exception e) {
17206            if (DEBUG_BACKUP) {
17207                Slog.e(TAG, "Unable to write default apps for backup", e);
17208            }
17209            return null;
17210        }
17211
17212        return dataStream.toByteArray();
17213    }
17214
17215    @Override
17216    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17217        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17218            throw new SecurityException("Only the system may call restorePreferredActivities()");
17219        }
17220
17221        try {
17222            final XmlPullParser parser = Xml.newPullParser();
17223            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17224            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17225                    new BlobXmlRestorer() {
17226                        @Override
17227                        public void apply(XmlPullParser parser, int userId)
17228                                throws XmlPullParserException, IOException {
17229                            synchronized (mPackages) {
17230                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17231                                mSettings.writeLPr();
17232                            }
17233                        }
17234                    } );
17235        } catch (Exception e) {
17236            if (DEBUG_BACKUP) {
17237                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17238            }
17239        }
17240    }
17241
17242    @Override
17243    public byte[] getPermissionGrantBackup(int userId) {
17244        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17245            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17246        }
17247
17248        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17249        try {
17250            final XmlSerializer serializer = new FastXmlSerializer();
17251            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17252            serializer.startDocument(null, true);
17253            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17254
17255            synchronized (mPackages) {
17256                serializeRuntimePermissionGrantsLPr(serializer, userId);
17257            }
17258
17259            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17260            serializer.endDocument();
17261            serializer.flush();
17262        } catch (Exception e) {
17263            if (DEBUG_BACKUP) {
17264                Slog.e(TAG, "Unable to write default apps for backup", e);
17265            }
17266            return null;
17267        }
17268
17269        return dataStream.toByteArray();
17270    }
17271
17272    @Override
17273    public void restorePermissionGrants(byte[] backup, int userId) {
17274        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17275            throw new SecurityException("Only the system may call restorePermissionGrants()");
17276        }
17277
17278        try {
17279            final XmlPullParser parser = Xml.newPullParser();
17280            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17281            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17282                    new BlobXmlRestorer() {
17283                        @Override
17284                        public void apply(XmlPullParser parser, int userId)
17285                                throws XmlPullParserException, IOException {
17286                            synchronized (mPackages) {
17287                                processRestoredPermissionGrantsLPr(parser, userId);
17288                            }
17289                        }
17290                    } );
17291        } catch (Exception e) {
17292            if (DEBUG_BACKUP) {
17293                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17294            }
17295        }
17296    }
17297
17298    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17299            throws IOException {
17300        serializer.startTag(null, TAG_ALL_GRANTS);
17301
17302        final int N = mSettings.mPackages.size();
17303        for (int i = 0; i < N; i++) {
17304            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17305            boolean pkgGrantsKnown = false;
17306
17307            PermissionsState packagePerms = ps.getPermissionsState();
17308
17309            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17310                final int grantFlags = state.getFlags();
17311                // only look at grants that are not system/policy fixed
17312                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17313                    final boolean isGranted = state.isGranted();
17314                    // And only back up the user-twiddled state bits
17315                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17316                        final String packageName = mSettings.mPackages.keyAt(i);
17317                        if (!pkgGrantsKnown) {
17318                            serializer.startTag(null, TAG_GRANT);
17319                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17320                            pkgGrantsKnown = true;
17321                        }
17322
17323                        final boolean userSet =
17324                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17325                        final boolean userFixed =
17326                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17327                        final boolean revoke =
17328                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17329
17330                        serializer.startTag(null, TAG_PERMISSION);
17331                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17332                        if (isGranted) {
17333                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17334                        }
17335                        if (userSet) {
17336                            serializer.attribute(null, ATTR_USER_SET, "true");
17337                        }
17338                        if (userFixed) {
17339                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17340                        }
17341                        if (revoke) {
17342                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17343                        }
17344                        serializer.endTag(null, TAG_PERMISSION);
17345                    }
17346                }
17347            }
17348
17349            if (pkgGrantsKnown) {
17350                serializer.endTag(null, TAG_GRANT);
17351            }
17352        }
17353
17354        serializer.endTag(null, TAG_ALL_GRANTS);
17355    }
17356
17357    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17358            throws XmlPullParserException, IOException {
17359        String pkgName = null;
17360        int outerDepth = parser.getDepth();
17361        int type;
17362        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17363                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17364            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17365                continue;
17366            }
17367
17368            final String tagName = parser.getName();
17369            if (tagName.equals(TAG_GRANT)) {
17370                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17371                if (DEBUG_BACKUP) {
17372                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17373                }
17374            } else if (tagName.equals(TAG_PERMISSION)) {
17375
17376                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17377                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17378
17379                int newFlagSet = 0;
17380                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17381                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17382                }
17383                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17384                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17385                }
17386                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17387                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17388                }
17389                if (DEBUG_BACKUP) {
17390                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17391                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17392                }
17393                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17394                if (ps != null) {
17395                    // Already installed so we apply the grant immediately
17396                    if (DEBUG_BACKUP) {
17397                        Slog.v(TAG, "        + already installed; applying");
17398                    }
17399                    PermissionsState perms = ps.getPermissionsState();
17400                    BasePermission bp = mSettings.mPermissions.get(permName);
17401                    if (bp != null) {
17402                        if (isGranted) {
17403                            perms.grantRuntimePermission(bp, userId);
17404                        }
17405                        if (newFlagSet != 0) {
17406                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17407                        }
17408                    }
17409                } else {
17410                    // Need to wait for post-restore install to apply the grant
17411                    if (DEBUG_BACKUP) {
17412                        Slog.v(TAG, "        - not yet installed; saving for later");
17413                    }
17414                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17415                            isGranted, newFlagSet, userId);
17416                }
17417            } else {
17418                PackageManagerService.reportSettingsProblem(Log.WARN,
17419                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17420                XmlUtils.skipCurrentTag(parser);
17421            }
17422        }
17423
17424        scheduleWriteSettingsLocked();
17425        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17426    }
17427
17428    @Override
17429    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17430            int sourceUserId, int targetUserId, int flags) {
17431        mContext.enforceCallingOrSelfPermission(
17432                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17433        int callingUid = Binder.getCallingUid();
17434        enforceOwnerRights(ownerPackage, callingUid);
17435        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17436        if (intentFilter.countActions() == 0) {
17437            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17438            return;
17439        }
17440        synchronized (mPackages) {
17441            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17442                    ownerPackage, targetUserId, flags);
17443            CrossProfileIntentResolver resolver =
17444                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17445            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17446            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17447            if (existing != null) {
17448                int size = existing.size();
17449                for (int i = 0; i < size; i++) {
17450                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17451                        return;
17452                    }
17453                }
17454            }
17455            resolver.addFilter(newFilter);
17456            scheduleWritePackageRestrictionsLocked(sourceUserId);
17457        }
17458    }
17459
17460    @Override
17461    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17462        mContext.enforceCallingOrSelfPermission(
17463                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17464        int callingUid = Binder.getCallingUid();
17465        enforceOwnerRights(ownerPackage, callingUid);
17466        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17467        synchronized (mPackages) {
17468            CrossProfileIntentResolver resolver =
17469                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17470            ArraySet<CrossProfileIntentFilter> set =
17471                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17472            for (CrossProfileIntentFilter filter : set) {
17473                if (filter.getOwnerPackage().equals(ownerPackage)) {
17474                    resolver.removeFilter(filter);
17475                }
17476            }
17477            scheduleWritePackageRestrictionsLocked(sourceUserId);
17478        }
17479    }
17480
17481    // Enforcing that callingUid is owning pkg on userId
17482    private void enforceOwnerRights(String pkg, int callingUid) {
17483        // The system owns everything.
17484        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17485            return;
17486        }
17487        int callingUserId = UserHandle.getUserId(callingUid);
17488        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17489        if (pi == null) {
17490            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17491                    + callingUserId);
17492        }
17493        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17494            throw new SecurityException("Calling uid " + callingUid
17495                    + " does not own package " + pkg);
17496        }
17497    }
17498
17499    @Override
17500    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17501        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17502    }
17503
17504    private Intent getHomeIntent() {
17505        Intent intent = new Intent(Intent.ACTION_MAIN);
17506        intent.addCategory(Intent.CATEGORY_HOME);
17507        return intent;
17508    }
17509
17510    private IntentFilter getHomeFilter() {
17511        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17512        filter.addCategory(Intent.CATEGORY_HOME);
17513        filter.addCategory(Intent.CATEGORY_DEFAULT);
17514        return filter;
17515    }
17516
17517    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17518            int userId) {
17519        Intent intent  = getHomeIntent();
17520        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17521                PackageManager.GET_META_DATA, userId);
17522        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17523                true, false, false, userId);
17524
17525        allHomeCandidates.clear();
17526        if (list != null) {
17527            for (ResolveInfo ri : list) {
17528                allHomeCandidates.add(ri);
17529            }
17530        }
17531        return (preferred == null || preferred.activityInfo == null)
17532                ? null
17533                : new ComponentName(preferred.activityInfo.packageName,
17534                        preferred.activityInfo.name);
17535    }
17536
17537    @Override
17538    public void setHomeActivity(ComponentName comp, int userId) {
17539        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17540        getHomeActivitiesAsUser(homeActivities, userId);
17541
17542        boolean found = false;
17543
17544        final int size = homeActivities.size();
17545        final ComponentName[] set = new ComponentName[size];
17546        for (int i = 0; i < size; i++) {
17547            final ResolveInfo candidate = homeActivities.get(i);
17548            final ActivityInfo info = candidate.activityInfo;
17549            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17550            set[i] = activityName;
17551            if (!found && activityName.equals(comp)) {
17552                found = true;
17553            }
17554        }
17555        if (!found) {
17556            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17557                    + userId);
17558        }
17559        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17560                set, comp, userId);
17561    }
17562
17563    private @Nullable String getSetupWizardPackageName() {
17564        final Intent intent = new Intent(Intent.ACTION_MAIN);
17565        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17566
17567        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17568                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17569                        | MATCH_DISABLED_COMPONENTS,
17570                UserHandle.myUserId());
17571        if (matches.size() == 1) {
17572            return matches.get(0).getComponentInfo().packageName;
17573        } else {
17574            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17575                    + ": matches=" + matches);
17576            return null;
17577        }
17578    }
17579
17580    @Override
17581    public void setApplicationEnabledSetting(String appPackageName,
17582            int newState, int flags, int userId, String callingPackage) {
17583        if (!sUserManager.exists(userId)) return;
17584        if (callingPackage == null) {
17585            callingPackage = Integer.toString(Binder.getCallingUid());
17586        }
17587        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17588    }
17589
17590    @Override
17591    public void setComponentEnabledSetting(ComponentName componentName,
17592            int newState, int flags, int userId) {
17593        if (!sUserManager.exists(userId)) return;
17594        setEnabledSetting(componentName.getPackageName(),
17595                componentName.getClassName(), newState, flags, userId, null);
17596    }
17597
17598    private void setEnabledSetting(final String packageName, String className, int newState,
17599            final int flags, int userId, String callingPackage) {
17600        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17601              || newState == COMPONENT_ENABLED_STATE_ENABLED
17602              || newState == COMPONENT_ENABLED_STATE_DISABLED
17603              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17604              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17605            throw new IllegalArgumentException("Invalid new component state: "
17606                    + newState);
17607        }
17608        PackageSetting pkgSetting;
17609        final int uid = Binder.getCallingUid();
17610        final int permission;
17611        if (uid == Process.SYSTEM_UID) {
17612            permission = PackageManager.PERMISSION_GRANTED;
17613        } else {
17614            permission = mContext.checkCallingOrSelfPermission(
17615                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17616        }
17617        enforceCrossUserPermission(uid, userId,
17618                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17619        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17620        boolean sendNow = false;
17621        boolean isApp = (className == null);
17622        String componentName = isApp ? packageName : className;
17623        int packageUid = -1;
17624        ArrayList<String> components;
17625
17626        // writer
17627        synchronized (mPackages) {
17628            pkgSetting = mSettings.mPackages.get(packageName);
17629            if (pkgSetting == null) {
17630                if (className == null) {
17631                    throw new IllegalArgumentException("Unknown package: " + packageName);
17632                }
17633                throw new IllegalArgumentException(
17634                        "Unknown component: " + packageName + "/" + className);
17635            }
17636        }
17637
17638        // Limit who can change which apps
17639        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17640            // Don't allow apps that don't have permission to modify other apps
17641            if (!allowedByPermission) {
17642                throw new SecurityException(
17643                        "Permission Denial: attempt to change component state from pid="
17644                        + Binder.getCallingPid()
17645                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17646            }
17647            // Don't allow changing profile and device owners. Calling into DPMS, so no locking.
17648            final DevicePolicyManagerInternal dpmi = LocalServices
17649                    .getService(DevicePolicyManagerInternal.class);
17650            if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
17651                throw new SecurityException("Cannot disable a device owner or a profile owner");
17652            }
17653        }
17654
17655        synchronized (mPackages) {
17656            if (uid == Process.SHELL_UID) {
17657                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17658                int oldState = pkgSetting.getEnabled(userId);
17659                if (className == null
17660                    &&
17661                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17662                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17663                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17664                    &&
17665                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17666                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17667                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17668                    // ok
17669                } else {
17670                    throw new SecurityException(
17671                            "Shell cannot change component state for " + packageName + "/"
17672                            + className + " to " + newState);
17673                }
17674            }
17675            if (className == null) {
17676                // We're dealing with an application/package level state change
17677                if (pkgSetting.getEnabled(userId) == newState) {
17678                    // Nothing to do
17679                    return;
17680                }
17681                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17682                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17683                    // Don't care about who enables an app.
17684                    callingPackage = null;
17685                }
17686                pkgSetting.setEnabled(newState, userId, callingPackage);
17687                // pkgSetting.pkg.mSetEnabled = newState;
17688            } else {
17689                // We're dealing with a component level state change
17690                // First, verify that this is a valid class name.
17691                PackageParser.Package pkg = pkgSetting.pkg;
17692                if (pkg == null || !pkg.hasComponentClassName(className)) {
17693                    if (pkg != null &&
17694                            pkg.applicationInfo.targetSdkVersion >=
17695                                    Build.VERSION_CODES.JELLY_BEAN) {
17696                        throw new IllegalArgumentException("Component class " + className
17697                                + " does not exist in " + packageName);
17698                    } else {
17699                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17700                                + className + " does not exist in " + packageName);
17701                    }
17702                }
17703                switch (newState) {
17704                case COMPONENT_ENABLED_STATE_ENABLED:
17705                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17706                        return;
17707                    }
17708                    break;
17709                case COMPONENT_ENABLED_STATE_DISABLED:
17710                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17711                        return;
17712                    }
17713                    break;
17714                case COMPONENT_ENABLED_STATE_DEFAULT:
17715                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17716                        return;
17717                    }
17718                    break;
17719                default:
17720                    Slog.e(TAG, "Invalid new component state: " + newState);
17721                    return;
17722                }
17723            }
17724            scheduleWritePackageRestrictionsLocked(userId);
17725            components = mPendingBroadcasts.get(userId, packageName);
17726            final boolean newPackage = components == null;
17727            if (newPackage) {
17728                components = new ArrayList<String>();
17729            }
17730            if (!components.contains(componentName)) {
17731                components.add(componentName);
17732            }
17733            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17734                sendNow = true;
17735                // Purge entry from pending broadcast list if another one exists already
17736                // since we are sending one right away.
17737                mPendingBroadcasts.remove(userId, packageName);
17738            } else {
17739                if (newPackage) {
17740                    mPendingBroadcasts.put(userId, packageName, components);
17741                }
17742                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17743                    // Schedule a message
17744                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17745                }
17746            }
17747        }
17748
17749        long callingId = Binder.clearCallingIdentity();
17750        try {
17751            if (sendNow) {
17752                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17753                sendPackageChangedBroadcast(packageName,
17754                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17755            }
17756        } finally {
17757            Binder.restoreCallingIdentity(callingId);
17758        }
17759    }
17760
17761    @Override
17762    public void flushPackageRestrictionsAsUser(int userId) {
17763        if (!sUserManager.exists(userId)) {
17764            return;
17765        }
17766        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17767                false /* checkShell */, "flushPackageRestrictions");
17768        synchronized (mPackages) {
17769            mSettings.writePackageRestrictionsLPr(userId);
17770            mDirtyUsers.remove(userId);
17771            if (mDirtyUsers.isEmpty()) {
17772                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17773            }
17774        }
17775    }
17776
17777    private void sendPackageChangedBroadcast(String packageName,
17778            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17779        if (DEBUG_INSTALL)
17780            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17781                    + componentNames);
17782        Bundle extras = new Bundle(4);
17783        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17784        String nameList[] = new String[componentNames.size()];
17785        componentNames.toArray(nameList);
17786        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17787        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17788        extras.putInt(Intent.EXTRA_UID, packageUid);
17789        // If this is not reporting a change of the overall package, then only send it
17790        // to registered receivers.  We don't want to launch a swath of apps for every
17791        // little component state change.
17792        final int flags = !componentNames.contains(packageName)
17793                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17794        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17795                new int[] {UserHandle.getUserId(packageUid)});
17796    }
17797
17798    @Override
17799    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17800        if (!sUserManager.exists(userId)) return;
17801        final int uid = Binder.getCallingUid();
17802        final int permission = mContext.checkCallingOrSelfPermission(
17803                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17804        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17805        enforceCrossUserPermission(uid, userId,
17806                true /* requireFullPermission */, true /* checkShell */, "stop package");
17807        // writer
17808        synchronized (mPackages) {
17809            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17810                    allowedByPermission, uid, userId)) {
17811                scheduleWritePackageRestrictionsLocked(userId);
17812            }
17813        }
17814    }
17815
17816    @Override
17817    public String getInstallerPackageName(String packageName) {
17818        // reader
17819        synchronized (mPackages) {
17820            return mSettings.getInstallerPackageNameLPr(packageName);
17821        }
17822    }
17823
17824    public boolean isOrphaned(String packageName) {
17825        // reader
17826        synchronized (mPackages) {
17827            return mSettings.isOrphaned(packageName);
17828        }
17829    }
17830
17831    @Override
17832    public int getApplicationEnabledSetting(String packageName, int userId) {
17833        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17834        int uid = Binder.getCallingUid();
17835        enforceCrossUserPermission(uid, userId,
17836                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17837        // reader
17838        synchronized (mPackages) {
17839            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17840        }
17841    }
17842
17843    @Override
17844    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17845        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17846        int uid = Binder.getCallingUid();
17847        enforceCrossUserPermission(uid, userId,
17848                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17849        // reader
17850        synchronized (mPackages) {
17851            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17852        }
17853    }
17854
17855    @Override
17856    public void enterSafeMode() {
17857        enforceSystemOrRoot("Only the system can request entering safe mode");
17858
17859        if (!mSystemReady) {
17860            mSafeMode = true;
17861        }
17862    }
17863
17864    @Override
17865    public void systemReady() {
17866        mSystemReady = true;
17867
17868        // Read the compatibilty setting when the system is ready.
17869        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17870                mContext.getContentResolver(),
17871                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17872        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17873        if (DEBUG_SETTINGS) {
17874            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17875        }
17876
17877        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17878
17879        synchronized (mPackages) {
17880            // Verify that all of the preferred activity components actually
17881            // exist.  It is possible for applications to be updated and at
17882            // that point remove a previously declared activity component that
17883            // had been set as a preferred activity.  We try to clean this up
17884            // the next time we encounter that preferred activity, but it is
17885            // possible for the user flow to never be able to return to that
17886            // situation so here we do a sanity check to make sure we haven't
17887            // left any junk around.
17888            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17889            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17890                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17891                removed.clear();
17892                for (PreferredActivity pa : pir.filterSet()) {
17893                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17894                        removed.add(pa);
17895                    }
17896                }
17897                if (removed.size() > 0) {
17898                    for (int r=0; r<removed.size(); r++) {
17899                        PreferredActivity pa = removed.get(r);
17900                        Slog.w(TAG, "Removing dangling preferred activity: "
17901                                + pa.mPref.mComponent);
17902                        pir.removeFilter(pa);
17903                    }
17904                    mSettings.writePackageRestrictionsLPr(
17905                            mSettings.mPreferredActivities.keyAt(i));
17906                }
17907            }
17908
17909            for (int userId : UserManagerService.getInstance().getUserIds()) {
17910                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17911                    grantPermissionsUserIds = ArrayUtils.appendInt(
17912                            grantPermissionsUserIds, userId);
17913                }
17914            }
17915        }
17916        sUserManager.systemReady();
17917
17918        // If we upgraded grant all default permissions before kicking off.
17919        for (int userId : grantPermissionsUserIds) {
17920            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17921        }
17922
17923        // Kick off any messages waiting for system ready
17924        if (mPostSystemReadyMessages != null) {
17925            for (Message msg : mPostSystemReadyMessages) {
17926                msg.sendToTarget();
17927            }
17928            mPostSystemReadyMessages = null;
17929        }
17930
17931        // Watch for external volumes that come and go over time
17932        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17933        storage.registerListener(mStorageListener);
17934
17935        mInstallerService.systemReady();
17936        mPackageDexOptimizer.systemReady();
17937
17938        MountServiceInternal mountServiceInternal = LocalServices.getService(
17939                MountServiceInternal.class);
17940        mountServiceInternal.addExternalStoragePolicy(
17941                new MountServiceInternal.ExternalStorageMountPolicy() {
17942            @Override
17943            public int getMountMode(int uid, String packageName) {
17944                if (Process.isIsolated(uid)) {
17945                    return Zygote.MOUNT_EXTERNAL_NONE;
17946                }
17947                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17948                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17949                }
17950                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17951                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17952                }
17953                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17954                    return Zygote.MOUNT_EXTERNAL_READ;
17955                }
17956                return Zygote.MOUNT_EXTERNAL_WRITE;
17957            }
17958
17959            @Override
17960            public boolean hasExternalStorage(int uid, String packageName) {
17961                return true;
17962            }
17963        });
17964
17965        // Now that we're mostly running, clean up stale users and apps
17966        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17967        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17968    }
17969
17970    @Override
17971    public boolean isSafeMode() {
17972        return mSafeMode;
17973    }
17974
17975    @Override
17976    public boolean hasSystemUidErrors() {
17977        return mHasSystemUidErrors;
17978    }
17979
17980    static String arrayToString(int[] array) {
17981        StringBuffer buf = new StringBuffer(128);
17982        buf.append('[');
17983        if (array != null) {
17984            for (int i=0; i<array.length; i++) {
17985                if (i > 0) buf.append(", ");
17986                buf.append(array[i]);
17987            }
17988        }
17989        buf.append(']');
17990        return buf.toString();
17991    }
17992
17993    static class DumpState {
17994        public static final int DUMP_LIBS = 1 << 0;
17995        public static final int DUMP_FEATURES = 1 << 1;
17996        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17997        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17998        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17999        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18000        public static final int DUMP_PERMISSIONS = 1 << 6;
18001        public static final int DUMP_PACKAGES = 1 << 7;
18002        public static final int DUMP_SHARED_USERS = 1 << 8;
18003        public static final int DUMP_MESSAGES = 1 << 9;
18004        public static final int DUMP_PROVIDERS = 1 << 10;
18005        public static final int DUMP_VERIFIERS = 1 << 11;
18006        public static final int DUMP_PREFERRED = 1 << 12;
18007        public static final int DUMP_PREFERRED_XML = 1 << 13;
18008        public static final int DUMP_KEYSETS = 1 << 14;
18009        public static final int DUMP_VERSION = 1 << 15;
18010        public static final int DUMP_INSTALLS = 1 << 16;
18011        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18012        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18013        public static final int DUMP_FROZEN = 1 << 19;
18014        public static final int DUMP_DEXOPT = 1 << 20;
18015
18016        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18017
18018        private int mTypes;
18019
18020        private int mOptions;
18021
18022        private boolean mTitlePrinted;
18023
18024        private SharedUserSetting mSharedUser;
18025
18026        public boolean isDumping(int type) {
18027            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18028                return true;
18029            }
18030
18031            return (mTypes & type) != 0;
18032        }
18033
18034        public void setDump(int type) {
18035            mTypes |= type;
18036        }
18037
18038        public boolean isOptionEnabled(int option) {
18039            return (mOptions & option) != 0;
18040        }
18041
18042        public void setOptionEnabled(int option) {
18043            mOptions |= option;
18044        }
18045
18046        public boolean onTitlePrinted() {
18047            final boolean printed = mTitlePrinted;
18048            mTitlePrinted = true;
18049            return printed;
18050        }
18051
18052        public boolean getTitlePrinted() {
18053            return mTitlePrinted;
18054        }
18055
18056        public void setTitlePrinted(boolean enabled) {
18057            mTitlePrinted = enabled;
18058        }
18059
18060        public SharedUserSetting getSharedUser() {
18061            return mSharedUser;
18062        }
18063
18064        public void setSharedUser(SharedUserSetting user) {
18065            mSharedUser = user;
18066        }
18067    }
18068
18069    @Override
18070    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18071            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18072        (new PackageManagerShellCommand(this)).exec(
18073                this, in, out, err, args, resultReceiver);
18074    }
18075
18076    @Override
18077    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18078        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18079                != PackageManager.PERMISSION_GRANTED) {
18080            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18081                    + Binder.getCallingPid()
18082                    + ", uid=" + Binder.getCallingUid()
18083                    + " without permission "
18084                    + android.Manifest.permission.DUMP);
18085            return;
18086        }
18087
18088        DumpState dumpState = new DumpState();
18089        boolean fullPreferred = false;
18090        boolean checkin = false;
18091
18092        String packageName = null;
18093        ArraySet<String> permissionNames = null;
18094
18095        int opti = 0;
18096        while (opti < args.length) {
18097            String opt = args[opti];
18098            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18099                break;
18100            }
18101            opti++;
18102
18103            if ("-a".equals(opt)) {
18104                // Right now we only know how to print all.
18105            } else if ("-h".equals(opt)) {
18106                pw.println("Package manager dump options:");
18107                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18108                pw.println("    --checkin: dump for a checkin");
18109                pw.println("    -f: print details of intent filters");
18110                pw.println("    -h: print this help");
18111                pw.println("  cmd may be one of:");
18112                pw.println("    l[ibraries]: list known shared libraries");
18113                pw.println("    f[eatures]: list device features");
18114                pw.println("    k[eysets]: print known keysets");
18115                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18116                pw.println("    perm[issions]: dump permissions");
18117                pw.println("    permission [name ...]: dump declaration and use of given permission");
18118                pw.println("    pref[erred]: print preferred package settings");
18119                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18120                pw.println("    prov[iders]: dump content providers");
18121                pw.println("    p[ackages]: dump installed packages");
18122                pw.println("    s[hared-users]: dump shared user IDs");
18123                pw.println("    m[essages]: print collected runtime messages");
18124                pw.println("    v[erifiers]: print package verifier info");
18125                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18126                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18127                pw.println("    version: print database version info");
18128                pw.println("    write: write current settings now");
18129                pw.println("    installs: details about install sessions");
18130                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18131                pw.println("    dexopt: dump dexopt state");
18132                pw.println("    <package.name>: info about given package");
18133                return;
18134            } else if ("--checkin".equals(opt)) {
18135                checkin = true;
18136            } else if ("-f".equals(opt)) {
18137                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18138            } else {
18139                pw.println("Unknown argument: " + opt + "; use -h for help");
18140            }
18141        }
18142
18143        // Is the caller requesting to dump a particular piece of data?
18144        if (opti < args.length) {
18145            String cmd = args[opti];
18146            opti++;
18147            // Is this a package name?
18148            if ("android".equals(cmd) || cmd.contains(".")) {
18149                packageName = cmd;
18150                // When dumping a single package, we always dump all of its
18151                // filter information since the amount of data will be reasonable.
18152                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18153            } else if ("check-permission".equals(cmd)) {
18154                if (opti >= args.length) {
18155                    pw.println("Error: check-permission missing permission argument");
18156                    return;
18157                }
18158                String perm = args[opti];
18159                opti++;
18160                if (opti >= args.length) {
18161                    pw.println("Error: check-permission missing package argument");
18162                    return;
18163                }
18164                String pkg = args[opti];
18165                opti++;
18166                int user = UserHandle.getUserId(Binder.getCallingUid());
18167                if (opti < args.length) {
18168                    try {
18169                        user = Integer.parseInt(args[opti]);
18170                    } catch (NumberFormatException e) {
18171                        pw.println("Error: check-permission user argument is not a number: "
18172                                + args[opti]);
18173                        return;
18174                    }
18175                }
18176                pw.println(checkPermission(perm, pkg, user));
18177                return;
18178            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18179                dumpState.setDump(DumpState.DUMP_LIBS);
18180            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18181                dumpState.setDump(DumpState.DUMP_FEATURES);
18182            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18183                if (opti >= args.length) {
18184                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18185                            | DumpState.DUMP_SERVICE_RESOLVERS
18186                            | DumpState.DUMP_RECEIVER_RESOLVERS
18187                            | DumpState.DUMP_CONTENT_RESOLVERS);
18188                } else {
18189                    while (opti < args.length) {
18190                        String name = args[opti];
18191                        if ("a".equals(name) || "activity".equals(name)) {
18192                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18193                        } else if ("s".equals(name) || "service".equals(name)) {
18194                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18195                        } else if ("r".equals(name) || "receiver".equals(name)) {
18196                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18197                        } else if ("c".equals(name) || "content".equals(name)) {
18198                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18199                        } else {
18200                            pw.println("Error: unknown resolver table type: " + name);
18201                            return;
18202                        }
18203                        opti++;
18204                    }
18205                }
18206            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18207                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18208            } else if ("permission".equals(cmd)) {
18209                if (opti >= args.length) {
18210                    pw.println("Error: permission requires permission name");
18211                    return;
18212                }
18213                permissionNames = new ArraySet<>();
18214                while (opti < args.length) {
18215                    permissionNames.add(args[opti]);
18216                    opti++;
18217                }
18218                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18219                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18220            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18221                dumpState.setDump(DumpState.DUMP_PREFERRED);
18222            } else if ("preferred-xml".equals(cmd)) {
18223                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18224                if (opti < args.length && "--full".equals(args[opti])) {
18225                    fullPreferred = true;
18226                    opti++;
18227                }
18228            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18229                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18230            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18231                dumpState.setDump(DumpState.DUMP_PACKAGES);
18232            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18233                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18234            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18235                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18236            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18237                dumpState.setDump(DumpState.DUMP_MESSAGES);
18238            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18239                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18240            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18241                    || "intent-filter-verifiers".equals(cmd)) {
18242                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18243            } else if ("version".equals(cmd)) {
18244                dumpState.setDump(DumpState.DUMP_VERSION);
18245            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18246                dumpState.setDump(DumpState.DUMP_KEYSETS);
18247            } else if ("installs".equals(cmd)) {
18248                dumpState.setDump(DumpState.DUMP_INSTALLS);
18249            } else if ("frozen".equals(cmd)) {
18250                dumpState.setDump(DumpState.DUMP_FROZEN);
18251            } else if ("dexopt".equals(cmd)) {
18252                dumpState.setDump(DumpState.DUMP_DEXOPT);
18253            } else if ("write".equals(cmd)) {
18254                synchronized (mPackages) {
18255                    mSettings.writeLPr();
18256                    pw.println("Settings written.");
18257                    return;
18258                }
18259            }
18260        }
18261
18262        if (checkin) {
18263            pw.println("vers,1");
18264        }
18265
18266        // reader
18267        synchronized (mPackages) {
18268            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18269                if (!checkin) {
18270                    if (dumpState.onTitlePrinted())
18271                        pw.println();
18272                    pw.println("Database versions:");
18273                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18274                }
18275            }
18276
18277            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18278                if (!checkin) {
18279                    if (dumpState.onTitlePrinted())
18280                        pw.println();
18281                    pw.println("Verifiers:");
18282                    pw.print("  Required: ");
18283                    pw.print(mRequiredVerifierPackage);
18284                    pw.print(" (uid=");
18285                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18286                            UserHandle.USER_SYSTEM));
18287                    pw.println(")");
18288                } else if (mRequiredVerifierPackage != null) {
18289                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18290                    pw.print(",");
18291                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18292                            UserHandle.USER_SYSTEM));
18293                }
18294            }
18295
18296            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18297                    packageName == null) {
18298                if (mIntentFilterVerifierComponent != null) {
18299                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18300                    if (!checkin) {
18301                        if (dumpState.onTitlePrinted())
18302                            pw.println();
18303                        pw.println("Intent Filter Verifier:");
18304                        pw.print("  Using: ");
18305                        pw.print(verifierPackageName);
18306                        pw.print(" (uid=");
18307                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18308                                UserHandle.USER_SYSTEM));
18309                        pw.println(")");
18310                    } else if (verifierPackageName != null) {
18311                        pw.print("ifv,"); pw.print(verifierPackageName);
18312                        pw.print(",");
18313                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18314                                UserHandle.USER_SYSTEM));
18315                    }
18316                } else {
18317                    pw.println();
18318                    pw.println("No Intent Filter Verifier available!");
18319                }
18320            }
18321
18322            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18323                boolean printedHeader = false;
18324                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18325                while (it.hasNext()) {
18326                    String name = it.next();
18327                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18328                    if (!checkin) {
18329                        if (!printedHeader) {
18330                            if (dumpState.onTitlePrinted())
18331                                pw.println();
18332                            pw.println("Libraries:");
18333                            printedHeader = true;
18334                        }
18335                        pw.print("  ");
18336                    } else {
18337                        pw.print("lib,");
18338                    }
18339                    pw.print(name);
18340                    if (!checkin) {
18341                        pw.print(" -> ");
18342                    }
18343                    if (ent.path != null) {
18344                        if (!checkin) {
18345                            pw.print("(jar) ");
18346                            pw.print(ent.path);
18347                        } else {
18348                            pw.print(",jar,");
18349                            pw.print(ent.path);
18350                        }
18351                    } else {
18352                        if (!checkin) {
18353                            pw.print("(apk) ");
18354                            pw.print(ent.apk);
18355                        } else {
18356                            pw.print(",apk,");
18357                            pw.print(ent.apk);
18358                        }
18359                    }
18360                    pw.println();
18361                }
18362            }
18363
18364            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18365                if (dumpState.onTitlePrinted())
18366                    pw.println();
18367                if (!checkin) {
18368                    pw.println("Features:");
18369                }
18370
18371                for (FeatureInfo feat : mAvailableFeatures.values()) {
18372                    if (checkin) {
18373                        pw.print("feat,");
18374                        pw.print(feat.name);
18375                        pw.print(",");
18376                        pw.println(feat.version);
18377                    } else {
18378                        pw.print("  ");
18379                        pw.print(feat.name);
18380                        if (feat.version > 0) {
18381                            pw.print(" version=");
18382                            pw.print(feat.version);
18383                        }
18384                        pw.println();
18385                    }
18386                }
18387            }
18388
18389            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18390                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18391                        : "Activity Resolver Table:", "  ", packageName,
18392                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18393                    dumpState.setTitlePrinted(true);
18394                }
18395            }
18396            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18397                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18398                        : "Receiver Resolver Table:", "  ", packageName,
18399                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18400                    dumpState.setTitlePrinted(true);
18401                }
18402            }
18403            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18404                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18405                        : "Service Resolver Table:", "  ", packageName,
18406                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18407                    dumpState.setTitlePrinted(true);
18408                }
18409            }
18410            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18411                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18412                        : "Provider Resolver Table:", "  ", packageName,
18413                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18414                    dumpState.setTitlePrinted(true);
18415                }
18416            }
18417
18418            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18419                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18420                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18421                    int user = mSettings.mPreferredActivities.keyAt(i);
18422                    if (pir.dump(pw,
18423                            dumpState.getTitlePrinted()
18424                                ? "\nPreferred Activities User " + user + ":"
18425                                : "Preferred Activities User " + user + ":", "  ",
18426                            packageName, true, false)) {
18427                        dumpState.setTitlePrinted(true);
18428                    }
18429                }
18430            }
18431
18432            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18433                pw.flush();
18434                FileOutputStream fout = new FileOutputStream(fd);
18435                BufferedOutputStream str = new BufferedOutputStream(fout);
18436                XmlSerializer serializer = new FastXmlSerializer();
18437                try {
18438                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18439                    serializer.startDocument(null, true);
18440                    serializer.setFeature(
18441                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18442                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18443                    serializer.endDocument();
18444                    serializer.flush();
18445                } catch (IllegalArgumentException e) {
18446                    pw.println("Failed writing: " + e);
18447                } catch (IllegalStateException e) {
18448                    pw.println("Failed writing: " + e);
18449                } catch (IOException e) {
18450                    pw.println("Failed writing: " + e);
18451                }
18452            }
18453
18454            if (!checkin
18455                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18456                    && packageName == null) {
18457                pw.println();
18458                int count = mSettings.mPackages.size();
18459                if (count == 0) {
18460                    pw.println("No applications!");
18461                    pw.println();
18462                } else {
18463                    final String prefix = "  ";
18464                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18465                    if (allPackageSettings.size() == 0) {
18466                        pw.println("No domain preferred apps!");
18467                        pw.println();
18468                    } else {
18469                        pw.println("App verification status:");
18470                        pw.println();
18471                        count = 0;
18472                        for (PackageSetting ps : allPackageSettings) {
18473                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18474                            if (ivi == null || ivi.getPackageName() == null) continue;
18475                            pw.println(prefix + "Package: " + ivi.getPackageName());
18476                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18477                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18478                            pw.println();
18479                            count++;
18480                        }
18481                        if (count == 0) {
18482                            pw.println(prefix + "No app verification established.");
18483                            pw.println();
18484                        }
18485                        for (int userId : sUserManager.getUserIds()) {
18486                            pw.println("App linkages for user " + userId + ":");
18487                            pw.println();
18488                            count = 0;
18489                            for (PackageSetting ps : allPackageSettings) {
18490                                final long status = ps.getDomainVerificationStatusForUser(userId);
18491                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18492                                    continue;
18493                                }
18494                                pw.println(prefix + "Package: " + ps.name);
18495                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18496                                String statusStr = IntentFilterVerificationInfo.
18497                                        getStatusStringFromValue(status);
18498                                pw.println(prefix + "Status:  " + statusStr);
18499                                pw.println();
18500                                count++;
18501                            }
18502                            if (count == 0) {
18503                                pw.println(prefix + "No configured app linkages.");
18504                                pw.println();
18505                            }
18506                        }
18507                    }
18508                }
18509            }
18510
18511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18512                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18513                if (packageName == null && permissionNames == null) {
18514                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18515                        if (iperm == 0) {
18516                            if (dumpState.onTitlePrinted())
18517                                pw.println();
18518                            pw.println("AppOp Permissions:");
18519                        }
18520                        pw.print("  AppOp Permission ");
18521                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18522                        pw.println(":");
18523                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18524                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18525                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18526                        }
18527                    }
18528                }
18529            }
18530
18531            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18532                boolean printedSomething = false;
18533                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18534                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18535                        continue;
18536                    }
18537                    if (!printedSomething) {
18538                        if (dumpState.onTitlePrinted())
18539                            pw.println();
18540                        pw.println("Registered ContentProviders:");
18541                        printedSomething = true;
18542                    }
18543                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18544                    pw.print("    "); pw.println(p.toString());
18545                }
18546                printedSomething = false;
18547                for (Map.Entry<String, PackageParser.Provider> entry :
18548                        mProvidersByAuthority.entrySet()) {
18549                    PackageParser.Provider p = entry.getValue();
18550                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18551                        continue;
18552                    }
18553                    if (!printedSomething) {
18554                        if (dumpState.onTitlePrinted())
18555                            pw.println();
18556                        pw.println("ContentProvider Authorities:");
18557                        printedSomething = true;
18558                    }
18559                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18560                    pw.print("    "); pw.println(p.toString());
18561                    if (p.info != null && p.info.applicationInfo != null) {
18562                        final String appInfo = p.info.applicationInfo.toString();
18563                        pw.print("      applicationInfo="); pw.println(appInfo);
18564                    }
18565                }
18566            }
18567
18568            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18569                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18570            }
18571
18572            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18573                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18574            }
18575
18576            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18577                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18578            }
18579
18580            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18581                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18582            }
18583
18584            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18585                // XXX should handle packageName != null by dumping only install data that
18586                // the given package is involved with.
18587                if (dumpState.onTitlePrinted()) pw.println();
18588                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18589            }
18590
18591            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18592                // XXX should handle packageName != null by dumping only install data that
18593                // the given package is involved with.
18594                if (dumpState.onTitlePrinted()) pw.println();
18595
18596                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18597                ipw.println();
18598                ipw.println("Frozen packages:");
18599                ipw.increaseIndent();
18600                if (mFrozenPackages.size() == 0) {
18601                    ipw.println("(none)");
18602                } else {
18603                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18604                        ipw.println(mFrozenPackages.valueAt(i));
18605                    }
18606                }
18607                ipw.decreaseIndent();
18608            }
18609
18610            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18611                if (dumpState.onTitlePrinted()) pw.println();
18612                dumpDexoptStateLPr(pw, packageName);
18613            }
18614
18615            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18616                if (dumpState.onTitlePrinted()) pw.println();
18617                mSettings.dumpReadMessagesLPr(pw, dumpState);
18618
18619                pw.println();
18620                pw.println("Package warning messages:");
18621                BufferedReader in = null;
18622                String line = null;
18623                try {
18624                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18625                    while ((line = in.readLine()) != null) {
18626                        if (line.contains("ignored: updated version")) continue;
18627                        pw.println(line);
18628                    }
18629                } catch (IOException ignored) {
18630                } finally {
18631                    IoUtils.closeQuietly(in);
18632                }
18633            }
18634
18635            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18636                BufferedReader in = null;
18637                String line = null;
18638                try {
18639                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18640                    while ((line = in.readLine()) != null) {
18641                        if (line.contains("ignored: updated version")) continue;
18642                        pw.print("msg,");
18643                        pw.println(line);
18644                    }
18645                } catch (IOException ignored) {
18646                } finally {
18647                    IoUtils.closeQuietly(in);
18648                }
18649            }
18650        }
18651    }
18652
18653    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18654        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18655        ipw.println();
18656        ipw.println("Dexopt state:");
18657        ipw.increaseIndent();
18658        Collection<PackageParser.Package> packages = null;
18659        if (packageName != null) {
18660            PackageParser.Package targetPackage = mPackages.get(packageName);
18661            if (targetPackage != null) {
18662                packages = Collections.singletonList(targetPackage);
18663            } else {
18664                ipw.println("Unable to find package: " + packageName);
18665                return;
18666            }
18667        } else {
18668            packages = mPackages.values();
18669        }
18670
18671        for (PackageParser.Package pkg : packages) {
18672            ipw.println("[" + pkg.packageName + "]");
18673            ipw.increaseIndent();
18674            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18675            ipw.decreaseIndent();
18676        }
18677    }
18678
18679    private String dumpDomainString(String packageName) {
18680        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18681                .getList();
18682        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18683
18684        ArraySet<String> result = new ArraySet<>();
18685        if (iviList.size() > 0) {
18686            for (IntentFilterVerificationInfo ivi : iviList) {
18687                for (String host : ivi.getDomains()) {
18688                    result.add(host);
18689                }
18690            }
18691        }
18692        if (filters != null && filters.size() > 0) {
18693            for (IntentFilter filter : filters) {
18694                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18695                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18696                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18697                    result.addAll(filter.getHostsList());
18698                }
18699            }
18700        }
18701
18702        StringBuilder sb = new StringBuilder(result.size() * 16);
18703        for (String domain : result) {
18704            if (sb.length() > 0) sb.append(" ");
18705            sb.append(domain);
18706        }
18707        return sb.toString();
18708    }
18709
18710    // ------- apps on sdcard specific code -------
18711    static final boolean DEBUG_SD_INSTALL = false;
18712
18713    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18714
18715    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18716
18717    private boolean mMediaMounted = false;
18718
18719    static String getEncryptKey() {
18720        try {
18721            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18722                    SD_ENCRYPTION_KEYSTORE_NAME);
18723            if (sdEncKey == null) {
18724                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18725                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18726                if (sdEncKey == null) {
18727                    Slog.e(TAG, "Failed to create encryption keys");
18728                    return null;
18729                }
18730            }
18731            return sdEncKey;
18732        } catch (NoSuchAlgorithmException nsae) {
18733            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18734            return null;
18735        } catch (IOException ioe) {
18736            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18737            return null;
18738        }
18739    }
18740
18741    /*
18742     * Update media status on PackageManager.
18743     */
18744    @Override
18745    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18746        int callingUid = Binder.getCallingUid();
18747        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18748            throw new SecurityException("Media status can only be updated by the system");
18749        }
18750        // reader; this apparently protects mMediaMounted, but should probably
18751        // be a different lock in that case.
18752        synchronized (mPackages) {
18753            Log.i(TAG, "Updating external media status from "
18754                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18755                    + (mediaStatus ? "mounted" : "unmounted"));
18756            if (DEBUG_SD_INSTALL)
18757                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18758                        + ", mMediaMounted=" + mMediaMounted);
18759            if (mediaStatus == mMediaMounted) {
18760                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18761                        : 0, -1);
18762                mHandler.sendMessage(msg);
18763                return;
18764            }
18765            mMediaMounted = mediaStatus;
18766        }
18767        // Queue up an async operation since the package installation may take a
18768        // little while.
18769        mHandler.post(new Runnable() {
18770            public void run() {
18771                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18772            }
18773        });
18774    }
18775
18776    /**
18777     * Called by MountService when the initial ASECs to scan are available.
18778     * Should block until all the ASEC containers are finished being scanned.
18779     */
18780    public void scanAvailableAsecs() {
18781        updateExternalMediaStatusInner(true, false, false);
18782    }
18783
18784    /*
18785     * Collect information of applications on external media, map them against
18786     * existing containers and update information based on current mount status.
18787     * Please note that we always have to report status if reportStatus has been
18788     * set to true especially when unloading packages.
18789     */
18790    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18791            boolean externalStorage) {
18792        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18793        int[] uidArr = EmptyArray.INT;
18794
18795        final String[] list = PackageHelper.getSecureContainerList();
18796        if (ArrayUtils.isEmpty(list)) {
18797            Log.i(TAG, "No secure containers found");
18798        } else {
18799            // Process list of secure containers and categorize them
18800            // as active or stale based on their package internal state.
18801
18802            // reader
18803            synchronized (mPackages) {
18804                for (String cid : list) {
18805                    // Leave stages untouched for now; installer service owns them
18806                    if (PackageInstallerService.isStageName(cid)) continue;
18807
18808                    if (DEBUG_SD_INSTALL)
18809                        Log.i(TAG, "Processing container " + cid);
18810                    String pkgName = getAsecPackageName(cid);
18811                    if (pkgName == null) {
18812                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18813                        continue;
18814                    }
18815                    if (DEBUG_SD_INSTALL)
18816                        Log.i(TAG, "Looking for pkg : " + pkgName);
18817
18818                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18819                    if (ps == null) {
18820                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18821                        continue;
18822                    }
18823
18824                    /*
18825                     * Skip packages that are not external if we're unmounting
18826                     * external storage.
18827                     */
18828                    if (externalStorage && !isMounted && !isExternal(ps)) {
18829                        continue;
18830                    }
18831
18832                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18833                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18834                    // The package status is changed only if the code path
18835                    // matches between settings and the container id.
18836                    if (ps.codePathString != null
18837                            && ps.codePathString.startsWith(args.getCodePath())) {
18838                        if (DEBUG_SD_INSTALL) {
18839                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18840                                    + " at code path: " + ps.codePathString);
18841                        }
18842
18843                        // We do have a valid package installed on sdcard
18844                        processCids.put(args, ps.codePathString);
18845                        final int uid = ps.appId;
18846                        if (uid != -1) {
18847                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18848                        }
18849                    } else {
18850                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18851                                + ps.codePathString);
18852                    }
18853                }
18854            }
18855
18856            Arrays.sort(uidArr);
18857        }
18858
18859        // Process packages with valid entries.
18860        if (isMounted) {
18861            if (DEBUG_SD_INSTALL)
18862                Log.i(TAG, "Loading packages");
18863            loadMediaPackages(processCids, uidArr, externalStorage);
18864            startCleaningPackages();
18865            mInstallerService.onSecureContainersAvailable();
18866        } else {
18867            if (DEBUG_SD_INSTALL)
18868                Log.i(TAG, "Unloading packages");
18869            unloadMediaPackages(processCids, uidArr, reportStatus);
18870        }
18871    }
18872
18873    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18874            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18875        final int size = infos.size();
18876        final String[] packageNames = new String[size];
18877        final int[] packageUids = new int[size];
18878        for (int i = 0; i < size; i++) {
18879            final ApplicationInfo info = infos.get(i);
18880            packageNames[i] = info.packageName;
18881            packageUids[i] = info.uid;
18882        }
18883        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18884                finishedReceiver);
18885    }
18886
18887    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18888            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18889        sendResourcesChangedBroadcast(mediaStatus, replacing,
18890                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18891    }
18892
18893    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18894            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18895        int size = pkgList.length;
18896        if (size > 0) {
18897            // Send broadcasts here
18898            Bundle extras = new Bundle();
18899            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18900            if (uidArr != null) {
18901                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18902            }
18903            if (replacing) {
18904                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18905            }
18906            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18907                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18908            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18909        }
18910    }
18911
18912   /*
18913     * Look at potentially valid container ids from processCids If package
18914     * information doesn't match the one on record or package scanning fails,
18915     * the cid is added to list of removeCids. We currently don't delete stale
18916     * containers.
18917     */
18918    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18919            boolean externalStorage) {
18920        ArrayList<String> pkgList = new ArrayList<String>();
18921        Set<AsecInstallArgs> keys = processCids.keySet();
18922
18923        for (AsecInstallArgs args : keys) {
18924            String codePath = processCids.get(args);
18925            if (DEBUG_SD_INSTALL)
18926                Log.i(TAG, "Loading container : " + args.cid);
18927            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18928            try {
18929                // Make sure there are no container errors first.
18930                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18931                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18932                            + " when installing from sdcard");
18933                    continue;
18934                }
18935                // Check code path here.
18936                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18937                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18938                            + " does not match one in settings " + codePath);
18939                    continue;
18940                }
18941                // Parse package
18942                int parseFlags = mDefParseFlags;
18943                if (args.isExternalAsec()) {
18944                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18945                }
18946                if (args.isFwdLocked()) {
18947                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18948                }
18949
18950                synchronized (mInstallLock) {
18951                    PackageParser.Package pkg = null;
18952                    try {
18953                        // Sadly we don't know the package name yet to freeze it
18954                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
18955                                SCAN_IGNORE_FROZEN, 0, null);
18956                    } catch (PackageManagerException e) {
18957                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18958                    }
18959                    // Scan the package
18960                    if (pkg != null) {
18961                        /*
18962                         * TODO why is the lock being held? doPostInstall is
18963                         * called in other places without the lock. This needs
18964                         * to be straightened out.
18965                         */
18966                        // writer
18967                        synchronized (mPackages) {
18968                            retCode = PackageManager.INSTALL_SUCCEEDED;
18969                            pkgList.add(pkg.packageName);
18970                            // Post process args
18971                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18972                                    pkg.applicationInfo.uid);
18973                        }
18974                    } else {
18975                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18976                    }
18977                }
18978
18979            } finally {
18980                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18981                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18982                }
18983            }
18984        }
18985        // writer
18986        synchronized (mPackages) {
18987            // If the platform SDK has changed since the last time we booted,
18988            // we need to re-grant app permission to catch any new ones that
18989            // appear. This is really a hack, and means that apps can in some
18990            // cases get permissions that the user didn't initially explicitly
18991            // allow... it would be nice to have some better way to handle
18992            // this situation.
18993            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18994                    : mSettings.getInternalVersion();
18995            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18996                    : StorageManager.UUID_PRIVATE_INTERNAL;
18997
18998            int updateFlags = UPDATE_PERMISSIONS_ALL;
18999            if (ver.sdkVersion != mSdkVersion) {
19000                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19001                        + mSdkVersion + "; regranting permissions for external");
19002                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19003            }
19004            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19005
19006            // Yay, everything is now upgraded
19007            ver.forceCurrent();
19008
19009            // can downgrade to reader
19010            // Persist settings
19011            mSettings.writeLPr();
19012        }
19013        // Send a broadcast to let everyone know we are done processing
19014        if (pkgList.size() > 0) {
19015            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19016        }
19017    }
19018
19019   /*
19020     * Utility method to unload a list of specified containers
19021     */
19022    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19023        // Just unmount all valid containers.
19024        for (AsecInstallArgs arg : cidArgs) {
19025            synchronized (mInstallLock) {
19026                arg.doPostDeleteLI(false);
19027           }
19028       }
19029   }
19030
19031    /*
19032     * Unload packages mounted on external media. This involves deleting package
19033     * data from internal structures, sending broadcasts about disabled packages,
19034     * gc'ing to free up references, unmounting all secure containers
19035     * corresponding to packages on external media, and posting a
19036     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19037     * that we always have to post this message if status has been requested no
19038     * matter what.
19039     */
19040    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19041            final boolean reportStatus) {
19042        if (DEBUG_SD_INSTALL)
19043            Log.i(TAG, "unloading media packages");
19044        ArrayList<String> pkgList = new ArrayList<String>();
19045        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19046        final Set<AsecInstallArgs> keys = processCids.keySet();
19047        for (AsecInstallArgs args : keys) {
19048            String pkgName = args.getPackageName();
19049            if (DEBUG_SD_INSTALL)
19050                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19051            // Delete package internally
19052            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19053            synchronized (mInstallLock) {
19054                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19055                final boolean res;
19056                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19057                        "unloadMediaPackages")) {
19058                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19059                            null);
19060                }
19061                if (res) {
19062                    pkgList.add(pkgName);
19063                } else {
19064                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19065                    failedList.add(args);
19066                }
19067            }
19068        }
19069
19070        // reader
19071        synchronized (mPackages) {
19072            // We didn't update the settings after removing each package;
19073            // write them now for all packages.
19074            mSettings.writeLPr();
19075        }
19076
19077        // We have to absolutely send UPDATED_MEDIA_STATUS only
19078        // after confirming that all the receivers processed the ordered
19079        // broadcast when packages get disabled, force a gc to clean things up.
19080        // and unload all the containers.
19081        if (pkgList.size() > 0) {
19082            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19083                    new IIntentReceiver.Stub() {
19084                public void performReceive(Intent intent, int resultCode, String data,
19085                        Bundle extras, boolean ordered, boolean sticky,
19086                        int sendingUser) throws RemoteException {
19087                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19088                            reportStatus ? 1 : 0, 1, keys);
19089                    mHandler.sendMessage(msg);
19090                }
19091            });
19092        } else {
19093            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19094                    keys);
19095            mHandler.sendMessage(msg);
19096        }
19097    }
19098
19099    private void loadPrivatePackages(final VolumeInfo vol) {
19100        mHandler.post(new Runnable() {
19101            @Override
19102            public void run() {
19103                loadPrivatePackagesInner(vol);
19104            }
19105        });
19106    }
19107
19108    private void loadPrivatePackagesInner(VolumeInfo vol) {
19109        final String volumeUuid = vol.fsUuid;
19110        if (TextUtils.isEmpty(volumeUuid)) {
19111            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19112            return;
19113        }
19114
19115        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19116        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19117        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19118
19119        final VersionInfo ver;
19120        final List<PackageSetting> packages;
19121        synchronized (mPackages) {
19122            ver = mSettings.findOrCreateVersion(volumeUuid);
19123            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19124        }
19125
19126        for (PackageSetting ps : packages) {
19127            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19128            synchronized (mInstallLock) {
19129                final PackageParser.Package pkg;
19130                try {
19131                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19132                    loaded.add(pkg.applicationInfo);
19133
19134                } catch (PackageManagerException e) {
19135                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19136                }
19137
19138                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19139                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19140                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19141                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19142                }
19143            }
19144        }
19145
19146        // Reconcile app data for all started/unlocked users
19147        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19148        final UserManager um = mContext.getSystemService(UserManager.class);
19149        UserManagerInternal umInternal = getUserManagerInternal();
19150        for (UserInfo user : um.getUsers()) {
19151            final int flags;
19152            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19153                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19154            } else if (umInternal.isUserRunning(user.id)) {
19155                flags = StorageManager.FLAG_STORAGE_DE;
19156            } else {
19157                continue;
19158            }
19159
19160            try {
19161                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19162                synchronized (mInstallLock) {
19163                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19164                }
19165            } catch (IllegalStateException e) {
19166                // Device was probably ejected, and we'll process that event momentarily
19167                Slog.w(TAG, "Failed to prepare storage: " + e);
19168            }
19169        }
19170
19171        synchronized (mPackages) {
19172            int updateFlags = UPDATE_PERMISSIONS_ALL;
19173            if (ver.sdkVersion != mSdkVersion) {
19174                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19175                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19176                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19177            }
19178            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19179
19180            // Yay, everything is now upgraded
19181            ver.forceCurrent();
19182
19183            mSettings.writeLPr();
19184        }
19185
19186        for (PackageFreezer freezer : freezers) {
19187            freezer.close();
19188        }
19189
19190        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19191        sendResourcesChangedBroadcast(true, false, loaded, null);
19192    }
19193
19194    private void unloadPrivatePackages(final VolumeInfo vol) {
19195        mHandler.post(new Runnable() {
19196            @Override
19197            public void run() {
19198                unloadPrivatePackagesInner(vol);
19199            }
19200        });
19201    }
19202
19203    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19204        final String volumeUuid = vol.fsUuid;
19205        if (TextUtils.isEmpty(volumeUuid)) {
19206            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19207            return;
19208        }
19209
19210        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19211        synchronized (mInstallLock) {
19212        synchronized (mPackages) {
19213            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19214            for (PackageSetting ps : packages) {
19215                if (ps.pkg == null) continue;
19216
19217                final ApplicationInfo info = ps.pkg.applicationInfo;
19218                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19219                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19220
19221                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19222                        "unloadPrivatePackagesInner")) {
19223                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19224                            false, null)) {
19225                        unloaded.add(info);
19226                    } else {
19227                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19228                    }
19229                }
19230
19231                // Try very hard to release any references to this package
19232                // so we don't risk the system server being killed due to
19233                // open FDs
19234                AttributeCache.instance().removePackage(ps.name);
19235            }
19236
19237            mSettings.writeLPr();
19238        }
19239        }
19240
19241        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19242        sendResourcesChangedBroadcast(false, false, unloaded, null);
19243
19244        // Try very hard to release any references to this path so we don't risk
19245        // the system server being killed due to open FDs
19246        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19247
19248        for (int i = 0; i < 3; i++) {
19249            System.gc();
19250            System.runFinalization();
19251        }
19252    }
19253
19254    /**
19255     * Prepare storage areas for given user on all mounted devices.
19256     */
19257    void prepareUserData(int userId, int userSerial, int flags) {
19258        synchronized (mInstallLock) {
19259            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19260            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19261                final String volumeUuid = vol.getFsUuid();
19262                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19263            }
19264        }
19265    }
19266
19267    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19268            boolean allowRecover) {
19269        // Prepare storage and verify that serial numbers are consistent; if
19270        // there's a mismatch we need to destroy to avoid leaking data
19271        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19272        try {
19273            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19274
19275            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19276                UserManagerService.enforceSerialNumber(
19277                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19278            }
19279            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19280                UserManagerService.enforceSerialNumber(
19281                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19282            }
19283
19284            synchronized (mInstallLock) {
19285                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19286            }
19287        } catch (Exception e) {
19288            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19289                    + " because we failed to prepare: " + e);
19290            destroyUserDataLI(volumeUuid, userId,
19291                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19292
19293            if (allowRecover) {
19294                // Try one last time; if we fail again we're really in trouble
19295                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19296            }
19297        }
19298    }
19299
19300    /**
19301     * Destroy storage areas for given user on all mounted devices.
19302     */
19303    void destroyUserData(int userId, int flags) {
19304        synchronized (mInstallLock) {
19305            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19306            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19307                final String volumeUuid = vol.getFsUuid();
19308                destroyUserDataLI(volumeUuid, userId, flags);
19309            }
19310        }
19311    }
19312
19313    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19314        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19315        try {
19316            // Clean up app data, profile data, and media data
19317            mInstaller.destroyUserData(volumeUuid, userId, flags);
19318
19319            // Clean up system data
19320            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19321                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19322                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19323                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19324                }
19325                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19326                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19327                }
19328            }
19329
19330            // Data with special labels is now gone, so finish the job
19331            storage.destroyUserStorage(volumeUuid, userId, flags);
19332
19333        } catch (Exception e) {
19334            logCriticalInfo(Log.WARN,
19335                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19336        }
19337    }
19338
19339    /**
19340     * Examine all users present on given mounted volume, and destroy data
19341     * belonging to users that are no longer valid, or whose user ID has been
19342     * recycled.
19343     */
19344    private void reconcileUsers(String volumeUuid) {
19345        final List<File> files = new ArrayList<>();
19346        Collections.addAll(files, FileUtils
19347                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19348        Collections.addAll(files, FileUtils
19349                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19350        for (File file : files) {
19351            if (!file.isDirectory()) continue;
19352
19353            final int userId;
19354            final UserInfo info;
19355            try {
19356                userId = Integer.parseInt(file.getName());
19357                info = sUserManager.getUserInfo(userId);
19358            } catch (NumberFormatException e) {
19359                Slog.w(TAG, "Invalid user directory " + file);
19360                continue;
19361            }
19362
19363            boolean destroyUser = false;
19364            if (info == null) {
19365                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19366                        + " because no matching user was found");
19367                destroyUser = true;
19368            } else if (!mOnlyCore) {
19369                try {
19370                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19371                } catch (IOException e) {
19372                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19373                            + " because we failed to enforce serial number: " + e);
19374                    destroyUser = true;
19375                }
19376            }
19377
19378            if (destroyUser) {
19379                synchronized (mInstallLock) {
19380                    destroyUserDataLI(volumeUuid, userId,
19381                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19382                }
19383            }
19384        }
19385    }
19386
19387    private void assertPackageKnown(String volumeUuid, String packageName)
19388            throws PackageManagerException {
19389        synchronized (mPackages) {
19390            final PackageSetting ps = mSettings.mPackages.get(packageName);
19391            if (ps == null) {
19392                throw new PackageManagerException("Package " + packageName + " is unknown");
19393            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19394                throw new PackageManagerException(
19395                        "Package " + packageName + " found on unknown volume " + volumeUuid
19396                                + "; expected volume " + ps.volumeUuid);
19397            }
19398        }
19399    }
19400
19401    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19402            throws PackageManagerException {
19403        synchronized (mPackages) {
19404            final PackageSetting ps = mSettings.mPackages.get(packageName);
19405            if (ps == null) {
19406                throw new PackageManagerException("Package " + packageName + " is unknown");
19407            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19408                throw new PackageManagerException(
19409                        "Package " + packageName + " found on unknown volume " + volumeUuid
19410                                + "; expected volume " + ps.volumeUuid);
19411            } else if (!ps.getInstalled(userId)) {
19412                throw new PackageManagerException(
19413                        "Package " + packageName + " not installed for user " + userId);
19414            }
19415        }
19416    }
19417
19418    /**
19419     * Examine all apps present on given mounted volume, and destroy apps that
19420     * aren't expected, either due to uninstallation or reinstallation on
19421     * another volume.
19422     */
19423    private void reconcileApps(String volumeUuid) {
19424        final File[] files = FileUtils
19425                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19426        for (File file : files) {
19427            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19428                    && !PackageInstallerService.isStageName(file.getName());
19429            if (!isPackage) {
19430                // Ignore entries which are not packages
19431                continue;
19432            }
19433
19434            try {
19435                final PackageLite pkg = PackageParser.parsePackageLite(file,
19436                        PackageParser.PARSE_MUST_BE_APK);
19437                assertPackageKnown(volumeUuid, pkg.packageName);
19438
19439            } catch (PackageParserException | PackageManagerException e) {
19440                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19441                synchronized (mInstallLock) {
19442                    removeCodePathLI(file);
19443                }
19444            }
19445        }
19446    }
19447
19448    /**
19449     * Reconcile all app data for the given user.
19450     * <p>
19451     * Verifies that directories exist and that ownership and labeling is
19452     * correct for all installed apps on all mounted volumes.
19453     */
19454    void reconcileAppsData(int userId, int flags) {
19455        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19456        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19457            final String volumeUuid = vol.getFsUuid();
19458            synchronized (mInstallLock) {
19459                reconcileAppsDataLI(volumeUuid, userId, flags);
19460            }
19461        }
19462    }
19463
19464    /**
19465     * Reconcile all app data on given mounted volume.
19466     * <p>
19467     * Destroys app data that isn't expected, either due to uninstallation or
19468     * reinstallation on another volume.
19469     * <p>
19470     * Verifies that directories exist and that ownership and labeling is
19471     * correct for all installed apps.
19472     */
19473    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19474        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19475                + Integer.toHexString(flags));
19476
19477        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19478        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19479
19480        boolean restoreconNeeded = false;
19481
19482        // First look for stale data that doesn't belong, and check if things
19483        // have changed since we did our last restorecon
19484        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19485            if (StorageManager.isFileEncryptedNativeOrEmulated()
19486                    && !StorageManager.isUserKeyUnlocked(userId)) {
19487                throw new RuntimeException(
19488                        "Yikes, someone asked us to reconcile CE storage while " + userId
19489                                + " was still locked; this would have caused massive data loss!");
19490            }
19491
19492            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19493
19494            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19495            for (File file : files) {
19496                final String packageName = file.getName();
19497                try {
19498                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19499                } catch (PackageManagerException e) {
19500                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19501                    try {
19502                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19503                                StorageManager.FLAG_STORAGE_CE, 0);
19504                    } catch (InstallerException e2) {
19505                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19506                    }
19507                }
19508            }
19509        }
19510        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19511            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19512
19513            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19514            for (File file : files) {
19515                final String packageName = file.getName();
19516                try {
19517                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19518                } catch (PackageManagerException e) {
19519                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19520                    try {
19521                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19522                                StorageManager.FLAG_STORAGE_DE, 0);
19523                    } catch (InstallerException e2) {
19524                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19525                    }
19526                }
19527            }
19528        }
19529
19530        // Ensure that data directories are ready to roll for all packages
19531        // installed for this volume and user
19532        final List<PackageSetting> packages;
19533        synchronized (mPackages) {
19534            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19535        }
19536        int preparedCount = 0;
19537        for (PackageSetting ps : packages) {
19538            final String packageName = ps.name;
19539            if (ps.pkg == null) {
19540                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19541                // TODO: might be due to legacy ASEC apps; we should circle back
19542                // and reconcile again once they're scanned
19543                continue;
19544            }
19545
19546            if (ps.getInstalled(userId)) {
19547                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19548
19549                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19550                    // We may have just shuffled around app data directories, so
19551                    // prepare them one more time
19552                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19553                }
19554
19555                preparedCount++;
19556            }
19557        }
19558
19559        if (restoreconNeeded) {
19560            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19561                SELinuxMMAC.setRestoreconDone(ceDir);
19562            }
19563            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19564                SELinuxMMAC.setRestoreconDone(deDir);
19565            }
19566        }
19567
19568        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19569                + " packages; restoreconNeeded was " + restoreconNeeded);
19570    }
19571
19572    /**
19573     * Prepare app data for the given app just after it was installed or
19574     * upgraded. This method carefully only touches users that it's installed
19575     * for, and it forces a restorecon to handle any seinfo changes.
19576     * <p>
19577     * Verifies that directories exist and that ownership and labeling is
19578     * correct for all installed apps. If there is an ownership mismatch, it
19579     * will try recovering system apps by wiping data; third-party app data is
19580     * left intact.
19581     * <p>
19582     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19583     */
19584    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19585        final PackageSetting ps;
19586        synchronized (mPackages) {
19587            ps = mSettings.mPackages.get(pkg.packageName);
19588            mSettings.writeKernelMappingLPr(ps);
19589        }
19590
19591        final UserManager um = mContext.getSystemService(UserManager.class);
19592        UserManagerInternal umInternal = getUserManagerInternal();
19593        for (UserInfo user : um.getUsers()) {
19594            final int flags;
19595            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19596                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19597            } else if (umInternal.isUserRunning(user.id)) {
19598                flags = StorageManager.FLAG_STORAGE_DE;
19599            } else {
19600                continue;
19601            }
19602
19603            if (ps.getInstalled(user.id)) {
19604                // Whenever an app changes, force a restorecon of its data
19605                // TODO: when user data is locked, mark that we're still dirty
19606                prepareAppDataLIF(pkg, user.id, flags, true);
19607            }
19608        }
19609    }
19610
19611    /**
19612     * Prepare app data for the given app.
19613     * <p>
19614     * Verifies that directories exist and that ownership and labeling is
19615     * correct for all installed apps. If there is an ownership mismatch, this
19616     * will try recovering system apps by wiping data; third-party app data is
19617     * left intact.
19618     */
19619    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19620            boolean restoreconNeeded) {
19621        if (pkg == null) {
19622            Slog.wtf(TAG, "Package was null!", new Throwable());
19623            return;
19624        }
19625        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19626        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19627        for (int i = 0; i < childCount; i++) {
19628            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19629        }
19630    }
19631
19632    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19633            boolean restoreconNeeded) {
19634        if (DEBUG_APP_DATA) {
19635            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19636                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19637        }
19638
19639        final String volumeUuid = pkg.volumeUuid;
19640        final String packageName = pkg.packageName;
19641        final ApplicationInfo app = pkg.applicationInfo;
19642        final int appId = UserHandle.getAppId(app.uid);
19643
19644        Preconditions.checkNotNull(app.seinfo);
19645
19646        try {
19647            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19648                    appId, app.seinfo, app.targetSdkVersion);
19649        } catch (InstallerException e) {
19650            if (app.isSystemApp()) {
19651                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19652                        + ", but trying to recover: " + e);
19653                destroyAppDataLeafLIF(pkg, userId, flags);
19654                try {
19655                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19656                            appId, app.seinfo, app.targetSdkVersion);
19657                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19658                } catch (InstallerException e2) {
19659                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19660                }
19661            } else {
19662                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19663            }
19664        }
19665
19666        if (restoreconNeeded) {
19667            try {
19668                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19669                        app.seinfo);
19670            } catch (InstallerException e) {
19671                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19672            }
19673        }
19674
19675        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19676            try {
19677                // CE storage is unlocked right now, so read out the inode and
19678                // remember for use later when it's locked
19679                // TODO: mark this structure as dirty so we persist it!
19680                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19681                        StorageManager.FLAG_STORAGE_CE);
19682                synchronized (mPackages) {
19683                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19684                    if (ps != null) {
19685                        ps.setCeDataInode(ceDataInode, userId);
19686                    }
19687                }
19688            } catch (InstallerException e) {
19689                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19690            }
19691        }
19692
19693        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19694    }
19695
19696    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19697        if (pkg == null) {
19698            Slog.wtf(TAG, "Package was null!", new Throwable());
19699            return;
19700        }
19701        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19702        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19703        for (int i = 0; i < childCount; i++) {
19704            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19705        }
19706    }
19707
19708    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19709        final String volumeUuid = pkg.volumeUuid;
19710        final String packageName = pkg.packageName;
19711        final ApplicationInfo app = pkg.applicationInfo;
19712
19713        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19714            // Create a native library symlink only if we have native libraries
19715            // and if the native libraries are 32 bit libraries. We do not provide
19716            // this symlink for 64 bit libraries.
19717            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19718                final String nativeLibPath = app.nativeLibraryDir;
19719                try {
19720                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19721                            nativeLibPath, userId);
19722                } catch (InstallerException e) {
19723                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19724                }
19725            }
19726        }
19727    }
19728
19729    /**
19730     * For system apps on non-FBE devices, this method migrates any existing
19731     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19732     * requested by the app.
19733     */
19734    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19735        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19736                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19737            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19738                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19739            try {
19740                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19741                        storageTarget);
19742            } catch (InstallerException e) {
19743                logCriticalInfo(Log.WARN,
19744                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19745            }
19746            return true;
19747        } else {
19748            return false;
19749        }
19750    }
19751
19752    public PackageFreezer freezePackage(String packageName, String killReason) {
19753        return new PackageFreezer(packageName, killReason);
19754    }
19755
19756    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19757            String killReason) {
19758        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19759            return new PackageFreezer();
19760        } else {
19761            return freezePackage(packageName, killReason);
19762        }
19763    }
19764
19765    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19766            String killReason) {
19767        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19768            return new PackageFreezer();
19769        } else {
19770            return freezePackage(packageName, killReason);
19771        }
19772    }
19773
19774    /**
19775     * Class that freezes and kills the given package upon creation, and
19776     * unfreezes it upon closing. This is typically used when doing surgery on
19777     * app code/data to prevent the app from running while you're working.
19778     */
19779    private class PackageFreezer implements AutoCloseable {
19780        private final String mPackageName;
19781        private final PackageFreezer[] mChildren;
19782
19783        private final boolean mWeFroze;
19784
19785        private final AtomicBoolean mClosed = new AtomicBoolean();
19786        private final CloseGuard mCloseGuard = CloseGuard.get();
19787
19788        /**
19789         * Create and return a stub freezer that doesn't actually do anything,
19790         * typically used when someone requested
19791         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19792         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19793         */
19794        public PackageFreezer() {
19795            mPackageName = null;
19796            mChildren = null;
19797            mWeFroze = false;
19798            mCloseGuard.open("close");
19799        }
19800
19801        public PackageFreezer(String packageName, String killReason) {
19802            synchronized (mPackages) {
19803                mPackageName = packageName;
19804                mWeFroze = mFrozenPackages.add(mPackageName);
19805
19806                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19807                if (ps != null) {
19808                    killApplication(ps.name, ps.appId, killReason);
19809                }
19810
19811                final PackageParser.Package p = mPackages.get(packageName);
19812                if (p != null && p.childPackages != null) {
19813                    final int N = p.childPackages.size();
19814                    mChildren = new PackageFreezer[N];
19815                    for (int i = 0; i < N; i++) {
19816                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19817                                killReason);
19818                    }
19819                } else {
19820                    mChildren = null;
19821                }
19822            }
19823            mCloseGuard.open("close");
19824        }
19825
19826        @Override
19827        protected void finalize() throws Throwable {
19828            try {
19829                mCloseGuard.warnIfOpen();
19830                close();
19831            } finally {
19832                super.finalize();
19833            }
19834        }
19835
19836        @Override
19837        public void close() {
19838            mCloseGuard.close();
19839            if (mClosed.compareAndSet(false, true)) {
19840                synchronized (mPackages) {
19841                    if (mWeFroze) {
19842                        mFrozenPackages.remove(mPackageName);
19843                    }
19844
19845                    if (mChildren != null) {
19846                        for (PackageFreezer freezer : mChildren) {
19847                            freezer.close();
19848                        }
19849                    }
19850                }
19851            }
19852        }
19853    }
19854
19855    /**
19856     * Verify that given package is currently frozen.
19857     */
19858    private void checkPackageFrozen(String packageName) {
19859        synchronized (mPackages) {
19860            if (!mFrozenPackages.contains(packageName)) {
19861                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19862            }
19863        }
19864    }
19865
19866    @Override
19867    public int movePackage(final String packageName, final String volumeUuid) {
19868        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19869
19870        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19871        final int moveId = mNextMoveId.getAndIncrement();
19872        mHandler.post(new Runnable() {
19873            @Override
19874            public void run() {
19875                try {
19876                    movePackageInternal(packageName, volumeUuid, moveId, user);
19877                } catch (PackageManagerException e) {
19878                    Slog.w(TAG, "Failed to move " + packageName, e);
19879                    mMoveCallbacks.notifyStatusChanged(moveId,
19880                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19881                }
19882            }
19883        });
19884        return moveId;
19885    }
19886
19887    private void movePackageInternal(final String packageName, final String volumeUuid,
19888            final int moveId, UserHandle user) throws PackageManagerException {
19889        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19890        final PackageManager pm = mContext.getPackageManager();
19891
19892        final boolean currentAsec;
19893        final String currentVolumeUuid;
19894        final File codeFile;
19895        final String installerPackageName;
19896        final String packageAbiOverride;
19897        final int appId;
19898        final String seinfo;
19899        final String label;
19900        final int targetSdkVersion;
19901        final PackageFreezer freezer;
19902        final int[] installedUserIds;
19903
19904        // reader
19905        synchronized (mPackages) {
19906            final PackageParser.Package pkg = mPackages.get(packageName);
19907            final PackageSetting ps = mSettings.mPackages.get(packageName);
19908            if (pkg == null || ps == null) {
19909                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19910            }
19911
19912            if (pkg.applicationInfo.isSystemApp()) {
19913                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19914                        "Cannot move system application");
19915            }
19916
19917            if (pkg.applicationInfo.isExternalAsec()) {
19918                currentAsec = true;
19919                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
19920            } else if (pkg.applicationInfo.isForwardLocked()) {
19921                currentAsec = true;
19922                currentVolumeUuid = "forward_locked";
19923            } else {
19924                currentAsec = false;
19925                currentVolumeUuid = ps.volumeUuid;
19926
19927                final File probe = new File(pkg.codePath);
19928                final File probeOat = new File(probe, "oat");
19929                if (!probe.isDirectory() || !probeOat.isDirectory()) {
19930                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19931                            "Move only supported for modern cluster style installs");
19932                }
19933            }
19934
19935            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
19936                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19937                        "Package already moved to " + volumeUuid);
19938            }
19939            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
19940                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
19941                        "Device admin cannot be moved");
19942            }
19943
19944            if (mFrozenPackages.contains(packageName)) {
19945                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
19946                        "Failed to move already frozen package");
19947            }
19948
19949            codeFile = new File(pkg.codePath);
19950            installerPackageName = ps.installerPackageName;
19951            packageAbiOverride = ps.cpuAbiOverrideString;
19952            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19953            seinfo = pkg.applicationInfo.seinfo;
19954            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
19955            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
19956            freezer = new PackageFreezer(packageName, "movePackageInternal");
19957            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
19958        }
19959
19960        final Bundle extras = new Bundle();
19961        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19962        extras.putString(Intent.EXTRA_TITLE, label);
19963        mMoveCallbacks.notifyCreated(moveId, extras);
19964
19965        int installFlags;
19966        final boolean moveCompleteApp;
19967        final File measurePath;
19968
19969        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19970            installFlags = INSTALL_INTERNAL;
19971            moveCompleteApp = !currentAsec;
19972            measurePath = Environment.getDataAppDirectory(volumeUuid);
19973        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19974            installFlags = INSTALL_EXTERNAL;
19975            moveCompleteApp = false;
19976            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19977        } else {
19978            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19979            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19980                    || !volume.isMountedWritable()) {
19981                freezer.close();
19982                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19983                        "Move location not mounted private volume");
19984            }
19985
19986            Preconditions.checkState(!currentAsec);
19987
19988            installFlags = INSTALL_INTERNAL;
19989            moveCompleteApp = true;
19990            measurePath = Environment.getDataAppDirectory(volumeUuid);
19991        }
19992
19993        final PackageStats stats = new PackageStats(null, -1);
19994        synchronized (mInstaller) {
19995            for (int userId : installedUserIds) {
19996                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
19997                    freezer.close();
19998                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19999                            "Failed to measure package size");
20000                }
20001            }
20002        }
20003
20004        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20005                + stats.dataSize);
20006
20007        final long startFreeBytes = measurePath.getFreeSpace();
20008        final long sizeBytes;
20009        if (moveCompleteApp) {
20010            sizeBytes = stats.codeSize + stats.dataSize;
20011        } else {
20012            sizeBytes = stats.codeSize;
20013        }
20014
20015        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20016            freezer.close();
20017            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20018                    "Not enough free space to move");
20019        }
20020
20021        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20022
20023        final CountDownLatch installedLatch = new CountDownLatch(1);
20024        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20025            @Override
20026            public void onUserActionRequired(Intent intent) throws RemoteException {
20027                throw new IllegalStateException();
20028            }
20029
20030            @Override
20031            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20032                    Bundle extras) throws RemoteException {
20033                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20034                        + PackageManager.installStatusToString(returnCode, msg));
20035
20036                installedLatch.countDown();
20037                freezer.close();
20038
20039                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20040                switch (status) {
20041                    case PackageInstaller.STATUS_SUCCESS:
20042                        mMoveCallbacks.notifyStatusChanged(moveId,
20043                                PackageManager.MOVE_SUCCEEDED);
20044                        break;
20045                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20046                        mMoveCallbacks.notifyStatusChanged(moveId,
20047                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20048                        break;
20049                    default:
20050                        mMoveCallbacks.notifyStatusChanged(moveId,
20051                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20052                        break;
20053                }
20054            }
20055        };
20056
20057        final MoveInfo move;
20058        if (moveCompleteApp) {
20059            // Kick off a thread to report progress estimates
20060            new Thread() {
20061                @Override
20062                public void run() {
20063                    while (true) {
20064                        try {
20065                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20066                                break;
20067                            }
20068                        } catch (InterruptedException ignored) {
20069                        }
20070
20071                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20072                        final int progress = 10 + (int) MathUtils.constrain(
20073                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20074                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20075                    }
20076                }
20077            }.start();
20078
20079            final String dataAppName = codeFile.getName();
20080            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20081                    dataAppName, appId, seinfo, targetSdkVersion);
20082        } else {
20083            move = null;
20084        }
20085
20086        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20087
20088        final Message msg = mHandler.obtainMessage(INIT_COPY);
20089        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20090        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20091                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20092                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20093        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20094        msg.obj = params;
20095
20096        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20097                System.identityHashCode(msg.obj));
20098        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20099                System.identityHashCode(msg.obj));
20100
20101        mHandler.sendMessage(msg);
20102    }
20103
20104    @Override
20105    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20106        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20107
20108        final int realMoveId = mNextMoveId.getAndIncrement();
20109        final Bundle extras = new Bundle();
20110        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20111        mMoveCallbacks.notifyCreated(realMoveId, extras);
20112
20113        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20114            @Override
20115            public void onCreated(int moveId, Bundle extras) {
20116                // Ignored
20117            }
20118
20119            @Override
20120            public void onStatusChanged(int moveId, int status, long estMillis) {
20121                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20122            }
20123        };
20124
20125        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20126        storage.setPrimaryStorageUuid(volumeUuid, callback);
20127        return realMoveId;
20128    }
20129
20130    @Override
20131    public int getMoveStatus(int moveId) {
20132        mContext.enforceCallingOrSelfPermission(
20133                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20134        return mMoveCallbacks.mLastStatus.get(moveId);
20135    }
20136
20137    @Override
20138    public void registerMoveCallback(IPackageMoveObserver callback) {
20139        mContext.enforceCallingOrSelfPermission(
20140                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20141        mMoveCallbacks.register(callback);
20142    }
20143
20144    @Override
20145    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20146        mContext.enforceCallingOrSelfPermission(
20147                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20148        mMoveCallbacks.unregister(callback);
20149    }
20150
20151    @Override
20152    public boolean setInstallLocation(int loc) {
20153        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20154                null);
20155        if (getInstallLocation() == loc) {
20156            return true;
20157        }
20158        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20159                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20160            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20161                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20162            return true;
20163        }
20164        return false;
20165   }
20166
20167    @Override
20168    public int getInstallLocation() {
20169        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20170                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20171                PackageHelper.APP_INSTALL_AUTO);
20172    }
20173
20174    /** Called by UserManagerService */
20175    void cleanUpUser(UserManagerService userManager, int userHandle) {
20176        synchronized (mPackages) {
20177            mDirtyUsers.remove(userHandle);
20178            mUserNeedsBadging.delete(userHandle);
20179            mSettings.removeUserLPw(userHandle);
20180            mPendingBroadcasts.remove(userHandle);
20181            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20182            removeUnusedPackagesLPw(userManager, userHandle);
20183        }
20184    }
20185
20186    /**
20187     * We're removing userHandle and would like to remove any downloaded packages
20188     * that are no longer in use by any other user.
20189     * @param userHandle the user being removed
20190     */
20191    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20192        final boolean DEBUG_CLEAN_APKS = false;
20193        int [] users = userManager.getUserIds();
20194        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20195        while (psit.hasNext()) {
20196            PackageSetting ps = psit.next();
20197            if (ps.pkg == null) {
20198                continue;
20199            }
20200            final String packageName = ps.pkg.packageName;
20201            // Skip over if system app
20202            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20203                continue;
20204            }
20205            if (DEBUG_CLEAN_APKS) {
20206                Slog.i(TAG, "Checking package " + packageName);
20207            }
20208            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20209            if (keep) {
20210                if (DEBUG_CLEAN_APKS) {
20211                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20212                }
20213            } else {
20214                for (int i = 0; i < users.length; i++) {
20215                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20216                        keep = true;
20217                        if (DEBUG_CLEAN_APKS) {
20218                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20219                                    + users[i]);
20220                        }
20221                        break;
20222                    }
20223                }
20224            }
20225            if (!keep) {
20226                if (DEBUG_CLEAN_APKS) {
20227                    Slog.i(TAG, "  Removing package " + packageName);
20228                }
20229                mHandler.post(new Runnable() {
20230                    public void run() {
20231                        deletePackageX(packageName, userHandle, 0);
20232                    } //end run
20233                });
20234            }
20235        }
20236    }
20237
20238    /** Called by UserManagerService */
20239    void createNewUser(int userId) {
20240        synchronized (mInstallLock) {
20241            mSettings.createNewUserLI(this, mInstaller, userId);
20242        }
20243        synchronized (mPackages) {
20244            scheduleWritePackageRestrictionsLocked(userId);
20245            scheduleWritePackageListLocked(userId);
20246            applyFactoryDefaultBrowserLPw(userId);
20247            primeDomainVerificationsLPw(userId);
20248        }
20249    }
20250
20251    void onBeforeUserStartUninitialized(final int userId) {
20252        synchronized (mPackages) {
20253            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20254                return;
20255            }
20256        }
20257        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20258        // If permission review for legacy apps is required, we represent
20259        // dagerous permissions for such apps as always granted runtime
20260        // permissions to keep per user flag state whether review is needed.
20261        // Hence, if a new user is added we have to propagate dangerous
20262        // permission grants for these legacy apps.
20263        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20264            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20265                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20266        }
20267    }
20268
20269    @Override
20270    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20271        mContext.enforceCallingOrSelfPermission(
20272                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20273                "Only package verification agents can read the verifier device identity");
20274
20275        synchronized (mPackages) {
20276            return mSettings.getVerifierDeviceIdentityLPw();
20277        }
20278    }
20279
20280    @Override
20281    public void setPermissionEnforced(String permission, boolean enforced) {
20282        // TODO: Now that we no longer change GID for storage, this should to away.
20283        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20284                "setPermissionEnforced");
20285        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20286            synchronized (mPackages) {
20287                if (mSettings.mReadExternalStorageEnforced == null
20288                        || mSettings.mReadExternalStorageEnforced != enforced) {
20289                    mSettings.mReadExternalStorageEnforced = enforced;
20290                    mSettings.writeLPr();
20291                }
20292            }
20293            // kill any non-foreground processes so we restart them and
20294            // grant/revoke the GID.
20295            final IActivityManager am = ActivityManagerNative.getDefault();
20296            if (am != null) {
20297                final long token = Binder.clearCallingIdentity();
20298                try {
20299                    am.killProcessesBelowForeground("setPermissionEnforcement");
20300                } catch (RemoteException e) {
20301                } finally {
20302                    Binder.restoreCallingIdentity(token);
20303                }
20304            }
20305        } else {
20306            throw new IllegalArgumentException("No selective enforcement for " + permission);
20307        }
20308    }
20309
20310    @Override
20311    @Deprecated
20312    public boolean isPermissionEnforced(String permission) {
20313        return true;
20314    }
20315
20316    @Override
20317    public boolean isStorageLow() {
20318        final long token = Binder.clearCallingIdentity();
20319        try {
20320            final DeviceStorageMonitorInternal
20321                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20322            if (dsm != null) {
20323                return dsm.isMemoryLow();
20324            } else {
20325                return false;
20326            }
20327        } finally {
20328            Binder.restoreCallingIdentity(token);
20329        }
20330    }
20331
20332    @Override
20333    public IPackageInstaller getPackageInstaller() {
20334        return mInstallerService;
20335    }
20336
20337    private boolean userNeedsBadging(int userId) {
20338        int index = mUserNeedsBadging.indexOfKey(userId);
20339        if (index < 0) {
20340            final UserInfo userInfo;
20341            final long token = Binder.clearCallingIdentity();
20342            try {
20343                userInfo = sUserManager.getUserInfo(userId);
20344            } finally {
20345                Binder.restoreCallingIdentity(token);
20346            }
20347            final boolean b;
20348            if (userInfo != null && userInfo.isManagedProfile()) {
20349                b = true;
20350            } else {
20351                b = false;
20352            }
20353            mUserNeedsBadging.put(userId, b);
20354            return b;
20355        }
20356        return mUserNeedsBadging.valueAt(index);
20357    }
20358
20359    @Override
20360    public KeySet getKeySetByAlias(String packageName, String alias) {
20361        if (packageName == null || alias == null) {
20362            return null;
20363        }
20364        synchronized(mPackages) {
20365            final PackageParser.Package pkg = mPackages.get(packageName);
20366            if (pkg == null) {
20367                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20368                throw new IllegalArgumentException("Unknown package: " + packageName);
20369            }
20370            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20371            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20372        }
20373    }
20374
20375    @Override
20376    public KeySet getSigningKeySet(String packageName) {
20377        if (packageName == null) {
20378            return null;
20379        }
20380        synchronized(mPackages) {
20381            final PackageParser.Package pkg = mPackages.get(packageName);
20382            if (pkg == null) {
20383                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20384                throw new IllegalArgumentException("Unknown package: " + packageName);
20385            }
20386            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20387                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20388                throw new SecurityException("May not access signing KeySet of other apps.");
20389            }
20390            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20391            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20392        }
20393    }
20394
20395    @Override
20396    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20397        if (packageName == null || ks == null) {
20398            return false;
20399        }
20400        synchronized(mPackages) {
20401            final PackageParser.Package pkg = mPackages.get(packageName);
20402            if (pkg == null) {
20403                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20404                throw new IllegalArgumentException("Unknown package: " + packageName);
20405            }
20406            IBinder ksh = ks.getToken();
20407            if (ksh instanceof KeySetHandle) {
20408                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20409                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20410            }
20411            return false;
20412        }
20413    }
20414
20415    @Override
20416    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20417        if (packageName == null || ks == null) {
20418            return false;
20419        }
20420        synchronized(mPackages) {
20421            final PackageParser.Package pkg = mPackages.get(packageName);
20422            if (pkg == null) {
20423                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20424                throw new IllegalArgumentException("Unknown package: " + packageName);
20425            }
20426            IBinder ksh = ks.getToken();
20427            if (ksh instanceof KeySetHandle) {
20428                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20429                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20430            }
20431            return false;
20432        }
20433    }
20434
20435    private void deletePackageIfUnusedLPr(final String packageName) {
20436        PackageSetting ps = mSettings.mPackages.get(packageName);
20437        if (ps == null) {
20438            return;
20439        }
20440        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20441            // TODO Implement atomic delete if package is unused
20442            // It is currently possible that the package will be deleted even if it is installed
20443            // after this method returns.
20444            mHandler.post(new Runnable() {
20445                public void run() {
20446                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20447                }
20448            });
20449        }
20450    }
20451
20452    /**
20453     * Check and throw if the given before/after packages would be considered a
20454     * downgrade.
20455     */
20456    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20457            throws PackageManagerException {
20458        if (after.versionCode < before.mVersionCode) {
20459            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20460                    "Update version code " + after.versionCode + " is older than current "
20461                    + before.mVersionCode);
20462        } else if (after.versionCode == before.mVersionCode) {
20463            if (after.baseRevisionCode < before.baseRevisionCode) {
20464                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20465                        "Update base revision code " + after.baseRevisionCode
20466                        + " is older than current " + before.baseRevisionCode);
20467            }
20468
20469            if (!ArrayUtils.isEmpty(after.splitNames)) {
20470                for (int i = 0; i < after.splitNames.length; i++) {
20471                    final String splitName = after.splitNames[i];
20472                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20473                    if (j != -1) {
20474                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20475                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20476                                    "Update split " + splitName + " revision code "
20477                                    + after.splitRevisionCodes[i] + " is older than current "
20478                                    + before.splitRevisionCodes[j]);
20479                        }
20480                    }
20481                }
20482            }
20483        }
20484    }
20485
20486    private static class MoveCallbacks extends Handler {
20487        private static final int MSG_CREATED = 1;
20488        private static final int MSG_STATUS_CHANGED = 2;
20489
20490        private final RemoteCallbackList<IPackageMoveObserver>
20491                mCallbacks = new RemoteCallbackList<>();
20492
20493        private final SparseIntArray mLastStatus = new SparseIntArray();
20494
20495        public MoveCallbacks(Looper looper) {
20496            super(looper);
20497        }
20498
20499        public void register(IPackageMoveObserver callback) {
20500            mCallbacks.register(callback);
20501        }
20502
20503        public void unregister(IPackageMoveObserver callback) {
20504            mCallbacks.unregister(callback);
20505        }
20506
20507        @Override
20508        public void handleMessage(Message msg) {
20509            final SomeArgs args = (SomeArgs) msg.obj;
20510            final int n = mCallbacks.beginBroadcast();
20511            for (int i = 0; i < n; i++) {
20512                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20513                try {
20514                    invokeCallback(callback, msg.what, args);
20515                } catch (RemoteException ignored) {
20516                }
20517            }
20518            mCallbacks.finishBroadcast();
20519            args.recycle();
20520        }
20521
20522        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20523                throws RemoteException {
20524            switch (what) {
20525                case MSG_CREATED: {
20526                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20527                    break;
20528                }
20529                case MSG_STATUS_CHANGED: {
20530                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20531                    break;
20532                }
20533            }
20534        }
20535
20536        private void notifyCreated(int moveId, Bundle extras) {
20537            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20538
20539            final SomeArgs args = SomeArgs.obtain();
20540            args.argi1 = moveId;
20541            args.arg2 = extras;
20542            obtainMessage(MSG_CREATED, args).sendToTarget();
20543        }
20544
20545        private void notifyStatusChanged(int moveId, int status) {
20546            notifyStatusChanged(moveId, status, -1);
20547        }
20548
20549        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20550            Slog.v(TAG, "Move " + moveId + " status " + status);
20551
20552            final SomeArgs args = SomeArgs.obtain();
20553            args.argi1 = moveId;
20554            args.argi2 = status;
20555            args.arg3 = estMillis;
20556            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20557
20558            synchronized (mLastStatus) {
20559                mLastStatus.put(moveId, status);
20560            }
20561        }
20562    }
20563
20564    private final static class OnPermissionChangeListeners extends Handler {
20565        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20566
20567        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20568                new RemoteCallbackList<>();
20569
20570        public OnPermissionChangeListeners(Looper looper) {
20571            super(looper);
20572        }
20573
20574        @Override
20575        public void handleMessage(Message msg) {
20576            switch (msg.what) {
20577                case MSG_ON_PERMISSIONS_CHANGED: {
20578                    final int uid = msg.arg1;
20579                    handleOnPermissionsChanged(uid);
20580                } break;
20581            }
20582        }
20583
20584        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20585            mPermissionListeners.register(listener);
20586
20587        }
20588
20589        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20590            mPermissionListeners.unregister(listener);
20591        }
20592
20593        public void onPermissionsChanged(int uid) {
20594            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20595                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20596            }
20597        }
20598
20599        private void handleOnPermissionsChanged(int uid) {
20600            final int count = mPermissionListeners.beginBroadcast();
20601            try {
20602                for (int i = 0; i < count; i++) {
20603                    IOnPermissionsChangeListener callback = mPermissionListeners
20604                            .getBroadcastItem(i);
20605                    try {
20606                        callback.onPermissionsChanged(uid);
20607                    } catch (RemoteException e) {
20608                        Log.e(TAG, "Permission listener is dead", e);
20609                    }
20610                }
20611            } finally {
20612                mPermissionListeners.finishBroadcast();
20613            }
20614        }
20615    }
20616
20617    private class PackageManagerInternalImpl extends PackageManagerInternal {
20618        @Override
20619        public void setLocationPackagesProvider(PackagesProvider provider) {
20620            synchronized (mPackages) {
20621                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20622            }
20623        }
20624
20625        @Override
20626        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20627            synchronized (mPackages) {
20628                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20629            }
20630        }
20631
20632        @Override
20633        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20634            synchronized (mPackages) {
20635                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20636            }
20637        }
20638
20639        @Override
20640        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20641            synchronized (mPackages) {
20642                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20643            }
20644        }
20645
20646        @Override
20647        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20648            synchronized (mPackages) {
20649                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20650            }
20651        }
20652
20653        @Override
20654        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20655            synchronized (mPackages) {
20656                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20657            }
20658        }
20659
20660        @Override
20661        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20662            synchronized (mPackages) {
20663                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20664                        packageName, userId);
20665            }
20666        }
20667
20668        @Override
20669        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20670            synchronized (mPackages) {
20671                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20672                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20673                        packageName, userId);
20674            }
20675        }
20676
20677        @Override
20678        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20679            synchronized (mPackages) {
20680                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20681                        packageName, userId);
20682            }
20683        }
20684
20685        @Override
20686        public void setKeepUninstalledPackages(final List<String> packageList) {
20687            Preconditions.checkNotNull(packageList);
20688            List<String> removedFromList = null;
20689            synchronized (mPackages) {
20690                if (mKeepUninstalledPackages != null) {
20691                    final int packagesCount = mKeepUninstalledPackages.size();
20692                    for (int i = 0; i < packagesCount; i++) {
20693                        String oldPackage = mKeepUninstalledPackages.get(i);
20694                        if (packageList != null && packageList.contains(oldPackage)) {
20695                            continue;
20696                        }
20697                        if (removedFromList == null) {
20698                            removedFromList = new ArrayList<>();
20699                        }
20700                        removedFromList.add(oldPackage);
20701                    }
20702                }
20703                mKeepUninstalledPackages = new ArrayList<>(packageList);
20704                if (removedFromList != null) {
20705                    final int removedCount = removedFromList.size();
20706                    for (int i = 0; i < removedCount; i++) {
20707                        deletePackageIfUnusedLPr(removedFromList.get(i));
20708                    }
20709                }
20710            }
20711        }
20712
20713        @Override
20714        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20715            synchronized (mPackages) {
20716                // If we do not support permission review, done.
20717                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20718                    return false;
20719                }
20720
20721                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20722                if (packageSetting == null) {
20723                    return false;
20724                }
20725
20726                // Permission review applies only to apps not supporting the new permission model.
20727                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20728                    return false;
20729                }
20730
20731                // Legacy apps have the permission and get user consent on launch.
20732                PermissionsState permissionsState = packageSetting.getPermissionsState();
20733                return permissionsState.isPermissionReviewRequired(userId);
20734            }
20735        }
20736
20737        @Override
20738        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20739            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20740        }
20741
20742        @Override
20743        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20744                int userId) {
20745            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20746        }
20747    }
20748
20749    @Override
20750    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20751        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20752        synchronized (mPackages) {
20753            final long identity = Binder.clearCallingIdentity();
20754            try {
20755                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20756                        packageNames, userId);
20757            } finally {
20758                Binder.restoreCallingIdentity(identity);
20759            }
20760        }
20761    }
20762
20763    private static void enforceSystemOrPhoneCaller(String tag) {
20764        int callingUid = Binder.getCallingUid();
20765        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20766            throw new SecurityException(
20767                    "Cannot call " + tag + " from UID " + callingUid);
20768        }
20769    }
20770
20771    boolean isHistoricalPackageUsageAvailable() {
20772        return mPackageUsage.isHistoricalPackageUsageAvailable();
20773    }
20774
20775    /**
20776     * Return a <b>copy</b> of the collection of packages known to the package manager.
20777     * @return A copy of the values of mPackages.
20778     */
20779    Collection<PackageParser.Package> getPackages() {
20780        synchronized (mPackages) {
20781            return new ArrayList<>(mPackages.values());
20782        }
20783    }
20784
20785    /**
20786     * Logs process start information (including base APK hash) to the security log.
20787     * @hide
20788     */
20789    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20790            String apkFile, int pid) {
20791        if (!SecurityLog.isLoggingEnabled()) {
20792            return;
20793        }
20794        Bundle data = new Bundle();
20795        data.putLong("startTimestamp", System.currentTimeMillis());
20796        data.putString("processName", processName);
20797        data.putInt("uid", uid);
20798        data.putString("seinfo", seinfo);
20799        data.putString("apkFile", apkFile);
20800        data.putInt("pid", pid);
20801        Message msg = mProcessLoggingHandler.obtainMessage(
20802                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20803        msg.setData(data);
20804        mProcessLoggingHandler.sendMessage(msg);
20805    }
20806}
20807