PackageManagerService.java revision 78f16950c62c68ccc6a5547f7388afd9b1c77fde
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.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
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 = Build.IS_DEBUGGABLE;
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 = !Build.IS_DEBUGGABLE;
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    final ProtectedPackages mProtectedPackages = new ProtectedPackages();
626
627    boolean mRestoredSettings;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741            new DefaultPermissionGrantPolicy(this);
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @Nullable String mSetupWizardPackage;
1124    final @NonNull String mServicesSystemSharedLibraryPackageName;
1125    final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127    private final PackageUsage mPackageUsage = new PackageUsage();
1128
1129    private class PackageUsage {
1130        private static final int WRITE_INTERVAL
1131            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1132
1133        private final Object mFileLock = new Object();
1134        private final AtomicLong mLastWritten = new AtomicLong(0);
1135        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1136
1137        private boolean mIsHistoricalPackageUsageAvailable = true;
1138
1139        boolean isHistoricalPackageUsageAvailable() {
1140            return mIsHistoricalPackageUsageAvailable;
1141        }
1142
1143        void write(boolean force) {
1144            if (force) {
1145                writeInternal();
1146                return;
1147            }
1148            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1149                && !DEBUG_DEXOPT) {
1150                return;
1151            }
1152            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1153                new Thread("PackageUsage_DiskWriter") {
1154                    @Override
1155                    public void run() {
1156                        try {
1157                            writeInternal();
1158                        } finally {
1159                            mBackgroundWriteRunning.set(false);
1160                        }
1161                    }
1162                }.start();
1163            }
1164        }
1165
1166        private void writeInternal() {
1167            synchronized (mPackages) {
1168                synchronized (mFileLock) {
1169                    AtomicFile file = getFile();
1170                    FileOutputStream f = null;
1171                    try {
1172                        f = file.startWrite();
1173                        BufferedOutputStream out = new BufferedOutputStream(f);
1174                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1175                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1176                        StringBuilder sb = new StringBuilder();
1177
1178                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1179                        sb.append('\n');
1180                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1181
1182                        for (PackageParser.Package pkg : mPackages.values()) {
1183                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1184                                continue;
1185                            }
1186                            sb.setLength(0);
1187                            sb.append(pkg.packageName);
1188                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1189                                sb.append(' ');
1190                                sb.append(usageTimeInMillis);
1191                            }
1192                            sb.append('\n');
1193                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1194                        }
1195                        out.flush();
1196                        file.finishWrite(f);
1197                    } catch (IOException e) {
1198                        if (f != null) {
1199                            file.failWrite(f);
1200                        }
1201                        Log.e(TAG, "Failed to write package usage times", e);
1202                    }
1203                }
1204            }
1205            mLastWritten.set(SystemClock.elapsedRealtime());
1206        }
1207
1208        void readLP() {
1209            synchronized (mFileLock) {
1210                AtomicFile file = getFile();
1211                BufferedInputStream in = null;
1212                try {
1213                    in = new BufferedInputStream(file.openRead());
1214                    StringBuffer sb = new StringBuffer();
1215
1216                    String firstLine = readLine(in, sb);
1217                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1218                        readVersion1LP(in, sb);
1219                    } else {
1220                        readVersion0LP(in, sb, firstLine);
1221                    }
1222                } catch (FileNotFoundException expected) {
1223                    mIsHistoricalPackageUsageAvailable = false;
1224                } catch (IOException e) {
1225                    Log.w(TAG, "Failed to read package usage times", e);
1226                } finally {
1227                    IoUtils.closeQuietly(in);
1228                }
1229            }
1230            mLastWritten.set(SystemClock.elapsedRealtime());
1231        }
1232
1233        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1234                throws IOException {
1235            // Initial version of the file had no version number and stored one
1236            // package-timestamp pair per line.
1237            // Note that the first line has already been read from the InputStream.
1238            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1239                String[] tokens = line.split(" ");
1240                if (tokens.length != 2) {
1241                    throw new IOException("Failed to parse " + line +
1242                            " as package-timestamp pair.");
1243                }
1244
1245                String packageName = tokens[0];
1246                PackageParser.Package pkg = mPackages.get(packageName);
1247                if (pkg == null) {
1248                    continue;
1249                }
1250
1251                long timestamp = parseAsLong(tokens[1]);
1252                for (int reason = 0;
1253                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1254                        reason++) {
1255                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1256                }
1257            }
1258        }
1259
1260        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1261            // Version 1 of the file started with the corresponding version
1262            // number and then stored a package name and eight timestamps per line.
1263            String line;
1264            while ((line = readLine(in, sb)) != null) {
1265                String[] tokens = line.split(" ");
1266                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1267                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1268                }
1269
1270                String packageName = tokens[0];
1271                PackageParser.Package pkg = mPackages.get(packageName);
1272                if (pkg == null) {
1273                    continue;
1274                }
1275
1276                for (int reason = 0;
1277                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1278                        reason++) {
1279                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1280                }
1281            }
1282        }
1283
1284        private long parseAsLong(String token) throws IOException {
1285            try {
1286                return Long.parseLong(token);
1287            } catch (NumberFormatException e) {
1288                throw new IOException("Failed to parse " + token + " as a long.", e);
1289            }
1290        }
1291
1292        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1293            return readToken(in, sb, '\n');
1294        }
1295
1296        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1297                throws IOException {
1298            sb.setLength(0);
1299            while (true) {
1300                int ch = in.read();
1301                if (ch == -1) {
1302                    if (sb.length() == 0) {
1303                        return null;
1304                    }
1305                    throw new IOException("Unexpected EOF");
1306                }
1307                if (ch == endOfToken) {
1308                    return sb.toString();
1309                }
1310                sb.append((char)ch);
1311            }
1312        }
1313
1314        private AtomicFile getFile() {
1315            File dataDir = Environment.getDataDirectory();
1316            File systemDir = new File(dataDir, "system");
1317            File fname = new File(systemDir, "package-usage.list");
1318            return new AtomicFile(fname);
1319        }
1320
1321        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1322        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1323    }
1324
1325    class PackageHandler extends Handler {
1326        private boolean mBound = false;
1327        final ArrayList<HandlerParams> mPendingInstalls =
1328            new ArrayList<HandlerParams>();
1329
1330        private boolean connectToService() {
1331            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1332                    " DefaultContainerService");
1333            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1334            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1335            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1336                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1337                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1338                mBound = true;
1339                return true;
1340            }
1341            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1342            return false;
1343        }
1344
1345        private void disconnectService() {
1346            mContainerService = null;
1347            mBound = false;
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1349            mContext.unbindService(mDefContainerConn);
1350            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1351        }
1352
1353        PackageHandler(Looper looper) {
1354            super(looper);
1355        }
1356
1357        public void handleMessage(Message msg) {
1358            try {
1359                doHandleMessage(msg);
1360            } finally {
1361                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1362            }
1363        }
1364
1365        void doHandleMessage(Message msg) {
1366            switch (msg.what) {
1367                case INIT_COPY: {
1368                    HandlerParams params = (HandlerParams) msg.obj;
1369                    int idx = mPendingInstalls.size();
1370                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1371                    // If a bind was already initiated we dont really
1372                    // need to do anything. The pending install
1373                    // will be processed later on.
1374                    if (!mBound) {
1375                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1376                                System.identityHashCode(mHandler));
1377                        // If this is the only one pending we might
1378                        // have to bind to the service again.
1379                        if (!connectToService()) {
1380                            Slog.e(TAG, "Failed to bind to media container service");
1381                            params.serviceError();
1382                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1383                                    System.identityHashCode(mHandler));
1384                            if (params.traceMethod != null) {
1385                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1386                                        params.traceCookie);
1387                            }
1388                            return;
1389                        } else {
1390                            // Once we bind to the service, the first
1391                            // pending request will be processed.
1392                            mPendingInstalls.add(idx, params);
1393                        }
1394                    } else {
1395                        mPendingInstalls.add(idx, params);
1396                        // Already bound to the service. Just make
1397                        // sure we trigger off processing the first request.
1398                        if (idx == 0) {
1399                            mHandler.sendEmptyMessage(MCS_BOUND);
1400                        }
1401                    }
1402                    break;
1403                }
1404                case MCS_BOUND: {
1405                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1406                    if (msg.obj != null) {
1407                        mContainerService = (IMediaContainerService) msg.obj;
1408                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1409                                System.identityHashCode(mHandler));
1410                    }
1411                    if (mContainerService == null) {
1412                        if (!mBound) {
1413                            // Something seriously wrong since we are not bound and we are not
1414                            // waiting for connection. Bail out.
1415                            Slog.e(TAG, "Cannot bind to media container service");
1416                            for (HandlerParams params : mPendingInstalls) {
1417                                // Indicate service bind error
1418                                params.serviceError();
1419                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1420                                        System.identityHashCode(params));
1421                                if (params.traceMethod != null) {
1422                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1423                                            params.traceMethod, params.traceCookie);
1424                                }
1425                                return;
1426                            }
1427                            mPendingInstalls.clear();
1428                        } else {
1429                            Slog.w(TAG, "Waiting to connect to media container service");
1430                        }
1431                    } else if (mPendingInstalls.size() > 0) {
1432                        HandlerParams params = mPendingInstalls.get(0);
1433                        if (params != null) {
1434                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1435                                    System.identityHashCode(params));
1436                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1437                            if (params.startCopy()) {
1438                                // We are done...  look for more work or to
1439                                // go idle.
1440                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1441                                        "Checking for more work or unbind...");
1442                                // Delete pending install
1443                                if (mPendingInstalls.size() > 0) {
1444                                    mPendingInstalls.remove(0);
1445                                }
1446                                if (mPendingInstalls.size() == 0) {
1447                                    if (mBound) {
1448                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1449                                                "Posting delayed MCS_UNBIND");
1450                                        removeMessages(MCS_UNBIND);
1451                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1452                                        // Unbind after a little delay, to avoid
1453                                        // continual thrashing.
1454                                        sendMessageDelayed(ubmsg, 10000);
1455                                    }
1456                                } else {
1457                                    // There are more pending requests in queue.
1458                                    // Just post MCS_BOUND message to trigger processing
1459                                    // of next pending install.
1460                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1461                                            "Posting MCS_BOUND for next work");
1462                                    mHandler.sendEmptyMessage(MCS_BOUND);
1463                                }
1464                            }
1465                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1466                        }
1467                    } else {
1468                        // Should never happen ideally.
1469                        Slog.w(TAG, "Empty queue");
1470                    }
1471                    break;
1472                }
1473                case MCS_RECONNECT: {
1474                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1475                    if (mPendingInstalls.size() > 0) {
1476                        if (mBound) {
1477                            disconnectService();
1478                        }
1479                        if (!connectToService()) {
1480                            Slog.e(TAG, "Failed to bind to media container service");
1481                            for (HandlerParams params : mPendingInstalls) {
1482                                // Indicate service bind error
1483                                params.serviceError();
1484                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485                                        System.identityHashCode(params));
1486                            }
1487                            mPendingInstalls.clear();
1488                        }
1489                    }
1490                    break;
1491                }
1492                case MCS_UNBIND: {
1493                    // If there is no actual work left, then time to unbind.
1494                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1495
1496                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1497                        if (mBound) {
1498                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1499
1500                            disconnectService();
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        // There are more pending requests in queue.
1504                        // Just post MCS_BOUND message to trigger processing
1505                        // of next pending install.
1506                        mHandler.sendEmptyMessage(MCS_BOUND);
1507                    }
1508
1509                    break;
1510                }
1511                case MCS_GIVE_UP: {
1512                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1513                    HandlerParams params = mPendingInstalls.remove(0);
1514                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1515                            System.identityHashCode(params));
1516                    break;
1517                }
1518                case SEND_PENDING_BROADCAST: {
1519                    String packages[];
1520                    ArrayList<String> components[];
1521                    int size = 0;
1522                    int uids[];
1523                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1524                    synchronized (mPackages) {
1525                        if (mPendingBroadcasts == null) {
1526                            return;
1527                        }
1528                        size = mPendingBroadcasts.size();
1529                        if (size <= 0) {
1530                            // Nothing to be done. Just return
1531                            return;
1532                        }
1533                        packages = new String[size];
1534                        components = new ArrayList[size];
1535                        uids = new int[size];
1536                        int i = 0;  // filling out the above arrays
1537
1538                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1539                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1540                            Iterator<Map.Entry<String, ArrayList<String>>> it
1541                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1542                                            .entrySet().iterator();
1543                            while (it.hasNext() && i < size) {
1544                                Map.Entry<String, ArrayList<String>> ent = it.next();
1545                                packages[i] = ent.getKey();
1546                                components[i] = ent.getValue();
1547                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1548                                uids[i] = (ps != null)
1549                                        ? UserHandle.getUid(packageUserId, ps.appId)
1550                                        : -1;
1551                                i++;
1552                            }
1553                        }
1554                        size = i;
1555                        mPendingBroadcasts.clear();
1556                    }
1557                    // Send broadcasts
1558                    for (int i = 0; i < size; i++) {
1559                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1560                    }
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562                    break;
1563                }
1564                case START_CLEANING_PACKAGE: {
1565                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1566                    final String packageName = (String)msg.obj;
1567                    final int userId = msg.arg1;
1568                    final boolean andCode = msg.arg2 != 0;
1569                    synchronized (mPackages) {
1570                        if (userId == UserHandle.USER_ALL) {
1571                            int[] users = sUserManager.getUserIds();
1572                            for (int user : users) {
1573                                mSettings.addPackageToCleanLPw(
1574                                        new PackageCleanItem(user, packageName, andCode));
1575                            }
1576                        } else {
1577                            mSettings.addPackageToCleanLPw(
1578                                    new PackageCleanItem(userId, packageName, andCode));
1579                        }
1580                    }
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1582                    startCleaningPackages();
1583                } break;
1584                case POST_INSTALL: {
1585                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1586
1587                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1588                    final boolean didRestore = (msg.arg2 != 0);
1589                    mRunningInstalls.delete(msg.arg1);
1590
1591                    if (data != null) {
1592                        InstallArgs args = data.args;
1593                        PackageInstalledInfo parentRes = data.res;
1594
1595                        final boolean grantPermissions = (args.installFlags
1596                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1597                        final boolean killApp = (args.installFlags
1598                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1599                        final String[] grantedPermissions = args.installGrantPermissions;
1600
1601                        // Handle the parent package
1602                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1603                                grantedPermissions, didRestore, args.installerPackageName,
1604                                args.observer);
1605
1606                        // Handle the child packages
1607                        final int childCount = (parentRes.addedChildPackages != null)
1608                                ? parentRes.addedChildPackages.size() : 0;
1609                        for (int i = 0; i < childCount; i++) {
1610                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1611                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1612                                    grantedPermissions, false, args.installerPackageName,
1613                                    args.observer);
1614                        }
1615
1616                        // Log tracing if needed
1617                        if (args.traceMethod != null) {
1618                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1619                                    args.traceCookie);
1620                        }
1621                    } else {
1622                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1623                    }
1624
1625                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1626                } break;
1627                case UPDATED_MEDIA_STATUS: {
1628                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1629                    boolean reportStatus = msg.arg1 == 1;
1630                    boolean doGc = msg.arg2 == 1;
1631                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1632                    if (doGc) {
1633                        // Force a gc to clear up stale containers.
1634                        Runtime.getRuntime().gc();
1635                    }
1636                    if (msg.obj != null) {
1637                        @SuppressWarnings("unchecked")
1638                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1639                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1640                        // Unload containers
1641                        unloadAllContainers(args);
1642                    }
1643                    if (reportStatus) {
1644                        try {
1645                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1646                            PackageHelper.getMountService().finishMediaUpdate();
1647                        } catch (RemoteException e) {
1648                            Log.e(TAG, "MountService not running?");
1649                        }
1650                    }
1651                } break;
1652                case WRITE_SETTINGS: {
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1654                    synchronized (mPackages) {
1655                        removeMessages(WRITE_SETTINGS);
1656                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1657                        mSettings.writeLPr();
1658                        mDirtyUsers.clear();
1659                    }
1660                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1661                } break;
1662                case WRITE_PACKAGE_RESTRICTIONS: {
1663                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1664                    synchronized (mPackages) {
1665                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1666                        for (int userId : mDirtyUsers) {
1667                            mSettings.writePackageRestrictionsLPr(userId);
1668                        }
1669                        mDirtyUsers.clear();
1670                    }
1671                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1672                } break;
1673                case WRITE_PACKAGE_LIST: {
1674                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1675                    synchronized (mPackages) {
1676                        removeMessages(WRITE_PACKAGE_LIST);
1677                        mSettings.writePackageListLPr(msg.arg1);
1678                    }
1679                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1680                } break;
1681                case CHECK_PENDING_VERIFICATION: {
1682                    final int verificationId = msg.arg1;
1683                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1684
1685                    if ((state != null) && !state.timeoutExtended()) {
1686                        final InstallArgs args = state.getInstallArgs();
1687                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1688
1689                        Slog.i(TAG, "Verification timed out for " + originUri);
1690                        mPendingVerification.remove(verificationId);
1691
1692                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1693
1694                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1695                            Slog.i(TAG, "Continuing with installation of " + originUri);
1696                            state.setVerifierResponse(Binder.getCallingUid(),
1697                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1698                            broadcastPackageVerified(verificationId, originUri,
1699                                    PackageManager.VERIFICATION_ALLOW,
1700                                    state.getInstallArgs().getUser());
1701                            try {
1702                                ret = args.copyApk(mContainerService, true);
1703                            } catch (RemoteException e) {
1704                                Slog.e(TAG, "Could not contact the ContainerService");
1705                            }
1706                        } else {
1707                            broadcastPackageVerified(verificationId, originUri,
1708                                    PackageManager.VERIFICATION_REJECT,
1709                                    state.getInstallArgs().getUser());
1710                        }
1711
1712                        Trace.asyncTraceEnd(
1713                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1714
1715                        processPendingInstall(args, ret);
1716                        mHandler.sendEmptyMessage(MCS_UNBIND);
1717                    }
1718                    break;
1719                }
1720                case PACKAGE_VERIFIED: {
1721                    final int verificationId = msg.arg1;
1722
1723                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1724                    if (state == null) {
1725                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1726                        break;
1727                    }
1728
1729                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1730
1731                    state.setVerifierResponse(response.callerUid, response.code);
1732
1733                    if (state.isVerificationComplete()) {
1734                        mPendingVerification.remove(verificationId);
1735
1736                        final InstallArgs args = state.getInstallArgs();
1737                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1738
1739                        int ret;
1740                        if (state.isInstallAllowed()) {
1741                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1742                            broadcastPackageVerified(verificationId, originUri,
1743                                    response.code, state.getInstallArgs().getUser());
1744                            try {
1745                                ret = args.copyApk(mContainerService, true);
1746                            } catch (RemoteException e) {
1747                                Slog.e(TAG, "Could not contact the ContainerService");
1748                            }
1749                        } else {
1750                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1751                        }
1752
1753                        Trace.asyncTraceEnd(
1754                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1755
1756                        processPendingInstall(args, ret);
1757                        mHandler.sendEmptyMessage(MCS_UNBIND);
1758                    }
1759
1760                    break;
1761                }
1762                case START_INTENT_FILTER_VERIFICATIONS: {
1763                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1764                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1765                            params.replacing, params.pkg);
1766                    break;
1767                }
1768                case INTENT_FILTER_VERIFIED: {
1769                    final int verificationId = msg.arg1;
1770
1771                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1772                            verificationId);
1773                    if (state == null) {
1774                        Slog.w(TAG, "Invalid IntentFilter verification token "
1775                                + verificationId + " received");
1776                        break;
1777                    }
1778
1779                    final int userId = state.getUserId();
1780
1781                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1782                            "Processing IntentFilter verification with token:"
1783                            + verificationId + " and userId:" + userId);
1784
1785                    final IntentFilterVerificationResponse response =
1786                            (IntentFilterVerificationResponse) msg.obj;
1787
1788                    state.setVerifierResponse(response.callerUid, response.code);
1789
1790                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1791                            "IntentFilter verification with token:" + verificationId
1792                            + " and userId:" + userId
1793                            + " is settings verifier response with response code:"
1794                            + response.code);
1795
1796                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1797                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1798                                + response.getFailedDomainsString());
1799                    }
1800
1801                    if (state.isVerificationComplete()) {
1802                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1803                    } else {
1804                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1805                                "IntentFilter verification with token:" + verificationId
1806                                + " was not said to be complete");
1807                    }
1808
1809                    break;
1810                }
1811            }
1812        }
1813    }
1814
1815    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1816            boolean killApp, String[] grantedPermissions,
1817            boolean launchedForRestore, String installerPackage,
1818            IPackageInstallObserver2 installObserver) {
1819        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1820            // Send the removed broadcasts
1821            if (res.removedInfo != null) {
1822                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1823            }
1824
1825            // Now that we successfully installed the package, grant runtime
1826            // permissions if requested before broadcasting the install.
1827            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1828                    >= Build.VERSION_CODES.M) {
1829                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1830            }
1831
1832            final boolean update = res.removedInfo != null
1833                    && res.removedInfo.removedPackage != null;
1834
1835            // If this is the first time we have child packages for a disabled privileged
1836            // app that had no children, we grant requested runtime permissions to the new
1837            // children if the parent on the system image had them already granted.
1838            if (res.pkg.parentPackage != null) {
1839                synchronized (mPackages) {
1840                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1841                }
1842            }
1843
1844            synchronized (mPackages) {
1845                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1846            }
1847
1848            final String packageName = res.pkg.applicationInfo.packageName;
1849            Bundle extras = new Bundle(1);
1850            extras.putInt(Intent.EXTRA_UID, res.uid);
1851
1852            // Determine the set of users who are adding this package for
1853            // the first time vs. those who are seeing an update.
1854            int[] firstUsers = EMPTY_INT_ARRAY;
1855            int[] updateUsers = EMPTY_INT_ARRAY;
1856            if (res.origUsers == null || res.origUsers.length == 0) {
1857                firstUsers = res.newUsers;
1858            } else {
1859                for (int newUser : res.newUsers) {
1860                    boolean isNew = true;
1861                    for (int origUser : res.origUsers) {
1862                        if (origUser == newUser) {
1863                            isNew = false;
1864                            break;
1865                        }
1866                    }
1867                    if (isNew) {
1868                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1869                    } else {
1870                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1871                    }
1872                }
1873            }
1874
1875            // Send installed broadcasts if the install/update is not ephemeral
1876            if (!isEphemeral(res.pkg)) {
1877                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1878
1879                // Send added for users that see the package for the first time
1880                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1881                        extras, 0 /*flags*/, null /*targetPackage*/,
1882                        null /*finishedReceiver*/, firstUsers);
1883
1884                // Send added for users that don't see the package for the first time
1885                if (update) {
1886                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1887                }
1888                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1889                        extras, 0 /*flags*/, null /*targetPackage*/,
1890                        null /*finishedReceiver*/, updateUsers);
1891
1892                // Send replaced for users that don't see the package for the first time
1893                if (update) {
1894                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1895                            packageName, extras, 0 /*flags*/,
1896                            null /*targetPackage*/, null /*finishedReceiver*/,
1897                            updateUsers);
1898                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1899                            null /*package*/, null /*extras*/, 0 /*flags*/,
1900                            packageName /*targetPackage*/,
1901                            null /*finishedReceiver*/, updateUsers);
1902                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1903                    // First-install and we did a restore, so we're responsible for the
1904                    // first-launch broadcast.
1905                    if (DEBUG_BACKUP) {
1906                        Slog.i(TAG, "Post-restore of " + packageName
1907                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1908                    }
1909                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1910                }
1911
1912                // Send broadcast package appeared if forward locked/external for all users
1913                // treat asec-hosted packages like removable media on upgrade
1914                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1915                    if (DEBUG_INSTALL) {
1916                        Slog.i(TAG, "upgrading pkg " + res.pkg
1917                                + " is ASEC-hosted -> AVAILABLE");
1918                    }
1919                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1920                    ArrayList<String> pkgList = new ArrayList<>(1);
1921                    pkgList.add(packageName);
1922                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1923                }
1924            }
1925
1926            // Work that needs to happen on first install within each user
1927            if (firstUsers != null && firstUsers.length > 0) {
1928                synchronized (mPackages) {
1929                    for (int userId : firstUsers) {
1930                        // If this app is a browser and it's newly-installed for some
1931                        // users, clear any default-browser state in those users. The
1932                        // app's nature doesn't depend on the user, so we can just check
1933                        // its browser nature in any user and generalize.
1934                        if (packageIsBrowser(packageName, userId)) {
1935                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1936                        }
1937
1938                        // We may also need to apply pending (restored) runtime
1939                        // permission grants within these users.
1940                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1941                    }
1942                }
1943            }
1944
1945            // Log current value of "unknown sources" setting
1946            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1947                    getUnknownSourcesSettings());
1948
1949            // Force a gc to clear up things
1950            Runtime.getRuntime().gc();
1951
1952            // Remove the replaced package's older resources safely now
1953            // We delete after a gc for applications  on sdcard.
1954            if (res.removedInfo != null && res.removedInfo.args != null) {
1955                synchronized (mInstallLock) {
1956                    res.removedInfo.args.doPostDeleteLI(true);
1957                }
1958            }
1959        }
1960
1961        // If someone is watching installs - notify them
1962        if (installObserver != null) {
1963            try {
1964                Bundle extras = extrasForInstallResult(res);
1965                installObserver.onPackageInstalled(res.name, res.returnCode,
1966                        res.returnMsg, extras);
1967            } catch (RemoteException e) {
1968                Slog.i(TAG, "Observer no longer exists.");
1969            }
1970        }
1971    }
1972
1973    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1974            PackageParser.Package pkg) {
1975        if (pkg.parentPackage == null) {
1976            return;
1977        }
1978        if (pkg.requestedPermissions == null) {
1979            return;
1980        }
1981        final PackageSetting disabledSysParentPs = mSettings
1982                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1983        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1984                || !disabledSysParentPs.isPrivileged()
1985                || (disabledSysParentPs.childPackageNames != null
1986                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1987            return;
1988        }
1989        final int[] allUserIds = sUserManager.getUserIds();
1990        final int permCount = pkg.requestedPermissions.size();
1991        for (int i = 0; i < permCount; i++) {
1992            String permission = pkg.requestedPermissions.get(i);
1993            BasePermission bp = mSettings.mPermissions.get(permission);
1994            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1995                continue;
1996            }
1997            for (int userId : allUserIds) {
1998                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1999                        permission, userId)) {
2000                    grantRuntimePermission(pkg.packageName, permission, userId);
2001                }
2002            }
2003        }
2004    }
2005
2006    private StorageEventListener mStorageListener = new StorageEventListener() {
2007        @Override
2008        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2009            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2010                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2011                    final String volumeUuid = vol.getFsUuid();
2012
2013                    // Clean up any users or apps that were removed or recreated
2014                    // while this volume was missing
2015                    reconcileUsers(volumeUuid);
2016                    reconcileApps(volumeUuid);
2017
2018                    // Clean up any install sessions that expired or were
2019                    // cancelled while this volume was missing
2020                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2021
2022                    loadPrivatePackages(vol);
2023
2024                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2025                    unloadPrivatePackages(vol);
2026                }
2027            }
2028
2029            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2030                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2031                    updateExternalMediaStatus(true, false);
2032                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2033                    updateExternalMediaStatus(false, false);
2034                }
2035            }
2036        }
2037
2038        @Override
2039        public void onVolumeForgotten(String fsUuid) {
2040            if (TextUtils.isEmpty(fsUuid)) {
2041                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2042                return;
2043            }
2044
2045            // Remove any apps installed on the forgotten volume
2046            synchronized (mPackages) {
2047                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2048                for (PackageSetting ps : packages) {
2049                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2050                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2051                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2052                }
2053
2054                mSettings.onVolumeForgotten(fsUuid);
2055                mSettings.writeLPr();
2056            }
2057        }
2058    };
2059
2060    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2061            String[] grantedPermissions) {
2062        for (int userId : userIds) {
2063            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2064        }
2065
2066        // We could have touched GID membership, so flush out packages.list
2067        synchronized (mPackages) {
2068            mSettings.writePackageListLPr();
2069        }
2070    }
2071
2072    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2073            String[] grantedPermissions) {
2074        SettingBase sb = (SettingBase) pkg.mExtras;
2075        if (sb == null) {
2076            return;
2077        }
2078
2079        PermissionsState permissionsState = sb.getPermissionsState();
2080
2081        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2082                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2083
2084        for (String permission : pkg.requestedPermissions) {
2085            final BasePermission bp;
2086            synchronized (mPackages) {
2087                bp = mSettings.mPermissions.get(permission);
2088            }
2089            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2090                    && (grantedPermissions == null
2091                           || ArrayUtils.contains(grantedPermissions, permission))) {
2092                final int flags = permissionsState.getPermissionFlags(permission, userId);
2093                // Installer cannot change immutable permissions.
2094                if ((flags & immutableFlags) == 0) {
2095                    grantRuntimePermission(pkg.packageName, permission, userId);
2096                }
2097            }
2098        }
2099    }
2100
2101    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2102        Bundle extras = null;
2103        switch (res.returnCode) {
2104            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2105                extras = new Bundle();
2106                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2107                        res.origPermission);
2108                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2109                        res.origPackage);
2110                break;
2111            }
2112            case PackageManager.INSTALL_SUCCEEDED: {
2113                extras = new Bundle();
2114                extras.putBoolean(Intent.EXTRA_REPLACING,
2115                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2116                break;
2117            }
2118        }
2119        return extras;
2120    }
2121
2122    void scheduleWriteSettingsLocked() {
2123        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2124            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2125        }
2126    }
2127
2128    void scheduleWritePackageListLocked(int userId) {
2129        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2130            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2131            msg.arg1 = userId;
2132            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2133        }
2134    }
2135
2136    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2137        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2138        scheduleWritePackageRestrictionsLocked(userId);
2139    }
2140
2141    void scheduleWritePackageRestrictionsLocked(int userId) {
2142        final int[] userIds = (userId == UserHandle.USER_ALL)
2143                ? sUserManager.getUserIds() : new int[]{userId};
2144        for (int nextUserId : userIds) {
2145            if (!sUserManager.exists(nextUserId)) return;
2146            mDirtyUsers.add(nextUserId);
2147            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2148                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2149            }
2150        }
2151    }
2152
2153    public static PackageManagerService main(Context context, Installer installer,
2154            boolean factoryTest, boolean onlyCore) {
2155        // Self-check for initial settings.
2156        PackageManagerServiceCompilerMapping.checkProperties();
2157
2158        PackageManagerService m = new PackageManagerService(context, installer,
2159                factoryTest, onlyCore);
2160        m.enableSystemUserPackages();
2161        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2162        // disabled after already being started.
2163        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2164                UserHandle.USER_SYSTEM);
2165        ServiceManager.addService("package", m);
2166        return m;
2167    }
2168
2169    private void enableSystemUserPackages() {
2170        if (!UserManager.isSplitSystemUser()) {
2171            return;
2172        }
2173        // For system user, enable apps based on the following conditions:
2174        // - app is whitelisted or belong to one of these groups:
2175        //   -- system app which has no launcher icons
2176        //   -- system app which has INTERACT_ACROSS_USERS permission
2177        //   -- system IME app
2178        // - app is not in the blacklist
2179        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2180        Set<String> enableApps = new ArraySet<>();
2181        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2182                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2183                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2184        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2185        enableApps.addAll(wlApps);
2186        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2187                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2188        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2189        enableApps.removeAll(blApps);
2190        Log.i(TAG, "Applications installed for system user: " + enableApps);
2191        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2192                UserHandle.SYSTEM);
2193        final int allAppsSize = allAps.size();
2194        synchronized (mPackages) {
2195            for (int i = 0; i < allAppsSize; i++) {
2196                String pName = allAps.get(i);
2197                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2198                // Should not happen, but we shouldn't be failing if it does
2199                if (pkgSetting == null) {
2200                    continue;
2201                }
2202                boolean install = enableApps.contains(pName);
2203                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2204                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2205                            + " for system user");
2206                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2207                }
2208            }
2209        }
2210    }
2211
2212    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2213        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2214                Context.DISPLAY_SERVICE);
2215        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2216    }
2217
2218    public PackageManagerService(Context context, Installer installer,
2219            boolean factoryTest, boolean onlyCore) {
2220        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2221                SystemClock.uptimeMillis());
2222
2223        if (mSdkVersion <= 0) {
2224            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2225        }
2226
2227        mContext = context;
2228        mFactoryTest = factoryTest;
2229        mOnlyCore = onlyCore;
2230        mMetrics = new DisplayMetrics();
2231        mSettings = new Settings(mPackages);
2232        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2233                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2234        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244
2245        String separateProcesses = SystemProperties.get("debug.separate_processes");
2246        if (separateProcesses != null && separateProcesses.length() > 0) {
2247            if ("*".equals(separateProcesses)) {
2248                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2249                mSeparateProcesses = null;
2250                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2251            } else {
2252                mDefParseFlags = 0;
2253                mSeparateProcesses = separateProcesses.split(",");
2254                Slog.w(TAG, "Running with debug.separate_processes: "
2255                        + separateProcesses);
2256            }
2257        } else {
2258            mDefParseFlags = 0;
2259            mSeparateProcesses = null;
2260        }
2261
2262        mInstaller = installer;
2263        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2264                "*dexopt*");
2265        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2266
2267        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2268                FgThread.get().getLooper());
2269
2270        getDefaultDisplayMetrics(context, mMetrics);
2271
2272        SystemConfig systemConfig = SystemConfig.getInstance();
2273        mGlobalGids = systemConfig.getGlobalGids();
2274        mSystemPermissions = systemConfig.getSystemPermissions();
2275        mAvailableFeatures = systemConfig.getAvailableFeatures();
2276
2277        synchronized (mInstallLock) {
2278        // writer
2279        synchronized (mPackages) {
2280            mHandlerThread = new ServiceThread(TAG,
2281                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2282            mHandlerThread.start();
2283            mHandler = new PackageHandler(mHandlerThread.getLooper());
2284            mProcessLoggingHandler = new ProcessLoggingHandler();
2285            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2286
2287            File dataDir = Environment.getDataDirectory();
2288            mAppInstallDir = new File(dataDir, "app");
2289            mAppLib32InstallDir = new File(dataDir, "app-lib");
2290            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2291            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2292            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2293
2294            sUserManager = new UserManagerService(context, this, mPackages);
2295
2296            // Propagate permission configuration in to package manager.
2297            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2298                    = systemConfig.getPermissions();
2299            for (int i=0; i<permConfig.size(); i++) {
2300                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2301                BasePermission bp = mSettings.mPermissions.get(perm.name);
2302                if (bp == null) {
2303                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2304                    mSettings.mPermissions.put(perm.name, bp);
2305                }
2306                if (perm.gids != null) {
2307                    bp.setGids(perm.gids, perm.perUser);
2308                }
2309            }
2310
2311            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2312            for (int i=0; i<libConfig.size(); i++) {
2313                mSharedLibraries.put(libConfig.keyAt(i),
2314                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2315            }
2316
2317            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2318
2319            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2320
2321            String customResolverActivity = Resources.getSystem().getString(
2322                    R.string.config_customResolverActivity);
2323            if (TextUtils.isEmpty(customResolverActivity)) {
2324                customResolverActivity = null;
2325            } else {
2326                mCustomResolverComponentName = ComponentName.unflattenFromString(
2327                        customResolverActivity);
2328            }
2329
2330            long startTime = SystemClock.uptimeMillis();
2331
2332            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2333                    startTime);
2334
2335            // Set flag to monitor and not change apk file paths when
2336            // scanning install directories.
2337            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2338
2339            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2340            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2341
2342            if (bootClassPath == null) {
2343                Slog.w(TAG, "No BOOTCLASSPATH found!");
2344            }
2345
2346            if (systemServerClassPath == null) {
2347                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2348            }
2349
2350            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2351            final String[] dexCodeInstructionSets =
2352                    getDexCodeInstructionSets(
2353                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2354
2355            /**
2356             * Ensure all external libraries have had dexopt run on them.
2357             */
2358            if (mSharedLibraries.size() > 0) {
2359                // NOTE: For now, we're compiling these system "shared libraries"
2360                // (and framework jars) into all available architectures. It's possible
2361                // to compile them only when we come across an app that uses them (there's
2362                // already logic for that in scanPackageLI) but that adds some complexity.
2363                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2364                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2365                        final String lib = libEntry.path;
2366                        if (lib == null) {
2367                            continue;
2368                        }
2369
2370                        try {
2371                            // Shared libraries do not have profiles so we perform a full
2372                            // AOT compilation (if needed).
2373                            int dexoptNeeded = DexFile.getDexOptNeeded(
2374                                    lib, dexCodeInstructionSet,
2375                                    getCompilerFilterForReason(REASON_SHARED_APK),
2376                                    false /* newProfile */);
2377                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2378                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2379                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2380                                        getCompilerFilterForReason(REASON_SHARED_APK),
2381                                        StorageManager.UUID_PRIVATE_INTERNAL,
2382                                        SKIP_SHARED_LIBRARY_CHECK);
2383                            }
2384                        } catch (FileNotFoundException e) {
2385                            Slog.w(TAG, "Library not found: " + lib);
2386                        } catch (IOException | InstallerException e) {
2387                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2388                                    + e.getMessage());
2389                        }
2390                    }
2391                }
2392            }
2393
2394            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2395
2396            final VersionInfo ver = mSettings.getInternalVersion();
2397            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2398
2399            // when upgrading from pre-M, promote system app permissions from install to runtime
2400            mPromoteSystemApps =
2401                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2402
2403            // When upgrading from pre-N, we need to handle package extraction like first boot,
2404            // as there is no profiling data available.
2405            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2406
2407            // save off the names of pre-existing system packages prior to scanning; we don't
2408            // want to automatically grant runtime permissions for new system apps
2409            if (mPromoteSystemApps) {
2410                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2411                while (pkgSettingIter.hasNext()) {
2412                    PackageSetting ps = pkgSettingIter.next();
2413                    if (isSystemApp(ps)) {
2414                        mExistingSystemPackages.add(ps.name);
2415                    }
2416                }
2417            }
2418
2419            // Collect vendor overlay packages.
2420            // (Do this before scanning any apps.)
2421            // For security and version matching reason, only consider
2422            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2423            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2424            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2425                    | PackageParser.PARSE_IS_SYSTEM
2426                    | PackageParser.PARSE_IS_SYSTEM_DIR
2427                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2428
2429            // Find base frameworks (resource packages without code).
2430            scanDirTracedLI(frameworkDir, mDefParseFlags
2431                    | PackageParser.PARSE_IS_SYSTEM
2432                    | PackageParser.PARSE_IS_SYSTEM_DIR
2433                    | PackageParser.PARSE_IS_PRIVILEGED,
2434                    scanFlags | SCAN_NO_DEX, 0);
2435
2436            // Collected privileged system packages.
2437            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2438            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2439                    | PackageParser.PARSE_IS_SYSTEM
2440                    | PackageParser.PARSE_IS_SYSTEM_DIR
2441                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2442
2443            // Collect ordinary system packages.
2444            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2445            scanDirTracedLI(systemAppDir, mDefParseFlags
2446                    | PackageParser.PARSE_IS_SYSTEM
2447                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2448
2449            // Collect all vendor packages.
2450            File vendorAppDir = new File("/vendor/app");
2451            try {
2452                vendorAppDir = vendorAppDir.getCanonicalFile();
2453            } catch (IOException e) {
2454                // failed to look up canonical path, continue with original one
2455            }
2456            scanDirTracedLI(vendorAppDir, mDefParseFlags
2457                    | PackageParser.PARSE_IS_SYSTEM
2458                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2459
2460            // Collect all OEM packages.
2461            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2462            scanDirTracedLI(oemAppDir, mDefParseFlags
2463                    | PackageParser.PARSE_IS_SYSTEM
2464                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2465
2466            // Prune any system packages that no longer exist.
2467            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2468            if (!mOnlyCore) {
2469                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2470                while (psit.hasNext()) {
2471                    PackageSetting ps = psit.next();
2472
2473                    /*
2474                     * If this is not a system app, it can't be a
2475                     * disable system app.
2476                     */
2477                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2478                        continue;
2479                    }
2480
2481                    /*
2482                     * If the package is scanned, it's not erased.
2483                     */
2484                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2485                    if (scannedPkg != null) {
2486                        /*
2487                         * If the system app is both scanned and in the
2488                         * disabled packages list, then it must have been
2489                         * added via OTA. Remove it from the currently
2490                         * scanned package so the previously user-installed
2491                         * application can be scanned.
2492                         */
2493                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2494                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2495                                    + ps.name + "; removing system app.  Last known codePath="
2496                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2497                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2498                                    + scannedPkg.mVersionCode);
2499                            removePackageLI(scannedPkg, true);
2500                            mExpectingBetter.put(ps.name, ps.codePath);
2501                        }
2502
2503                        continue;
2504                    }
2505
2506                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2507                        psit.remove();
2508                        logCriticalInfo(Log.WARN, "System package " + ps.name
2509                                + " no longer exists; it's data will be wiped");
2510                        // Actual deletion of code and data will be handled by later
2511                        // reconciliation step
2512                    } else {
2513                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2514                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2515                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2516                        }
2517                    }
2518                }
2519            }
2520
2521            //look for any incomplete package installations
2522            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2523            for (int i = 0; i < deletePkgsList.size(); i++) {
2524                // Actual deletion of code and data will be handled by later
2525                // reconciliation step
2526                final String packageName = deletePkgsList.get(i).name;
2527                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2528                synchronized (mPackages) {
2529                    mSettings.removePackageLPw(packageName);
2530                }
2531            }
2532
2533            //delete tmp files
2534            deleteTempPackageFiles();
2535
2536            // Remove any shared userIDs that have no associated packages
2537            mSettings.pruneSharedUsersLPw();
2538
2539            if (!mOnlyCore) {
2540                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2541                        SystemClock.uptimeMillis());
2542                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2543
2544                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2545                        | PackageParser.PARSE_FORWARD_LOCK,
2546                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2547
2548                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2549                        | PackageParser.PARSE_IS_EPHEMERAL,
2550                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2551
2552                /**
2553                 * Remove disable package settings for any updated system
2554                 * apps that were removed via an OTA. If they're not a
2555                 * previously-updated app, remove them completely.
2556                 * Otherwise, just revoke their system-level permissions.
2557                 */
2558                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2559                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2560                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2561
2562                    String msg;
2563                    if (deletedPkg == null) {
2564                        msg = "Updated system package " + deletedAppName
2565                                + " no longer exists; it's data will be wiped";
2566                        // Actual deletion of code and data will be handled by later
2567                        // reconciliation step
2568                    } else {
2569                        msg = "Updated system app + " + deletedAppName
2570                                + " no longer present; removing system privileges for "
2571                                + deletedAppName;
2572
2573                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2574
2575                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2576                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2577                    }
2578                    logCriticalInfo(Log.WARN, msg);
2579                }
2580
2581                /**
2582                 * Make sure all system apps that we expected to appear on
2583                 * the userdata partition actually showed up. If they never
2584                 * appeared, crawl back and revive the system version.
2585                 */
2586                for (int i = 0; i < mExpectingBetter.size(); i++) {
2587                    final String packageName = mExpectingBetter.keyAt(i);
2588                    if (!mPackages.containsKey(packageName)) {
2589                        final File scanFile = mExpectingBetter.valueAt(i);
2590
2591                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2592                                + " but never showed up; reverting to system");
2593
2594                        int reparseFlags = mDefParseFlags;
2595                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2596                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2597                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                                    | PackageParser.PARSE_IS_PRIVILEGED;
2599                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2600                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2601                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2602                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2603                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2604                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2605                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2606                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2607                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2608                        } else {
2609                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2610                            continue;
2611                        }
2612
2613                        mSettings.enableSystemPackageLPw(packageName);
2614
2615                        try {
2616                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2617                        } catch (PackageManagerException e) {
2618                            Slog.e(TAG, "Failed to parse original system package: "
2619                                    + e.getMessage());
2620                        }
2621                    }
2622                }
2623            }
2624            mExpectingBetter.clear();
2625
2626            // Resolve protected action filters. Only the setup wizard is allowed to
2627            // have a high priority filter for these actions.
2628            mSetupWizardPackage = getSetupWizardPackageName();
2629            if (mProtectedFilters.size() > 0) {
2630                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2631                    Slog.i(TAG, "No setup wizard;"
2632                        + " All protected intents capped to priority 0");
2633                }
2634                for (ActivityIntentInfo filter : mProtectedFilters) {
2635                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2636                        if (DEBUG_FILTERS) {
2637                            Slog.i(TAG, "Found setup wizard;"
2638                                + " allow priority " + filter.getPriority() + ";"
2639                                + " package: " + filter.activity.info.packageName
2640                                + " activity: " + filter.activity.className
2641                                + " priority: " + filter.getPriority());
2642                        }
2643                        // skip setup wizard; allow it to keep the high priority filter
2644                        continue;
2645                    }
2646                    Slog.w(TAG, "Protected action; cap priority to 0;"
2647                            + " package: " + filter.activity.info.packageName
2648                            + " activity: " + filter.activity.className
2649                            + " origPrio: " + filter.getPriority());
2650                    filter.setPriority(0);
2651                }
2652            }
2653            mDeferProtectedFilters = false;
2654            mProtectedFilters.clear();
2655
2656            // Now that we know all of the shared libraries, update all clients to have
2657            // the correct library paths.
2658            updateAllSharedLibrariesLPw();
2659
2660            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2661                // NOTE: We ignore potential failures here during a system scan (like
2662                // the rest of the commands above) because there's precious little we
2663                // can do about it. A settings error is reported, though.
2664                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2665                        false /* boot complete */);
2666            }
2667
2668            // Now that we know all the packages we are keeping,
2669            // read and update their last usage times.
2670            mPackageUsage.readLP();
2671
2672            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2673                    SystemClock.uptimeMillis());
2674            Slog.i(TAG, "Time to scan packages: "
2675                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2676                    + " seconds");
2677
2678            // If the platform SDK has changed since the last time we booted,
2679            // we need to re-grant app permission to catch any new ones that
2680            // appear.  This is really a hack, and means that apps can in some
2681            // cases get permissions that the user didn't initially explicitly
2682            // allow...  it would be nice to have some better way to handle
2683            // this situation.
2684            int updateFlags = UPDATE_PERMISSIONS_ALL;
2685            if (ver.sdkVersion != mSdkVersion) {
2686                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2687                        + mSdkVersion + "; regranting permissions for internal storage");
2688                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2689            }
2690            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2691            ver.sdkVersion = mSdkVersion;
2692
2693            // If this is the first boot or an update from pre-M, and it is a normal
2694            // boot, then we need to initialize the default preferred apps across
2695            // all defined users.
2696            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2697                for (UserInfo user : sUserManager.getUsers(true)) {
2698                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2699                    applyFactoryDefaultBrowserLPw(user.id);
2700                    primeDomainVerificationsLPw(user.id);
2701                }
2702            }
2703
2704            // Prepare storage for system user really early during boot,
2705            // since core system apps like SettingsProvider and SystemUI
2706            // can't wait for user to start
2707            final int storageFlags;
2708            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2709                storageFlags = StorageManager.FLAG_STORAGE_DE;
2710            } else {
2711                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2712            }
2713            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2714                    storageFlags);
2715
2716            // If this is first boot after an OTA, and a normal boot, then
2717            // we need to clear code cache directories.
2718            // Note that we do *not* clear the application profiles. These remain valid
2719            // across OTAs and are used to drive profile verification (post OTA) and
2720            // profile compilation (without waiting to collect a fresh set of profiles).
2721            if (mIsUpgrade && !onlyCore) {
2722                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2723                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2724                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2725                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2726                        // No apps are running this early, so no need to freeze
2727                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2728                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2729                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2730                    }
2731                }
2732                ver.fingerprint = Build.FINGERPRINT;
2733            }
2734
2735            checkDefaultBrowser();
2736
2737            // clear only after permissions and other defaults have been updated
2738            mExistingSystemPackages.clear();
2739            mPromoteSystemApps = false;
2740
2741            // All the changes are done during package scanning.
2742            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2743
2744            // can downgrade to reader
2745            mSettings.writeLPr();
2746
2747            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2748            // early on (before the package manager declares itself as early) because other
2749            // components in the system server might ask for package contexts for these apps.
2750            //
2751            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2752            // (i.e, that the data partition is unavailable).
2753            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2754                long start = System.nanoTime();
2755                List<PackageParser.Package> coreApps = new ArrayList<>();
2756                for (PackageParser.Package pkg : mPackages.values()) {
2757                    if (pkg.coreApp) {
2758                        coreApps.add(pkg);
2759                    }
2760                }
2761
2762                int[] stats = performDexOpt(coreApps, false,
2763                        getCompilerFilterForReason(REASON_CORE_APP));
2764
2765                final int elapsedTimeSeconds =
2766                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2767                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2768
2769                if (DEBUG_DEXOPT) {
2770                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2771                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2772                }
2773
2774
2775                // TODO: Should we log these stats to tron too ?
2776                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2777                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2778                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2779                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2780            }
2781
2782            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2783                    SystemClock.uptimeMillis());
2784
2785            if (!mOnlyCore) {
2786                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2787                mRequiredInstallerPackage = getRequiredInstallerLPr();
2788                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2789                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2790                        mIntentFilterVerifierComponent);
2791                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2792                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2793                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2794                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2795            } else {
2796                mRequiredVerifierPackage = null;
2797                mRequiredInstallerPackage = null;
2798                mIntentFilterVerifierComponent = null;
2799                mIntentFilterVerifier = null;
2800                mServicesSystemSharedLibraryPackageName = null;
2801                mSharedSystemSharedLibraryPackageName = null;
2802            }
2803
2804            mInstallerService = new PackageInstallerService(context, this);
2805
2806            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2807            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2808            // both the installer and resolver must be present to enable ephemeral
2809            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2810                if (DEBUG_EPHEMERAL) {
2811                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2812                            + " installer:" + ephemeralInstallerComponent);
2813                }
2814                mEphemeralResolverComponent = ephemeralResolverComponent;
2815                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2816                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2817                mEphemeralResolverConnection =
2818                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2819            } else {
2820                if (DEBUG_EPHEMERAL) {
2821                    final String missingComponent =
2822                            (ephemeralResolverComponent == null)
2823                            ? (ephemeralInstallerComponent == null)
2824                                    ? "resolver and installer"
2825                                    : "resolver"
2826                            : "installer";
2827                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2828                }
2829                mEphemeralResolverComponent = null;
2830                mEphemeralInstallerComponent = null;
2831                mEphemeralResolverConnection = null;
2832            }
2833
2834            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2835        } // synchronized (mPackages)
2836        } // synchronized (mInstallLock)
2837
2838        // Now after opening every single application zip, make sure they
2839        // are all flushed.  Not really needed, but keeps things nice and
2840        // tidy.
2841        Runtime.getRuntime().gc();
2842
2843        // The initial scanning above does many calls into installd while
2844        // holding the mPackages lock, but we're mostly interested in yelling
2845        // once we have a booted system.
2846        mInstaller.setWarnIfHeld(mPackages);
2847
2848        // Expose private service for system components to use.
2849        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2850    }
2851
2852    @Override
2853    public boolean isFirstBoot() {
2854        return !mRestoredSettings;
2855    }
2856
2857    @Override
2858    public boolean isOnlyCoreApps() {
2859        return mOnlyCore;
2860    }
2861
2862    @Override
2863    public boolean isUpgrade() {
2864        return mIsUpgrade;
2865    }
2866
2867    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2868        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2869
2870        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2871                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2872                UserHandle.USER_SYSTEM);
2873        if (matches.size() == 1) {
2874            return matches.get(0).getComponentInfo().packageName;
2875        } else {
2876            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2877            return null;
2878        }
2879    }
2880
2881    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2882        synchronized (mPackages) {
2883            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2884            if (libraryEntry == null) {
2885                throw new IllegalStateException("Missing required shared library:" + libraryName);
2886            }
2887            return libraryEntry.apk;
2888        }
2889    }
2890
2891    private @NonNull String getRequiredInstallerLPr() {
2892        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2893        intent.addCategory(Intent.CATEGORY_DEFAULT);
2894        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2895
2896        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2897                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2898                UserHandle.USER_SYSTEM);
2899        if (matches.size() == 1) {
2900            ResolveInfo resolveInfo = matches.get(0);
2901            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2902                throw new RuntimeException("The installer must be a privileged app");
2903            }
2904            return matches.get(0).getComponentInfo().packageName;
2905        } else {
2906            throw new RuntimeException("There must be exactly one installer; found " + matches);
2907        }
2908    }
2909
2910    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2911        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2912
2913        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2914                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2915                UserHandle.USER_SYSTEM);
2916        ResolveInfo best = null;
2917        final int N = matches.size();
2918        for (int i = 0; i < N; i++) {
2919            final ResolveInfo cur = matches.get(i);
2920            final String packageName = cur.getComponentInfo().packageName;
2921            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2922                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2923                continue;
2924            }
2925
2926            if (best == null || cur.priority > best.priority) {
2927                best = cur;
2928            }
2929        }
2930
2931        if (best != null) {
2932            return best.getComponentInfo().getComponentName();
2933        } else {
2934            throw new RuntimeException("There must be at least one intent filter verifier");
2935        }
2936    }
2937
2938    private @Nullable ComponentName getEphemeralResolverLPr() {
2939        final String[] packageArray =
2940                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2941        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2942            if (DEBUG_EPHEMERAL) {
2943                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2944            }
2945            return null;
2946        }
2947
2948        final int resolveFlags =
2949                MATCH_DIRECT_BOOT_AWARE
2950                | MATCH_DIRECT_BOOT_UNAWARE
2951                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2952        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2953        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2954                resolveFlags, UserHandle.USER_SYSTEM);
2955
2956        final int N = resolvers.size();
2957        if (N == 0) {
2958            if (DEBUG_EPHEMERAL) {
2959                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2960            }
2961            return null;
2962        }
2963
2964        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2965        for (int i = 0; i < N; i++) {
2966            final ResolveInfo info = resolvers.get(i);
2967
2968            if (info.serviceInfo == null) {
2969                continue;
2970            }
2971
2972            final String packageName = info.serviceInfo.packageName;
2973            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2974                if (DEBUG_EPHEMERAL) {
2975                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2976                            + " pkg: " + packageName + ", info:" + info);
2977                }
2978                continue;
2979            }
2980
2981            if (DEBUG_EPHEMERAL) {
2982                Slog.v(TAG, "Ephemeral resolver found;"
2983                        + " pkg: " + packageName + ", info:" + info);
2984            }
2985            return new ComponentName(packageName, info.serviceInfo.name);
2986        }
2987        if (DEBUG_EPHEMERAL) {
2988            Slog.v(TAG, "Ephemeral resolver NOT found");
2989        }
2990        return null;
2991    }
2992
2993    private @Nullable ComponentName getEphemeralInstallerLPr() {
2994        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2995        intent.addCategory(Intent.CATEGORY_DEFAULT);
2996        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2997
2998        final int resolveFlags =
2999                MATCH_DIRECT_BOOT_AWARE
3000                | MATCH_DIRECT_BOOT_UNAWARE
3001                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3002        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3003                resolveFlags, UserHandle.USER_SYSTEM);
3004        if (matches.size() == 0) {
3005            return null;
3006        } else if (matches.size() == 1) {
3007            return matches.get(0).getComponentInfo().getComponentName();
3008        } else {
3009            throw new RuntimeException(
3010                    "There must be at most one ephemeral installer; found " + matches);
3011        }
3012    }
3013
3014    private void primeDomainVerificationsLPw(int userId) {
3015        if (DEBUG_DOMAIN_VERIFICATION) {
3016            Slog.d(TAG, "Priming domain verifications in user " + userId);
3017        }
3018
3019        SystemConfig systemConfig = SystemConfig.getInstance();
3020        ArraySet<String> packages = systemConfig.getLinkedApps();
3021        ArraySet<String> domains = new ArraySet<String>();
3022
3023        for (String packageName : packages) {
3024            PackageParser.Package pkg = mPackages.get(packageName);
3025            if (pkg != null) {
3026                if (!pkg.isSystemApp()) {
3027                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3028                    continue;
3029                }
3030
3031                domains.clear();
3032                for (PackageParser.Activity a : pkg.activities) {
3033                    for (ActivityIntentInfo filter : a.intents) {
3034                        if (hasValidDomains(filter)) {
3035                            domains.addAll(filter.getHostsList());
3036                        }
3037                    }
3038                }
3039
3040                if (domains.size() > 0) {
3041                    if (DEBUG_DOMAIN_VERIFICATION) {
3042                        Slog.v(TAG, "      + " + packageName);
3043                    }
3044                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3045                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3046                    // and then 'always' in the per-user state actually used for intent resolution.
3047                    final IntentFilterVerificationInfo ivi;
3048                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3049                            new ArrayList<String>(domains));
3050                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3051                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3052                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3053                } else {
3054                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3055                            + "' does not handle web links");
3056                }
3057            } else {
3058                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3059            }
3060        }
3061
3062        scheduleWritePackageRestrictionsLocked(userId);
3063        scheduleWriteSettingsLocked();
3064    }
3065
3066    private void applyFactoryDefaultBrowserLPw(int userId) {
3067        // The default browser app's package name is stored in a string resource,
3068        // with a product-specific overlay used for vendor customization.
3069        String browserPkg = mContext.getResources().getString(
3070                com.android.internal.R.string.default_browser);
3071        if (!TextUtils.isEmpty(browserPkg)) {
3072            // non-empty string => required to be a known package
3073            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3074            if (ps == null) {
3075                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3076                browserPkg = null;
3077            } else {
3078                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3079            }
3080        }
3081
3082        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3083        // default.  If there's more than one, just leave everything alone.
3084        if (browserPkg == null) {
3085            calculateDefaultBrowserLPw(userId);
3086        }
3087    }
3088
3089    private void calculateDefaultBrowserLPw(int userId) {
3090        List<String> allBrowsers = resolveAllBrowserApps(userId);
3091        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3092        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3093    }
3094
3095    private List<String> resolveAllBrowserApps(int userId) {
3096        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3097        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3098                PackageManager.MATCH_ALL, userId);
3099
3100        final int count = list.size();
3101        List<String> result = new ArrayList<String>(count);
3102        for (int i=0; i<count; i++) {
3103            ResolveInfo info = list.get(i);
3104            if (info.activityInfo == null
3105                    || !info.handleAllWebDataURI
3106                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3107                    || result.contains(info.activityInfo.packageName)) {
3108                continue;
3109            }
3110            result.add(info.activityInfo.packageName);
3111        }
3112
3113        return result;
3114    }
3115
3116    private boolean packageIsBrowser(String packageName, int userId) {
3117        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3118                PackageManager.MATCH_ALL, userId);
3119        final int N = list.size();
3120        for (int i = 0; i < N; i++) {
3121            ResolveInfo info = list.get(i);
3122            if (packageName.equals(info.activityInfo.packageName)) {
3123                return true;
3124            }
3125        }
3126        return false;
3127    }
3128
3129    private void checkDefaultBrowser() {
3130        final int myUserId = UserHandle.myUserId();
3131        final String packageName = getDefaultBrowserPackageName(myUserId);
3132        if (packageName != null) {
3133            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3134            if (info == null) {
3135                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3136                synchronized (mPackages) {
3137                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3138                }
3139            }
3140        }
3141    }
3142
3143    @Override
3144    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3145            throws RemoteException {
3146        try {
3147            return super.onTransact(code, data, reply, flags);
3148        } catch (RuntimeException e) {
3149            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3150                Slog.wtf(TAG, "Package Manager Crash", e);
3151            }
3152            throw e;
3153        }
3154    }
3155
3156    static int[] appendInts(int[] cur, int[] add) {
3157        if (add == null) return cur;
3158        if (cur == null) return add;
3159        final int N = add.length;
3160        for (int i=0; i<N; i++) {
3161            cur = appendInt(cur, add[i]);
3162        }
3163        return cur;
3164    }
3165
3166    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3167        if (!sUserManager.exists(userId)) return null;
3168        if (ps == null) {
3169            return null;
3170        }
3171        final PackageParser.Package p = ps.pkg;
3172        if (p == null) {
3173            return null;
3174        }
3175
3176        final PermissionsState permissionsState = ps.getPermissionsState();
3177
3178        final int[] gids = permissionsState.computeGids(userId);
3179        final Set<String> permissions = permissionsState.getPermissions(userId);
3180        final PackageUserState state = ps.readUserState(userId);
3181
3182        return PackageParser.generatePackageInfo(p, gids, flags,
3183                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3184    }
3185
3186    @Override
3187    public void checkPackageStartable(String packageName, int userId) {
3188        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3189
3190        synchronized (mPackages) {
3191            final PackageSetting ps = mSettings.mPackages.get(packageName);
3192            if (ps == null) {
3193                throw new SecurityException("Package " + packageName + " was not found!");
3194            }
3195
3196            if (!ps.getInstalled(userId)) {
3197                throw new SecurityException(
3198                        "Package " + packageName + " was not installed for user " + userId + "!");
3199            }
3200
3201            if (mSafeMode && !ps.isSystem()) {
3202                throw new SecurityException("Package " + packageName + " not a system app!");
3203            }
3204
3205            if (mFrozenPackages.contains(packageName)) {
3206                throw new SecurityException("Package " + packageName + " is currently frozen!");
3207            }
3208
3209            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3210                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3211                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3212            }
3213        }
3214    }
3215
3216    @Override
3217    public boolean isPackageAvailable(String packageName, int userId) {
3218        if (!sUserManager.exists(userId)) return false;
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3220                false /* requireFullPermission */, false /* checkShell */, "is package available");
3221        synchronized (mPackages) {
3222            PackageParser.Package p = mPackages.get(packageName);
3223            if (p != null) {
3224                final PackageSetting ps = (PackageSetting) p.mExtras;
3225                if (ps != null) {
3226                    final PackageUserState state = ps.readUserState(userId);
3227                    if (state != null) {
3228                        return PackageParser.isAvailable(state);
3229                    }
3230                }
3231            }
3232        }
3233        return false;
3234    }
3235
3236    @Override
3237    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3238        if (!sUserManager.exists(userId)) return null;
3239        flags = updateFlagsForPackage(flags, userId, packageName);
3240        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3241                false /* requireFullPermission */, false /* checkShell */, "get package info");
3242        // reader
3243        synchronized (mPackages) {
3244            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3245            PackageParser.Package p = null;
3246            if (matchFactoryOnly) {
3247                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3248                if (ps != null) {
3249                    return generatePackageInfo(ps, flags, userId);
3250                }
3251            }
3252            if (p == null) {
3253                p = mPackages.get(packageName);
3254                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3255                    return null;
3256                }
3257            }
3258            if (DEBUG_PACKAGE_INFO)
3259                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3260            if (p != null) {
3261                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3262            }
3263            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3264                final PackageSetting ps = mSettings.mPackages.get(packageName);
3265                return generatePackageInfo(ps, flags, userId);
3266            }
3267        }
3268        return null;
3269    }
3270
3271    @Override
3272    public String[] currentToCanonicalPackageNames(String[] names) {
3273        String[] out = new String[names.length];
3274        // reader
3275        synchronized (mPackages) {
3276            for (int i=names.length-1; i>=0; i--) {
3277                PackageSetting ps = mSettings.mPackages.get(names[i]);
3278                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3279            }
3280        }
3281        return out;
3282    }
3283
3284    @Override
3285    public String[] canonicalToCurrentPackageNames(String[] names) {
3286        String[] out = new String[names.length];
3287        // reader
3288        synchronized (mPackages) {
3289            for (int i=names.length-1; i>=0; i--) {
3290                String cur = mSettings.mRenamedPackages.get(names[i]);
3291                out[i] = cur != null ? cur : names[i];
3292            }
3293        }
3294        return out;
3295    }
3296
3297    @Override
3298    public int getPackageUid(String packageName, int flags, int userId) {
3299        if (!sUserManager.exists(userId)) return -1;
3300        flags = updateFlagsForPackage(flags, userId, packageName);
3301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3302                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3303
3304        // reader
3305        synchronized (mPackages) {
3306            final PackageParser.Package p = mPackages.get(packageName);
3307            if (p != null && p.isMatch(flags)) {
3308                return UserHandle.getUid(userId, p.applicationInfo.uid);
3309            }
3310            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3311                final PackageSetting ps = mSettings.mPackages.get(packageName);
3312                if (ps != null && ps.isMatch(flags)) {
3313                    return UserHandle.getUid(userId, ps.appId);
3314                }
3315            }
3316        }
3317
3318        return -1;
3319    }
3320
3321    @Override
3322    public int[] getPackageGids(String packageName, int flags, int userId) {
3323        if (!sUserManager.exists(userId)) return null;
3324        flags = updateFlagsForPackage(flags, userId, packageName);
3325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3326                false /* requireFullPermission */, false /* checkShell */,
3327                "getPackageGids");
3328
3329        // reader
3330        synchronized (mPackages) {
3331            final PackageParser.Package p = mPackages.get(packageName);
3332            if (p != null && p.isMatch(flags)) {
3333                PackageSetting ps = (PackageSetting) p.mExtras;
3334                return ps.getPermissionsState().computeGids(userId);
3335            }
3336            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3337                final PackageSetting ps = mSettings.mPackages.get(packageName);
3338                if (ps != null && ps.isMatch(flags)) {
3339                    return ps.getPermissionsState().computeGids(userId);
3340                }
3341            }
3342        }
3343
3344        return null;
3345    }
3346
3347    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3348        if (bp.perm != null) {
3349            return PackageParser.generatePermissionInfo(bp.perm, flags);
3350        }
3351        PermissionInfo pi = new PermissionInfo();
3352        pi.name = bp.name;
3353        pi.packageName = bp.sourcePackage;
3354        pi.nonLocalizedLabel = bp.name;
3355        pi.protectionLevel = bp.protectionLevel;
3356        return pi;
3357    }
3358
3359    @Override
3360    public PermissionInfo getPermissionInfo(String name, int flags) {
3361        // reader
3362        synchronized (mPackages) {
3363            final BasePermission p = mSettings.mPermissions.get(name);
3364            if (p != null) {
3365                return generatePermissionInfo(p, flags);
3366            }
3367            return null;
3368        }
3369    }
3370
3371    @Override
3372    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3373            int flags) {
3374        // reader
3375        synchronized (mPackages) {
3376            if (group != null && !mPermissionGroups.containsKey(group)) {
3377                // This is thrown as NameNotFoundException
3378                return null;
3379            }
3380
3381            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3382            for (BasePermission p : mSettings.mPermissions.values()) {
3383                if (group == null) {
3384                    if (p.perm == null || p.perm.info.group == null) {
3385                        out.add(generatePermissionInfo(p, flags));
3386                    }
3387                } else {
3388                    if (p.perm != null && group.equals(p.perm.info.group)) {
3389                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3390                    }
3391                }
3392            }
3393            return new ParceledListSlice<>(out);
3394        }
3395    }
3396
3397    @Override
3398    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3399        // reader
3400        synchronized (mPackages) {
3401            return PackageParser.generatePermissionGroupInfo(
3402                    mPermissionGroups.get(name), flags);
3403        }
3404    }
3405
3406    @Override
3407    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3408        // reader
3409        synchronized (mPackages) {
3410            final int N = mPermissionGroups.size();
3411            ArrayList<PermissionGroupInfo> out
3412                    = new ArrayList<PermissionGroupInfo>(N);
3413            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3414                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3415            }
3416            return new ParceledListSlice<>(out);
3417        }
3418    }
3419
3420    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3421            int userId) {
3422        if (!sUserManager.exists(userId)) return null;
3423        PackageSetting ps = mSettings.mPackages.get(packageName);
3424        if (ps != null) {
3425            if (ps.pkg == null) {
3426                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3427                if (pInfo != null) {
3428                    return pInfo.applicationInfo;
3429                }
3430                return null;
3431            }
3432            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3433                    ps.readUserState(userId), userId);
3434        }
3435        return null;
3436    }
3437
3438    @Override
3439    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3440        if (!sUserManager.exists(userId)) return null;
3441        flags = updateFlagsForApplication(flags, userId, packageName);
3442        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3443                false /* requireFullPermission */, false /* checkShell */, "get application info");
3444        // writer
3445        synchronized (mPackages) {
3446            PackageParser.Package p = mPackages.get(packageName);
3447            if (DEBUG_PACKAGE_INFO) Log.v(
3448                    TAG, "getApplicationInfo " + packageName
3449                    + ": " + p);
3450            if (p != null) {
3451                PackageSetting ps = mSettings.mPackages.get(packageName);
3452                if (ps == null) return null;
3453                // Note: isEnabledLP() does not apply here - always return info
3454                return PackageParser.generateApplicationInfo(
3455                        p, flags, ps.readUserState(userId), userId);
3456            }
3457            if ("android".equals(packageName)||"system".equals(packageName)) {
3458                return mAndroidApplication;
3459            }
3460            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3461                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3462            }
3463        }
3464        return null;
3465    }
3466
3467    @Override
3468    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3469            final IPackageDataObserver observer) {
3470        mContext.enforceCallingOrSelfPermission(
3471                android.Manifest.permission.CLEAR_APP_CACHE, null);
3472        // Queue up an async operation since clearing cache may take a little while.
3473        mHandler.post(new Runnable() {
3474            public void run() {
3475                mHandler.removeCallbacks(this);
3476                boolean success = true;
3477                synchronized (mInstallLock) {
3478                    try {
3479                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3480                    } catch (InstallerException e) {
3481                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3482                        success = false;
3483                    }
3484                }
3485                if (observer != null) {
3486                    try {
3487                        observer.onRemoveCompleted(null, success);
3488                    } catch (RemoteException e) {
3489                        Slog.w(TAG, "RemoveException when invoking call back");
3490                    }
3491                }
3492            }
3493        });
3494    }
3495
3496    @Override
3497    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3498            final IntentSender pi) {
3499        mContext.enforceCallingOrSelfPermission(
3500                android.Manifest.permission.CLEAR_APP_CACHE, null);
3501        // Queue up an async operation since clearing cache may take a little while.
3502        mHandler.post(new Runnable() {
3503            public void run() {
3504                mHandler.removeCallbacks(this);
3505                boolean success = true;
3506                synchronized (mInstallLock) {
3507                    try {
3508                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3509                    } catch (InstallerException e) {
3510                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3511                        success = false;
3512                    }
3513                }
3514                if(pi != null) {
3515                    try {
3516                        // Callback via pending intent
3517                        int code = success ? 1 : 0;
3518                        pi.sendIntent(null, code, null,
3519                                null, null);
3520                    } catch (SendIntentException e1) {
3521                        Slog.i(TAG, "Failed to send pending intent");
3522                    }
3523                }
3524            }
3525        });
3526    }
3527
3528    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3529        synchronized (mInstallLock) {
3530            try {
3531                mInstaller.freeCache(volumeUuid, freeStorageSize);
3532            } catch (InstallerException e) {
3533                throw new IOException("Failed to free enough space", e);
3534            }
3535        }
3536    }
3537
3538    /**
3539     * Update given flags based on encryption status of current user.
3540     */
3541    private int updateFlags(int flags, int userId) {
3542        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3543                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3544            // Caller expressed an explicit opinion about what encryption
3545            // aware/unaware components they want to see, so fall through and
3546            // give them what they want
3547        } else {
3548            // Caller expressed no opinion, so match based on user state
3549            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3550                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3551            } else {
3552                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3553            }
3554        }
3555        return flags;
3556    }
3557
3558    private UserManagerInternal getUserManagerInternal() {
3559        if (mUserManagerInternal == null) {
3560            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3561        }
3562        return mUserManagerInternal;
3563    }
3564
3565    /**
3566     * Update given flags when being used to request {@link PackageInfo}.
3567     */
3568    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3569        boolean triaged = true;
3570        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3571                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3572            // Caller is asking for component details, so they'd better be
3573            // asking for specific encryption matching behavior, or be triaged
3574            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3575                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3576                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3577                triaged = false;
3578            }
3579        }
3580        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3581                | PackageManager.MATCH_SYSTEM_ONLY
3582                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3583            triaged = false;
3584        }
3585        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3586            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3587                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3588        }
3589        return updateFlags(flags, userId);
3590    }
3591
3592    /**
3593     * Update given flags when being used to request {@link ApplicationInfo}.
3594     */
3595    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3596        return updateFlagsForPackage(flags, userId, cookie);
3597    }
3598
3599    /**
3600     * Update given flags when being used to request {@link ComponentInfo}.
3601     */
3602    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3603        if (cookie instanceof Intent) {
3604            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3605                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3606            }
3607        }
3608
3609        boolean triaged = true;
3610        // Caller is asking for component details, so they'd better be
3611        // asking for specific encryption matching behavior, or be triaged
3612        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3613                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3614                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3615            triaged = false;
3616        }
3617        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3618            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3619                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3620        }
3621
3622        return updateFlags(flags, userId);
3623    }
3624
3625    /**
3626     * Update given flags when being used to request {@link ResolveInfo}.
3627     */
3628    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3629        // Safe mode means we shouldn't match any third-party components
3630        if (mSafeMode) {
3631            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3632        }
3633
3634        return updateFlagsForComponent(flags, userId, cookie);
3635    }
3636
3637    @Override
3638    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3639        if (!sUserManager.exists(userId)) return null;
3640        flags = updateFlagsForComponent(flags, userId, component);
3641        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3642                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3643        synchronized (mPackages) {
3644            PackageParser.Activity a = mActivities.mActivities.get(component);
3645
3646            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3647            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3648                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3649                if (ps == null) return null;
3650                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3651                        userId);
3652            }
3653            if (mResolveComponentName.equals(component)) {
3654                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3655                        new PackageUserState(), userId);
3656            }
3657        }
3658        return null;
3659    }
3660
3661    @Override
3662    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3663            String resolvedType) {
3664        synchronized (mPackages) {
3665            if (component.equals(mResolveComponentName)) {
3666                // The resolver supports EVERYTHING!
3667                return true;
3668            }
3669            PackageParser.Activity a = mActivities.mActivities.get(component);
3670            if (a == null) {
3671                return false;
3672            }
3673            for (int i=0; i<a.intents.size(); i++) {
3674                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3675                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3676                    return true;
3677                }
3678            }
3679            return false;
3680        }
3681    }
3682
3683    @Override
3684    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3685        if (!sUserManager.exists(userId)) return null;
3686        flags = updateFlagsForComponent(flags, userId, component);
3687        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3688                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3689        synchronized (mPackages) {
3690            PackageParser.Activity a = mReceivers.mActivities.get(component);
3691            if (DEBUG_PACKAGE_INFO) Log.v(
3692                TAG, "getReceiverInfo " + component + ": " + a);
3693            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3694                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3695                if (ps == null) return null;
3696                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3697                        userId);
3698            }
3699        }
3700        return null;
3701    }
3702
3703    @Override
3704    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3705        if (!sUserManager.exists(userId)) return null;
3706        flags = updateFlagsForComponent(flags, userId, component);
3707        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3708                false /* requireFullPermission */, false /* checkShell */, "get service info");
3709        synchronized (mPackages) {
3710            PackageParser.Service s = mServices.mServices.get(component);
3711            if (DEBUG_PACKAGE_INFO) Log.v(
3712                TAG, "getServiceInfo " + component + ": " + s);
3713            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3714                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3715                if (ps == null) return null;
3716                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3717                        userId);
3718            }
3719        }
3720        return null;
3721    }
3722
3723    @Override
3724    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3725        if (!sUserManager.exists(userId)) return null;
3726        flags = updateFlagsForComponent(flags, userId, component);
3727        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3728                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3729        synchronized (mPackages) {
3730            PackageParser.Provider p = mProviders.mProviders.get(component);
3731            if (DEBUG_PACKAGE_INFO) Log.v(
3732                TAG, "getProviderInfo " + component + ": " + p);
3733            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3734                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3735                if (ps == null) return null;
3736                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3737                        userId);
3738            }
3739        }
3740        return null;
3741    }
3742
3743    @Override
3744    public String[] getSystemSharedLibraryNames() {
3745        Set<String> libSet;
3746        synchronized (mPackages) {
3747            libSet = mSharedLibraries.keySet();
3748            int size = libSet.size();
3749            if (size > 0) {
3750                String[] libs = new String[size];
3751                libSet.toArray(libs);
3752                return libs;
3753            }
3754        }
3755        return null;
3756    }
3757
3758    @Override
3759    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3760        synchronized (mPackages) {
3761            return mServicesSystemSharedLibraryPackageName;
3762        }
3763    }
3764
3765    @Override
3766    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3767        synchronized (mPackages) {
3768            return mSharedSystemSharedLibraryPackageName;
3769        }
3770    }
3771
3772    @Override
3773    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3774        synchronized (mPackages) {
3775            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3776
3777            final FeatureInfo fi = new FeatureInfo();
3778            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3779                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3780            res.add(fi);
3781
3782            return new ParceledListSlice<>(res);
3783        }
3784    }
3785
3786    @Override
3787    public boolean hasSystemFeature(String name, int version) {
3788        synchronized (mPackages) {
3789            final FeatureInfo feat = mAvailableFeatures.get(name);
3790            if (feat == null) {
3791                return false;
3792            } else {
3793                return feat.version >= version;
3794            }
3795        }
3796    }
3797
3798    @Override
3799    public int checkPermission(String permName, String pkgName, int userId) {
3800        if (!sUserManager.exists(userId)) {
3801            return PackageManager.PERMISSION_DENIED;
3802        }
3803
3804        synchronized (mPackages) {
3805            final PackageParser.Package p = mPackages.get(pkgName);
3806            if (p != null && p.mExtras != null) {
3807                final PackageSetting ps = (PackageSetting) p.mExtras;
3808                final PermissionsState permissionsState = ps.getPermissionsState();
3809                if (permissionsState.hasPermission(permName, userId)) {
3810                    return PackageManager.PERMISSION_GRANTED;
3811                }
3812                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3813                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3814                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3815                    return PackageManager.PERMISSION_GRANTED;
3816                }
3817            }
3818        }
3819
3820        return PackageManager.PERMISSION_DENIED;
3821    }
3822
3823    @Override
3824    public int checkUidPermission(String permName, int uid) {
3825        final int userId = UserHandle.getUserId(uid);
3826
3827        if (!sUserManager.exists(userId)) {
3828            return PackageManager.PERMISSION_DENIED;
3829        }
3830
3831        synchronized (mPackages) {
3832            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3833            if (obj != null) {
3834                final SettingBase ps = (SettingBase) obj;
3835                final PermissionsState permissionsState = ps.getPermissionsState();
3836                if (permissionsState.hasPermission(permName, userId)) {
3837                    return PackageManager.PERMISSION_GRANTED;
3838                }
3839                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3840                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3841                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3842                    return PackageManager.PERMISSION_GRANTED;
3843                }
3844            } else {
3845                ArraySet<String> perms = mSystemPermissions.get(uid);
3846                if (perms != null) {
3847                    if (perms.contains(permName)) {
3848                        return PackageManager.PERMISSION_GRANTED;
3849                    }
3850                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3851                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3852                        return PackageManager.PERMISSION_GRANTED;
3853                    }
3854                }
3855            }
3856        }
3857
3858        return PackageManager.PERMISSION_DENIED;
3859    }
3860
3861    @Override
3862    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3863        if (UserHandle.getCallingUserId() != userId) {
3864            mContext.enforceCallingPermission(
3865                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3866                    "isPermissionRevokedByPolicy for user " + userId);
3867        }
3868
3869        if (checkPermission(permission, packageName, userId)
3870                == PackageManager.PERMISSION_GRANTED) {
3871            return false;
3872        }
3873
3874        final long identity = Binder.clearCallingIdentity();
3875        try {
3876            final int flags = getPermissionFlags(permission, packageName, userId);
3877            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3878        } finally {
3879            Binder.restoreCallingIdentity(identity);
3880        }
3881    }
3882
3883    @Override
3884    public String getPermissionControllerPackageName() {
3885        synchronized (mPackages) {
3886            return mRequiredInstallerPackage;
3887        }
3888    }
3889
3890    /**
3891     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3892     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3893     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3894     * @param message the message to log on security exception
3895     */
3896    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3897            boolean checkShell, String message) {
3898        if (userId < 0) {
3899            throw new IllegalArgumentException("Invalid userId " + userId);
3900        }
3901        if (checkShell) {
3902            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3903        }
3904        if (userId == UserHandle.getUserId(callingUid)) return;
3905        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3906            if (requireFullPermission) {
3907                mContext.enforceCallingOrSelfPermission(
3908                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3909            } else {
3910                try {
3911                    mContext.enforceCallingOrSelfPermission(
3912                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3913                } catch (SecurityException se) {
3914                    mContext.enforceCallingOrSelfPermission(
3915                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3916                }
3917            }
3918        }
3919    }
3920
3921    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3922        if (callingUid == Process.SHELL_UID) {
3923            if (userHandle >= 0
3924                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3925                throw new SecurityException("Shell does not have permission to access user "
3926                        + userHandle);
3927            } else if (userHandle < 0) {
3928                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3929                        + Debug.getCallers(3));
3930            }
3931        }
3932    }
3933
3934    private BasePermission findPermissionTreeLP(String permName) {
3935        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3936            if (permName.startsWith(bp.name) &&
3937                    permName.length() > bp.name.length() &&
3938                    permName.charAt(bp.name.length()) == '.') {
3939                return bp;
3940            }
3941        }
3942        return null;
3943    }
3944
3945    private BasePermission checkPermissionTreeLP(String permName) {
3946        if (permName != null) {
3947            BasePermission bp = findPermissionTreeLP(permName);
3948            if (bp != null) {
3949                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3950                    return bp;
3951                }
3952                throw new SecurityException("Calling uid "
3953                        + Binder.getCallingUid()
3954                        + " is not allowed to add to permission tree "
3955                        + bp.name + " owned by uid " + bp.uid);
3956            }
3957        }
3958        throw new SecurityException("No permission tree found for " + permName);
3959    }
3960
3961    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3962        if (s1 == null) {
3963            return s2 == null;
3964        }
3965        if (s2 == null) {
3966            return false;
3967        }
3968        if (s1.getClass() != s2.getClass()) {
3969            return false;
3970        }
3971        return s1.equals(s2);
3972    }
3973
3974    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3975        if (pi1.icon != pi2.icon) return false;
3976        if (pi1.logo != pi2.logo) return false;
3977        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3978        if (!compareStrings(pi1.name, pi2.name)) return false;
3979        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3980        // We'll take care of setting this one.
3981        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3982        // These are not currently stored in settings.
3983        //if (!compareStrings(pi1.group, pi2.group)) return false;
3984        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3985        //if (pi1.labelRes != pi2.labelRes) return false;
3986        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3987        return true;
3988    }
3989
3990    int permissionInfoFootprint(PermissionInfo info) {
3991        int size = info.name.length();
3992        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3993        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3994        return size;
3995    }
3996
3997    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3998        int size = 0;
3999        for (BasePermission perm : mSettings.mPermissions.values()) {
4000            if (perm.uid == tree.uid) {
4001                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4002            }
4003        }
4004        return size;
4005    }
4006
4007    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4008        // We calculate the max size of permissions defined by this uid and throw
4009        // if that plus the size of 'info' would exceed our stated maximum.
4010        if (tree.uid != Process.SYSTEM_UID) {
4011            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4012            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4013                throw new SecurityException("Permission tree size cap exceeded");
4014            }
4015        }
4016    }
4017
4018    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4019        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4020            throw new SecurityException("Label must be specified in permission");
4021        }
4022        BasePermission tree = checkPermissionTreeLP(info.name);
4023        BasePermission bp = mSettings.mPermissions.get(info.name);
4024        boolean added = bp == null;
4025        boolean changed = true;
4026        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4027        if (added) {
4028            enforcePermissionCapLocked(info, tree);
4029            bp = new BasePermission(info.name, tree.sourcePackage,
4030                    BasePermission.TYPE_DYNAMIC);
4031        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4032            throw new SecurityException(
4033                    "Not allowed to modify non-dynamic permission "
4034                    + info.name);
4035        } else {
4036            if (bp.protectionLevel == fixedLevel
4037                    && bp.perm.owner.equals(tree.perm.owner)
4038                    && bp.uid == tree.uid
4039                    && comparePermissionInfos(bp.perm.info, info)) {
4040                changed = false;
4041            }
4042        }
4043        bp.protectionLevel = fixedLevel;
4044        info = new PermissionInfo(info);
4045        info.protectionLevel = fixedLevel;
4046        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4047        bp.perm.info.packageName = tree.perm.info.packageName;
4048        bp.uid = tree.uid;
4049        if (added) {
4050            mSettings.mPermissions.put(info.name, bp);
4051        }
4052        if (changed) {
4053            if (!async) {
4054                mSettings.writeLPr();
4055            } else {
4056                scheduleWriteSettingsLocked();
4057            }
4058        }
4059        return added;
4060    }
4061
4062    @Override
4063    public boolean addPermission(PermissionInfo info) {
4064        synchronized (mPackages) {
4065            return addPermissionLocked(info, false);
4066        }
4067    }
4068
4069    @Override
4070    public boolean addPermissionAsync(PermissionInfo info) {
4071        synchronized (mPackages) {
4072            return addPermissionLocked(info, true);
4073        }
4074    }
4075
4076    @Override
4077    public void removePermission(String name) {
4078        synchronized (mPackages) {
4079            checkPermissionTreeLP(name);
4080            BasePermission bp = mSettings.mPermissions.get(name);
4081            if (bp != null) {
4082                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4083                    throw new SecurityException(
4084                            "Not allowed to modify non-dynamic permission "
4085                            + name);
4086                }
4087                mSettings.mPermissions.remove(name);
4088                mSettings.writeLPr();
4089            }
4090        }
4091    }
4092
4093    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4094            BasePermission bp) {
4095        int index = pkg.requestedPermissions.indexOf(bp.name);
4096        if (index == -1) {
4097            throw new SecurityException("Package " + pkg.packageName
4098                    + " has not requested permission " + bp.name);
4099        }
4100        if (!bp.isRuntime() && !bp.isDevelopment()) {
4101            throw new SecurityException("Permission " + bp.name
4102                    + " is not a changeable permission type");
4103        }
4104    }
4105
4106    @Override
4107    public void grantRuntimePermission(String packageName, String name, final int userId) {
4108        if (!sUserManager.exists(userId)) {
4109            Log.e(TAG, "No such user:" + userId);
4110            return;
4111        }
4112
4113        mContext.enforceCallingOrSelfPermission(
4114                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4115                "grantRuntimePermission");
4116
4117        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4118                true /* requireFullPermission */, true /* checkShell */,
4119                "grantRuntimePermission");
4120
4121        final int uid;
4122        final SettingBase sb;
4123
4124        synchronized (mPackages) {
4125            final PackageParser.Package pkg = mPackages.get(packageName);
4126            if (pkg == null) {
4127                throw new IllegalArgumentException("Unknown package: " + packageName);
4128            }
4129
4130            final BasePermission bp = mSettings.mPermissions.get(name);
4131            if (bp == null) {
4132                throw new IllegalArgumentException("Unknown permission: " + name);
4133            }
4134
4135            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4136
4137            // If a permission review is required for legacy apps we represent
4138            // their permissions as always granted runtime ones since we need
4139            // to keep the review required permission flag per user while an
4140            // install permission's state is shared across all users.
4141            if (Build.PERMISSIONS_REVIEW_REQUIRED
4142                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4143                    && bp.isRuntime()) {
4144                return;
4145            }
4146
4147            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4148            sb = (SettingBase) pkg.mExtras;
4149            if (sb == null) {
4150                throw new IllegalArgumentException("Unknown package: " + packageName);
4151            }
4152
4153            final PermissionsState permissionsState = sb.getPermissionsState();
4154
4155            final int flags = permissionsState.getPermissionFlags(name, userId);
4156            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4157                throw new SecurityException("Cannot grant system fixed permission "
4158                        + name + " for package " + packageName);
4159            }
4160
4161            if (bp.isDevelopment()) {
4162                // Development permissions must be handled specially, since they are not
4163                // normal runtime permissions.  For now they apply to all users.
4164                if (permissionsState.grantInstallPermission(bp) !=
4165                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4166                    scheduleWriteSettingsLocked();
4167                }
4168                return;
4169            }
4170
4171            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4172                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4173                return;
4174            }
4175
4176            final int result = permissionsState.grantRuntimePermission(bp, userId);
4177            switch (result) {
4178                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4179                    return;
4180                }
4181
4182                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4183                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4184                    mHandler.post(new Runnable() {
4185                        @Override
4186                        public void run() {
4187                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4188                        }
4189                    });
4190                }
4191                break;
4192            }
4193
4194            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4195
4196            // Not critical if that is lost - app has to request again.
4197            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4198        }
4199
4200        // Only need to do this if user is initialized. Otherwise it's a new user
4201        // and there are no processes running as the user yet and there's no need
4202        // to make an expensive call to remount processes for the changed permissions.
4203        if (READ_EXTERNAL_STORAGE.equals(name)
4204                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4205            final long token = Binder.clearCallingIdentity();
4206            try {
4207                if (sUserManager.isInitialized(userId)) {
4208                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4209                            MountServiceInternal.class);
4210                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4211                }
4212            } finally {
4213                Binder.restoreCallingIdentity(token);
4214            }
4215        }
4216    }
4217
4218    @Override
4219    public void revokeRuntimePermission(String packageName, String name, int userId) {
4220        if (!sUserManager.exists(userId)) {
4221            Log.e(TAG, "No such user:" + userId);
4222            return;
4223        }
4224
4225        mContext.enforceCallingOrSelfPermission(
4226                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4227                "revokeRuntimePermission");
4228
4229        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4230                true /* requireFullPermission */, true /* checkShell */,
4231                "revokeRuntimePermission");
4232
4233        final int appId;
4234
4235        synchronized (mPackages) {
4236            final PackageParser.Package pkg = mPackages.get(packageName);
4237            if (pkg == null) {
4238                throw new IllegalArgumentException("Unknown package: " + packageName);
4239            }
4240
4241            final BasePermission bp = mSettings.mPermissions.get(name);
4242            if (bp == null) {
4243                throw new IllegalArgumentException("Unknown permission: " + name);
4244            }
4245
4246            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4247
4248            // If a permission review is required for legacy apps we represent
4249            // their permissions as always granted runtime ones since we need
4250            // to keep the review required permission flag per user while an
4251            // install permission's state is shared across all users.
4252            if (Build.PERMISSIONS_REVIEW_REQUIRED
4253                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4254                    && bp.isRuntime()) {
4255                return;
4256            }
4257
4258            SettingBase sb = (SettingBase) pkg.mExtras;
4259            if (sb == null) {
4260                throw new IllegalArgumentException("Unknown package: " + packageName);
4261            }
4262
4263            final PermissionsState permissionsState = sb.getPermissionsState();
4264
4265            final int flags = permissionsState.getPermissionFlags(name, userId);
4266            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4267                throw new SecurityException("Cannot revoke system fixed permission "
4268                        + name + " for package " + packageName);
4269            }
4270
4271            if (bp.isDevelopment()) {
4272                // Development permissions must be handled specially, since they are not
4273                // normal runtime permissions.  For now they apply to all users.
4274                if (permissionsState.revokeInstallPermission(bp) !=
4275                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4276                    scheduleWriteSettingsLocked();
4277                }
4278                return;
4279            }
4280
4281            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4282                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4283                return;
4284            }
4285
4286            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4287
4288            // Critical, after this call app should never have the permission.
4289            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4290
4291            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4292        }
4293
4294        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4295    }
4296
4297    @Override
4298    public void resetRuntimePermissions() {
4299        mContext.enforceCallingOrSelfPermission(
4300                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4301                "revokeRuntimePermission");
4302
4303        int callingUid = Binder.getCallingUid();
4304        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4305            mContext.enforceCallingOrSelfPermission(
4306                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4307                    "resetRuntimePermissions");
4308        }
4309
4310        synchronized (mPackages) {
4311            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4312            for (int userId : UserManagerService.getInstance().getUserIds()) {
4313                final int packageCount = mPackages.size();
4314                for (int i = 0; i < packageCount; i++) {
4315                    PackageParser.Package pkg = mPackages.valueAt(i);
4316                    if (!(pkg.mExtras instanceof PackageSetting)) {
4317                        continue;
4318                    }
4319                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4320                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4321                }
4322            }
4323        }
4324    }
4325
4326    @Override
4327    public int getPermissionFlags(String name, String packageName, int userId) {
4328        if (!sUserManager.exists(userId)) {
4329            return 0;
4330        }
4331
4332        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4333
4334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4335                true /* requireFullPermission */, false /* checkShell */,
4336                "getPermissionFlags");
4337
4338        synchronized (mPackages) {
4339            final PackageParser.Package pkg = mPackages.get(packageName);
4340            if (pkg == null) {
4341                return 0;
4342            }
4343
4344            final BasePermission bp = mSettings.mPermissions.get(name);
4345            if (bp == null) {
4346                return 0;
4347            }
4348
4349            SettingBase sb = (SettingBase) pkg.mExtras;
4350            if (sb == null) {
4351                return 0;
4352            }
4353
4354            PermissionsState permissionsState = sb.getPermissionsState();
4355            return permissionsState.getPermissionFlags(name, userId);
4356        }
4357    }
4358
4359    @Override
4360    public void updatePermissionFlags(String name, String packageName, int flagMask,
4361            int flagValues, int userId) {
4362        if (!sUserManager.exists(userId)) {
4363            return;
4364        }
4365
4366        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4367
4368        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4369                true /* requireFullPermission */, true /* checkShell */,
4370                "updatePermissionFlags");
4371
4372        // Only the system can change these flags and nothing else.
4373        if (getCallingUid() != Process.SYSTEM_UID) {
4374            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4375            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4376            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4377            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4378            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4379        }
4380
4381        synchronized (mPackages) {
4382            final PackageParser.Package pkg = mPackages.get(packageName);
4383            if (pkg == null) {
4384                throw new IllegalArgumentException("Unknown package: " + packageName);
4385            }
4386
4387            final BasePermission bp = mSettings.mPermissions.get(name);
4388            if (bp == null) {
4389                throw new IllegalArgumentException("Unknown permission: " + name);
4390            }
4391
4392            SettingBase sb = (SettingBase) pkg.mExtras;
4393            if (sb == null) {
4394                throw new IllegalArgumentException("Unknown package: " + packageName);
4395            }
4396
4397            PermissionsState permissionsState = sb.getPermissionsState();
4398
4399            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4400
4401            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4402                // Install and runtime permissions are stored in different places,
4403                // so figure out what permission changed and persist the change.
4404                if (permissionsState.getInstallPermissionState(name) != null) {
4405                    scheduleWriteSettingsLocked();
4406                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4407                        || hadState) {
4408                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4409                }
4410            }
4411        }
4412    }
4413
4414    /**
4415     * Update the permission flags for all packages and runtime permissions of a user in order
4416     * to allow device or profile owner to remove POLICY_FIXED.
4417     */
4418    @Override
4419    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4420        if (!sUserManager.exists(userId)) {
4421            return;
4422        }
4423
4424        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4425
4426        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4427                true /* requireFullPermission */, true /* checkShell */,
4428                "updatePermissionFlagsForAllApps");
4429
4430        // Only the system can change system fixed flags.
4431        if (getCallingUid() != Process.SYSTEM_UID) {
4432            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4433            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4434        }
4435
4436        synchronized (mPackages) {
4437            boolean changed = false;
4438            final int packageCount = mPackages.size();
4439            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4440                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4441                SettingBase sb = (SettingBase) pkg.mExtras;
4442                if (sb == null) {
4443                    continue;
4444                }
4445                PermissionsState permissionsState = sb.getPermissionsState();
4446                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4447                        userId, flagMask, flagValues);
4448            }
4449            if (changed) {
4450                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4451            }
4452        }
4453    }
4454
4455    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4456        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4457                != PackageManager.PERMISSION_GRANTED
4458            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4459                != PackageManager.PERMISSION_GRANTED) {
4460            throw new SecurityException(message + " requires "
4461                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4462                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4463        }
4464    }
4465
4466    @Override
4467    public boolean shouldShowRequestPermissionRationale(String permissionName,
4468            String packageName, int userId) {
4469        if (UserHandle.getCallingUserId() != userId) {
4470            mContext.enforceCallingPermission(
4471                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4472                    "canShowRequestPermissionRationale for user " + userId);
4473        }
4474
4475        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4476        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4477            return false;
4478        }
4479
4480        if (checkPermission(permissionName, packageName, userId)
4481                == PackageManager.PERMISSION_GRANTED) {
4482            return false;
4483        }
4484
4485        final int flags;
4486
4487        final long identity = Binder.clearCallingIdentity();
4488        try {
4489            flags = getPermissionFlags(permissionName,
4490                    packageName, userId);
4491        } finally {
4492            Binder.restoreCallingIdentity(identity);
4493        }
4494
4495        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4496                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4497                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4498
4499        if ((flags & fixedFlags) != 0) {
4500            return false;
4501        }
4502
4503        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4504    }
4505
4506    @Override
4507    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4508        mContext.enforceCallingOrSelfPermission(
4509                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4510                "addOnPermissionsChangeListener");
4511
4512        synchronized (mPackages) {
4513            mOnPermissionChangeListeners.addListenerLocked(listener);
4514        }
4515    }
4516
4517    @Override
4518    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4519        synchronized (mPackages) {
4520            mOnPermissionChangeListeners.removeListenerLocked(listener);
4521        }
4522    }
4523
4524    @Override
4525    public boolean isProtectedBroadcast(String actionName) {
4526        synchronized (mPackages) {
4527            if (mProtectedBroadcasts.contains(actionName)) {
4528                return true;
4529            } else if (actionName != null) {
4530                // TODO: remove these terrible hacks
4531                if (actionName.startsWith("android.net.netmon.lingerExpired")
4532                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4533                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4534                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4535                    return true;
4536                }
4537            }
4538        }
4539        return false;
4540    }
4541
4542    @Override
4543    public int checkSignatures(String pkg1, String pkg2) {
4544        synchronized (mPackages) {
4545            final PackageParser.Package p1 = mPackages.get(pkg1);
4546            final PackageParser.Package p2 = mPackages.get(pkg2);
4547            if (p1 == null || p1.mExtras == null
4548                    || p2 == null || p2.mExtras == null) {
4549                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4550            }
4551            return compareSignatures(p1.mSignatures, p2.mSignatures);
4552        }
4553    }
4554
4555    @Override
4556    public int checkUidSignatures(int uid1, int uid2) {
4557        // Map to base uids.
4558        uid1 = UserHandle.getAppId(uid1);
4559        uid2 = UserHandle.getAppId(uid2);
4560        // reader
4561        synchronized (mPackages) {
4562            Signature[] s1;
4563            Signature[] s2;
4564            Object obj = mSettings.getUserIdLPr(uid1);
4565            if (obj != null) {
4566                if (obj instanceof SharedUserSetting) {
4567                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4568                } else if (obj instanceof PackageSetting) {
4569                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4570                } else {
4571                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4572                }
4573            } else {
4574                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4575            }
4576            obj = mSettings.getUserIdLPr(uid2);
4577            if (obj != null) {
4578                if (obj instanceof SharedUserSetting) {
4579                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4580                } else if (obj instanceof PackageSetting) {
4581                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4582                } else {
4583                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4584                }
4585            } else {
4586                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4587            }
4588            return compareSignatures(s1, s2);
4589        }
4590    }
4591
4592    /**
4593     * This method should typically only be used when granting or revoking
4594     * permissions, since the app may immediately restart after this call.
4595     * <p>
4596     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4597     * guard your work against the app being relaunched.
4598     */
4599    private void killUid(int appId, int userId, String reason) {
4600        final long identity = Binder.clearCallingIdentity();
4601        try {
4602            IActivityManager am = ActivityManagerNative.getDefault();
4603            if (am != null) {
4604                try {
4605                    am.killUid(appId, userId, reason);
4606                } catch (RemoteException e) {
4607                    /* ignore - same process */
4608                }
4609            }
4610        } finally {
4611            Binder.restoreCallingIdentity(identity);
4612        }
4613    }
4614
4615    /**
4616     * Compares two sets of signatures. Returns:
4617     * <br />
4618     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4619     * <br />
4620     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4621     * <br />
4622     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4623     * <br />
4624     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4625     * <br />
4626     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4627     */
4628    static int compareSignatures(Signature[] s1, Signature[] s2) {
4629        if (s1 == null) {
4630            return s2 == null
4631                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4632                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4633        }
4634
4635        if (s2 == null) {
4636            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4637        }
4638
4639        if (s1.length != s2.length) {
4640            return PackageManager.SIGNATURE_NO_MATCH;
4641        }
4642
4643        // Since both signature sets are of size 1, we can compare without HashSets.
4644        if (s1.length == 1) {
4645            return s1[0].equals(s2[0]) ?
4646                    PackageManager.SIGNATURE_MATCH :
4647                    PackageManager.SIGNATURE_NO_MATCH;
4648        }
4649
4650        ArraySet<Signature> set1 = new ArraySet<Signature>();
4651        for (Signature sig : s1) {
4652            set1.add(sig);
4653        }
4654        ArraySet<Signature> set2 = new ArraySet<Signature>();
4655        for (Signature sig : s2) {
4656            set2.add(sig);
4657        }
4658        // Make sure s2 contains all signatures in s1.
4659        if (set1.equals(set2)) {
4660            return PackageManager.SIGNATURE_MATCH;
4661        }
4662        return PackageManager.SIGNATURE_NO_MATCH;
4663    }
4664
4665    /**
4666     * If the database version for this type of package (internal storage or
4667     * external storage) is less than the version where package signatures
4668     * were updated, return true.
4669     */
4670    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4671        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4672        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4673    }
4674
4675    /**
4676     * Used for backward compatibility to make sure any packages with
4677     * certificate chains get upgraded to the new style. {@code existingSigs}
4678     * will be in the old format (since they were stored on disk from before the
4679     * system upgrade) and {@code scannedSigs} will be in the newer format.
4680     */
4681    private int compareSignaturesCompat(PackageSignatures existingSigs,
4682            PackageParser.Package scannedPkg) {
4683        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4684            return PackageManager.SIGNATURE_NO_MATCH;
4685        }
4686
4687        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4688        for (Signature sig : existingSigs.mSignatures) {
4689            existingSet.add(sig);
4690        }
4691        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4692        for (Signature sig : scannedPkg.mSignatures) {
4693            try {
4694                Signature[] chainSignatures = sig.getChainSignatures();
4695                for (Signature chainSig : chainSignatures) {
4696                    scannedCompatSet.add(chainSig);
4697                }
4698            } catch (CertificateEncodingException e) {
4699                scannedCompatSet.add(sig);
4700            }
4701        }
4702        /*
4703         * Make sure the expanded scanned set contains all signatures in the
4704         * existing one.
4705         */
4706        if (scannedCompatSet.equals(existingSet)) {
4707            // Migrate the old signatures to the new scheme.
4708            existingSigs.assignSignatures(scannedPkg.mSignatures);
4709            // The new KeySets will be re-added later in the scanning process.
4710            synchronized (mPackages) {
4711                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4712            }
4713            return PackageManager.SIGNATURE_MATCH;
4714        }
4715        return PackageManager.SIGNATURE_NO_MATCH;
4716    }
4717
4718    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4719        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4720        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4721    }
4722
4723    private int compareSignaturesRecover(PackageSignatures existingSigs,
4724            PackageParser.Package scannedPkg) {
4725        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4726            return PackageManager.SIGNATURE_NO_MATCH;
4727        }
4728
4729        String msg = null;
4730        try {
4731            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4732                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4733                        + scannedPkg.packageName);
4734                return PackageManager.SIGNATURE_MATCH;
4735            }
4736        } catch (CertificateException e) {
4737            msg = e.getMessage();
4738        }
4739
4740        logCriticalInfo(Log.INFO,
4741                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4742        return PackageManager.SIGNATURE_NO_MATCH;
4743    }
4744
4745    @Override
4746    public List<String> getAllPackages() {
4747        synchronized (mPackages) {
4748            return new ArrayList<String>(mPackages.keySet());
4749        }
4750    }
4751
4752    @Override
4753    public String[] getPackagesForUid(int uid) {
4754        uid = UserHandle.getAppId(uid);
4755        // reader
4756        synchronized (mPackages) {
4757            Object obj = mSettings.getUserIdLPr(uid);
4758            if (obj instanceof SharedUserSetting) {
4759                final SharedUserSetting sus = (SharedUserSetting) obj;
4760                final int N = sus.packages.size();
4761                final String[] res = new String[N];
4762                final Iterator<PackageSetting> it = sus.packages.iterator();
4763                int i = 0;
4764                while (it.hasNext()) {
4765                    res[i++] = it.next().name;
4766                }
4767                return res;
4768            } else if (obj instanceof PackageSetting) {
4769                final PackageSetting ps = (PackageSetting) obj;
4770                return new String[] { ps.name };
4771            }
4772        }
4773        return null;
4774    }
4775
4776    @Override
4777    public String getNameForUid(int uid) {
4778        // reader
4779        synchronized (mPackages) {
4780            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4781            if (obj instanceof SharedUserSetting) {
4782                final SharedUserSetting sus = (SharedUserSetting) obj;
4783                return sus.name + ":" + sus.userId;
4784            } else if (obj instanceof PackageSetting) {
4785                final PackageSetting ps = (PackageSetting) obj;
4786                return ps.name;
4787            }
4788        }
4789        return null;
4790    }
4791
4792    @Override
4793    public int getUidForSharedUser(String sharedUserName) {
4794        if(sharedUserName == null) {
4795            return -1;
4796        }
4797        // reader
4798        synchronized (mPackages) {
4799            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4800            if (suid == null) {
4801                return -1;
4802            }
4803            return suid.userId;
4804        }
4805    }
4806
4807    @Override
4808    public int getFlagsForUid(int uid) {
4809        synchronized (mPackages) {
4810            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4811            if (obj instanceof SharedUserSetting) {
4812                final SharedUserSetting sus = (SharedUserSetting) obj;
4813                return sus.pkgFlags;
4814            } else if (obj instanceof PackageSetting) {
4815                final PackageSetting ps = (PackageSetting) obj;
4816                return ps.pkgFlags;
4817            }
4818        }
4819        return 0;
4820    }
4821
4822    @Override
4823    public int getPrivateFlagsForUid(int uid) {
4824        synchronized (mPackages) {
4825            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4826            if (obj instanceof SharedUserSetting) {
4827                final SharedUserSetting sus = (SharedUserSetting) obj;
4828                return sus.pkgPrivateFlags;
4829            } else if (obj instanceof PackageSetting) {
4830                final PackageSetting ps = (PackageSetting) obj;
4831                return ps.pkgPrivateFlags;
4832            }
4833        }
4834        return 0;
4835    }
4836
4837    @Override
4838    public boolean isUidPrivileged(int uid) {
4839        uid = UserHandle.getAppId(uid);
4840        // reader
4841        synchronized (mPackages) {
4842            Object obj = mSettings.getUserIdLPr(uid);
4843            if (obj instanceof SharedUserSetting) {
4844                final SharedUserSetting sus = (SharedUserSetting) obj;
4845                final Iterator<PackageSetting> it = sus.packages.iterator();
4846                while (it.hasNext()) {
4847                    if (it.next().isPrivileged()) {
4848                        return true;
4849                    }
4850                }
4851            } else if (obj instanceof PackageSetting) {
4852                final PackageSetting ps = (PackageSetting) obj;
4853                return ps.isPrivileged();
4854            }
4855        }
4856        return false;
4857    }
4858
4859    @Override
4860    public String[] getAppOpPermissionPackages(String permissionName) {
4861        synchronized (mPackages) {
4862            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4863            if (pkgs == null) {
4864                return null;
4865            }
4866            return pkgs.toArray(new String[pkgs.size()]);
4867        }
4868    }
4869
4870    @Override
4871    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4872            int flags, int userId) {
4873        try {
4874            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4875
4876            if (!sUserManager.exists(userId)) return null;
4877            flags = updateFlagsForResolve(flags, userId, intent);
4878            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4879                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4880
4881            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4882            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4883                    flags, userId);
4884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4885
4886            final ResolveInfo bestChoice =
4887                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4888
4889            if (isEphemeralAllowed(intent, query, userId)) {
4890                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4891                final EphemeralResolveInfo ai =
4892                        getEphemeralResolveInfo(intent, resolvedType, userId);
4893                if (ai != null) {
4894                    if (DEBUG_EPHEMERAL) {
4895                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4896                    }
4897                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4898                    bestChoice.ephemeralResolveInfo = ai;
4899                }
4900                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4901            }
4902            return bestChoice;
4903        } finally {
4904            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4905        }
4906    }
4907
4908    @Override
4909    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4910            IntentFilter filter, int match, ComponentName activity) {
4911        final int userId = UserHandle.getCallingUserId();
4912        if (DEBUG_PREFERRED) {
4913            Log.v(TAG, "setLastChosenActivity intent=" + intent
4914                + " resolvedType=" + resolvedType
4915                + " flags=" + flags
4916                + " filter=" + filter
4917                + " match=" + match
4918                + " activity=" + activity);
4919            filter.dump(new PrintStreamPrinter(System.out), "    ");
4920        }
4921        intent.setComponent(null);
4922        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4923                userId);
4924        // Find any earlier preferred or last chosen entries and nuke them
4925        findPreferredActivity(intent, resolvedType,
4926                flags, query, 0, false, true, false, userId);
4927        // Add the new activity as the last chosen for this filter
4928        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4929                "Setting last chosen");
4930    }
4931
4932    @Override
4933    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4934        final int userId = UserHandle.getCallingUserId();
4935        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4936        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4937                userId);
4938        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4939                false, false, false, userId);
4940    }
4941
4942
4943    private boolean isEphemeralAllowed(
4944            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4945        // Short circuit and return early if possible.
4946        if (DISABLE_EPHEMERAL_APPS) {
4947            return false;
4948        }
4949        final int callingUser = UserHandle.getCallingUserId();
4950        if (callingUser != UserHandle.USER_SYSTEM) {
4951            return false;
4952        }
4953        if (mEphemeralResolverConnection == null) {
4954            return false;
4955        }
4956        if (intent.getComponent() != null) {
4957            return false;
4958        }
4959        if (intent.getPackage() != null) {
4960            return false;
4961        }
4962        final boolean isWebUri = hasWebURI(intent);
4963        if (!isWebUri) {
4964            return false;
4965        }
4966        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4967        synchronized (mPackages) {
4968            final int count = resolvedActivites.size();
4969            for (int n = 0; n < count; n++) {
4970                ResolveInfo info = resolvedActivites.get(n);
4971                String packageName = info.activityInfo.packageName;
4972                PackageSetting ps = mSettings.mPackages.get(packageName);
4973                if (ps != null) {
4974                    // Try to get the status from User settings first
4975                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4976                    int status = (int) (packedStatus >> 32);
4977                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4978                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4979                        if (DEBUG_EPHEMERAL) {
4980                            Slog.v(TAG, "DENY ephemeral apps;"
4981                                + " pkg: " + packageName + ", status: " + status);
4982                        }
4983                        return false;
4984                    }
4985                }
4986            }
4987        }
4988        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4989        return true;
4990    }
4991
4992    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4993            int userId) {
4994        MessageDigest digest = null;
4995        try {
4996            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4997        } catch (NoSuchAlgorithmException e) {
4998            // If we can't create a digest, ignore ephemeral apps.
4999            return null;
5000        }
5001
5002        final byte[] hostBytes = intent.getData().getHost().getBytes();
5003        final byte[] digestBytes = digest.digest(hostBytes);
5004        int shaPrefix =
5005                (digestBytes[0] & 0xFF) << 24
5006                | (digestBytes[1] & 0xFF) << 16
5007                | (digestBytes[2] & 0xFF) << 8
5008                | (digestBytes[3] & 0xFF) << 0;
5009        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5010                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5011        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5012            // No hash prefix match; there are no ephemeral apps for this domain.
5013            return null;
5014        }
5015        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5016            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5017            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5018                continue;
5019            }
5020            final List<IntentFilter> filters = ephemeralApplication.getFilters();
5021            // No filters; this should never happen.
5022            if (filters.isEmpty()) {
5023                continue;
5024            }
5025            // We have a domain match; resolve the filters to see if anything matches.
5026            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5027            for (int j = filters.size() - 1; j >= 0; --j) {
5028                final EphemeralResolveIntentInfo intentInfo =
5029                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5030                ephemeralResolver.addFilter(intentInfo);
5031            }
5032            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5033                    intent, resolvedType, false /*defaultOnly*/, userId);
5034            if (!matchedResolveInfoList.isEmpty()) {
5035                return matchedResolveInfoList.get(0);
5036            }
5037        }
5038        // Hash or filter mis-match; no ephemeral apps for this domain.
5039        return null;
5040    }
5041
5042    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5043            int flags, List<ResolveInfo> query, int userId) {
5044        if (query != null) {
5045            final int N = query.size();
5046            if (N == 1) {
5047                return query.get(0);
5048            } else if (N > 1) {
5049                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5050                // If there is more than one activity with the same priority,
5051                // then let the user decide between them.
5052                ResolveInfo r0 = query.get(0);
5053                ResolveInfo r1 = query.get(1);
5054                if (DEBUG_INTENT_MATCHING || debug) {
5055                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5056                            + r1.activityInfo.name + "=" + r1.priority);
5057                }
5058                // If the first activity has a higher priority, or a different
5059                // default, then it is always desirable to pick it.
5060                if (r0.priority != r1.priority
5061                        || r0.preferredOrder != r1.preferredOrder
5062                        || r0.isDefault != r1.isDefault) {
5063                    return query.get(0);
5064                }
5065                // If we have saved a preference for a preferred activity for
5066                // this Intent, use that.
5067                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5068                        flags, query, r0.priority, true, false, debug, userId);
5069                if (ri != null) {
5070                    return ri;
5071                }
5072                ri = new ResolveInfo(mResolveInfo);
5073                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5074                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5075                // If all of the options come from the same package, show the application's
5076                // label and icon instead of the generic resolver's.
5077                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5078                // and then throw away the ResolveInfo itself, meaning that the caller loses
5079                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5080                // a fallback for this case; we only set the target package's resources on
5081                // the ResolveInfo, not the ActivityInfo.
5082                final String intentPackage = intent.getPackage();
5083                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5084                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5085                    ri.resolvePackageName = intentPackage;
5086                    if (userNeedsBadging(userId)) {
5087                        ri.noResourceId = true;
5088                    } else {
5089                        ri.icon = appi.icon;
5090                    }
5091                    ri.iconResourceId = appi.icon;
5092                    ri.labelRes = appi.labelRes;
5093                }
5094                ri.activityInfo.applicationInfo = new ApplicationInfo(
5095                        ri.activityInfo.applicationInfo);
5096                if (userId != 0) {
5097                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5098                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5099                }
5100                // Make sure that the resolver is displayable in car mode
5101                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5102                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5103                return ri;
5104            }
5105        }
5106        return null;
5107    }
5108
5109    /**
5110     * Return true if the given list is not empty and all of its contents have
5111     * an activityInfo with the given package name.
5112     */
5113    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5114        if (ArrayUtils.isEmpty(list)) {
5115            return false;
5116        }
5117        for (int i = 0, N = list.size(); i < N; i++) {
5118            final ResolveInfo ri = list.get(i);
5119            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5120            if (ai == null || !packageName.equals(ai.packageName)) {
5121                return false;
5122            }
5123        }
5124        return true;
5125    }
5126
5127    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5128            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5129        final int N = query.size();
5130        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5131                .get(userId);
5132        // Get the list of persistent preferred activities that handle the intent
5133        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5134        List<PersistentPreferredActivity> pprefs = ppir != null
5135                ? ppir.queryIntent(intent, resolvedType,
5136                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5137                : null;
5138        if (pprefs != null && pprefs.size() > 0) {
5139            final int M = pprefs.size();
5140            for (int i=0; i<M; i++) {
5141                final PersistentPreferredActivity ppa = pprefs.get(i);
5142                if (DEBUG_PREFERRED || debug) {
5143                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5144                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5145                            + "\n  component=" + ppa.mComponent);
5146                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5147                }
5148                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5149                        flags | MATCH_DISABLED_COMPONENTS, userId);
5150                if (DEBUG_PREFERRED || debug) {
5151                    Slog.v(TAG, "Found persistent preferred activity:");
5152                    if (ai != null) {
5153                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5154                    } else {
5155                        Slog.v(TAG, "  null");
5156                    }
5157                }
5158                if (ai == null) {
5159                    // This previously registered persistent preferred activity
5160                    // component is no longer known. Ignore it and do NOT remove it.
5161                    continue;
5162                }
5163                for (int j=0; j<N; j++) {
5164                    final ResolveInfo ri = query.get(j);
5165                    if (!ri.activityInfo.applicationInfo.packageName
5166                            .equals(ai.applicationInfo.packageName)) {
5167                        continue;
5168                    }
5169                    if (!ri.activityInfo.name.equals(ai.name)) {
5170                        continue;
5171                    }
5172                    //  Found a persistent preference that can handle the intent.
5173                    if (DEBUG_PREFERRED || debug) {
5174                        Slog.v(TAG, "Returning persistent preferred activity: " +
5175                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5176                    }
5177                    return ri;
5178                }
5179            }
5180        }
5181        return null;
5182    }
5183
5184    // TODO: handle preferred activities missing while user has amnesia
5185    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5186            List<ResolveInfo> query, int priority, boolean always,
5187            boolean removeMatches, boolean debug, int userId) {
5188        if (!sUserManager.exists(userId)) return null;
5189        flags = updateFlagsForResolve(flags, userId, intent);
5190        // writer
5191        synchronized (mPackages) {
5192            if (intent.getSelector() != null) {
5193                intent = intent.getSelector();
5194            }
5195            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5196
5197            // Try to find a matching persistent preferred activity.
5198            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5199                    debug, userId);
5200
5201            // If a persistent preferred activity matched, use it.
5202            if (pri != null) {
5203                return pri;
5204            }
5205
5206            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5207            // Get the list of preferred activities that handle the intent
5208            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5209            List<PreferredActivity> prefs = pir != null
5210                    ? pir.queryIntent(intent, resolvedType,
5211                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5212                    : null;
5213            if (prefs != null && prefs.size() > 0) {
5214                boolean changed = false;
5215                try {
5216                    // First figure out how good the original match set is.
5217                    // We will only allow preferred activities that came
5218                    // from the same match quality.
5219                    int match = 0;
5220
5221                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5222
5223                    final int N = query.size();
5224                    for (int j=0; j<N; j++) {
5225                        final ResolveInfo ri = query.get(j);
5226                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5227                                + ": 0x" + Integer.toHexString(match));
5228                        if (ri.match > match) {
5229                            match = ri.match;
5230                        }
5231                    }
5232
5233                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5234                            + Integer.toHexString(match));
5235
5236                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5237                    final int M = prefs.size();
5238                    for (int i=0; i<M; i++) {
5239                        final PreferredActivity pa = prefs.get(i);
5240                        if (DEBUG_PREFERRED || debug) {
5241                            Slog.v(TAG, "Checking PreferredActivity ds="
5242                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5243                                    + "\n  component=" + pa.mPref.mComponent);
5244                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5245                        }
5246                        if (pa.mPref.mMatch != match) {
5247                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5248                                    + Integer.toHexString(pa.mPref.mMatch));
5249                            continue;
5250                        }
5251                        // If it's not an "always" type preferred activity and that's what we're
5252                        // looking for, skip it.
5253                        if (always && !pa.mPref.mAlways) {
5254                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5255                            continue;
5256                        }
5257                        final ActivityInfo ai = getActivityInfo(
5258                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5259                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5260                                userId);
5261                        if (DEBUG_PREFERRED || debug) {
5262                            Slog.v(TAG, "Found preferred activity:");
5263                            if (ai != null) {
5264                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5265                            } else {
5266                                Slog.v(TAG, "  null");
5267                            }
5268                        }
5269                        if (ai == null) {
5270                            // This previously registered preferred activity
5271                            // component is no longer known.  Most likely an update
5272                            // to the app was installed and in the new version this
5273                            // component no longer exists.  Clean it up by removing
5274                            // it from the preferred activities list, and skip it.
5275                            Slog.w(TAG, "Removing dangling preferred activity: "
5276                                    + pa.mPref.mComponent);
5277                            pir.removeFilter(pa);
5278                            changed = true;
5279                            continue;
5280                        }
5281                        for (int j=0; j<N; j++) {
5282                            final ResolveInfo ri = query.get(j);
5283                            if (!ri.activityInfo.applicationInfo.packageName
5284                                    .equals(ai.applicationInfo.packageName)) {
5285                                continue;
5286                            }
5287                            if (!ri.activityInfo.name.equals(ai.name)) {
5288                                continue;
5289                            }
5290
5291                            if (removeMatches) {
5292                                pir.removeFilter(pa);
5293                                changed = true;
5294                                if (DEBUG_PREFERRED) {
5295                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5296                                }
5297                                break;
5298                            }
5299
5300                            // Okay we found a previously set preferred or last chosen app.
5301                            // If the result set is different from when this
5302                            // was created, we need to clear it and re-ask the
5303                            // user their preference, if we're looking for an "always" type entry.
5304                            if (always && !pa.mPref.sameSet(query)) {
5305                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5306                                        + intent + " type " + resolvedType);
5307                                if (DEBUG_PREFERRED) {
5308                                    Slog.v(TAG, "Removing preferred activity since set changed "
5309                                            + pa.mPref.mComponent);
5310                                }
5311                                pir.removeFilter(pa);
5312                                // Re-add the filter as a "last chosen" entry (!always)
5313                                PreferredActivity lastChosen = new PreferredActivity(
5314                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5315                                pir.addFilter(lastChosen);
5316                                changed = true;
5317                                return null;
5318                            }
5319
5320                            // Yay! Either the set matched or we're looking for the last chosen
5321                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5322                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5323                            return ri;
5324                        }
5325                    }
5326                } finally {
5327                    if (changed) {
5328                        if (DEBUG_PREFERRED) {
5329                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5330                        }
5331                        scheduleWritePackageRestrictionsLocked(userId);
5332                    }
5333                }
5334            }
5335        }
5336        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5337        return null;
5338    }
5339
5340    /*
5341     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5342     */
5343    @Override
5344    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5345            int targetUserId) {
5346        mContext.enforceCallingOrSelfPermission(
5347                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5348        List<CrossProfileIntentFilter> matches =
5349                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5350        if (matches != null) {
5351            int size = matches.size();
5352            for (int i = 0; i < size; i++) {
5353                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5354            }
5355        }
5356        if (hasWebURI(intent)) {
5357            // cross-profile app linking works only towards the parent.
5358            final UserInfo parent = getProfileParent(sourceUserId);
5359            synchronized(mPackages) {
5360                int flags = updateFlagsForResolve(0, parent.id, intent);
5361                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5362                        intent, resolvedType, flags, sourceUserId, parent.id);
5363                return xpDomainInfo != null;
5364            }
5365        }
5366        return false;
5367    }
5368
5369    private UserInfo getProfileParent(int userId) {
5370        final long identity = Binder.clearCallingIdentity();
5371        try {
5372            return sUserManager.getProfileParent(userId);
5373        } finally {
5374            Binder.restoreCallingIdentity(identity);
5375        }
5376    }
5377
5378    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5379            String resolvedType, int userId) {
5380        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5381        if (resolver != null) {
5382            return resolver.queryIntent(intent, resolvedType, false, userId);
5383        }
5384        return null;
5385    }
5386
5387    @Override
5388    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5389            String resolvedType, int flags, int userId) {
5390        try {
5391            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5392
5393            return new ParceledListSlice<>(
5394                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5395        } finally {
5396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5397        }
5398    }
5399
5400    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5401            String resolvedType, int flags, int userId) {
5402        if (!sUserManager.exists(userId)) return Collections.emptyList();
5403        flags = updateFlagsForResolve(flags, userId, intent);
5404        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5405                false /* requireFullPermission */, false /* checkShell */,
5406                "query intent activities");
5407        ComponentName comp = intent.getComponent();
5408        if (comp == null) {
5409            if (intent.getSelector() != null) {
5410                intent = intent.getSelector();
5411                comp = intent.getComponent();
5412            }
5413        }
5414
5415        if (comp != null) {
5416            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5417            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5418            if (ai != null) {
5419                final ResolveInfo ri = new ResolveInfo();
5420                ri.activityInfo = ai;
5421                list.add(ri);
5422            }
5423            return list;
5424        }
5425
5426        // reader
5427        synchronized (mPackages) {
5428            final String pkgName = intent.getPackage();
5429            if (pkgName == null) {
5430                List<CrossProfileIntentFilter> matchingFilters =
5431                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5432                // Check for results that need to skip the current profile.
5433                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5434                        resolvedType, flags, userId);
5435                if (xpResolveInfo != null) {
5436                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5437                    result.add(xpResolveInfo);
5438                    return filterIfNotSystemUser(result, userId);
5439                }
5440
5441                // Check for results in the current profile.
5442                List<ResolveInfo> result = mActivities.queryIntent(
5443                        intent, resolvedType, flags, userId);
5444                result = filterIfNotSystemUser(result, userId);
5445
5446                // Check for cross profile results.
5447                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5448                xpResolveInfo = queryCrossProfileIntents(
5449                        matchingFilters, intent, resolvedType, flags, userId,
5450                        hasNonNegativePriorityResult);
5451                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5452                    boolean isVisibleToUser = filterIfNotSystemUser(
5453                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5454                    if (isVisibleToUser) {
5455                        result.add(xpResolveInfo);
5456                        Collections.sort(result, mResolvePrioritySorter);
5457                    }
5458                }
5459                if (hasWebURI(intent)) {
5460                    CrossProfileDomainInfo xpDomainInfo = null;
5461                    final UserInfo parent = getProfileParent(userId);
5462                    if (parent != null) {
5463                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5464                                flags, userId, parent.id);
5465                    }
5466                    if (xpDomainInfo != null) {
5467                        if (xpResolveInfo != null) {
5468                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5469                            // in the result.
5470                            result.remove(xpResolveInfo);
5471                        }
5472                        if (result.size() == 0) {
5473                            result.add(xpDomainInfo.resolveInfo);
5474                            return result;
5475                        }
5476                    } else if (result.size() <= 1) {
5477                        return result;
5478                    }
5479                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5480                            xpDomainInfo, userId);
5481                    Collections.sort(result, mResolvePrioritySorter);
5482                }
5483                return result;
5484            }
5485            final PackageParser.Package pkg = mPackages.get(pkgName);
5486            if (pkg != null) {
5487                return filterIfNotSystemUser(
5488                        mActivities.queryIntentForPackage(
5489                                intent, resolvedType, flags, pkg.activities, userId),
5490                        userId);
5491            }
5492            return new ArrayList<ResolveInfo>();
5493        }
5494    }
5495
5496    private static class CrossProfileDomainInfo {
5497        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5498        ResolveInfo resolveInfo;
5499        /* Best domain verification status of the activities found in the other profile */
5500        int bestDomainVerificationStatus;
5501    }
5502
5503    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5504            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5505        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5506                sourceUserId)) {
5507            return null;
5508        }
5509        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5510                resolvedType, flags, parentUserId);
5511
5512        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5513            return null;
5514        }
5515        CrossProfileDomainInfo result = null;
5516        int size = resultTargetUser.size();
5517        for (int i = 0; i < size; i++) {
5518            ResolveInfo riTargetUser = resultTargetUser.get(i);
5519            // Intent filter verification is only for filters that specify a host. So don't return
5520            // those that handle all web uris.
5521            if (riTargetUser.handleAllWebDataURI) {
5522                continue;
5523            }
5524            String packageName = riTargetUser.activityInfo.packageName;
5525            PackageSetting ps = mSettings.mPackages.get(packageName);
5526            if (ps == null) {
5527                continue;
5528            }
5529            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5530            int status = (int)(verificationState >> 32);
5531            if (result == null) {
5532                result = new CrossProfileDomainInfo();
5533                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5534                        sourceUserId, parentUserId);
5535                result.bestDomainVerificationStatus = status;
5536            } else {
5537                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5538                        result.bestDomainVerificationStatus);
5539            }
5540        }
5541        // Don't consider matches with status NEVER across profiles.
5542        if (result != null && result.bestDomainVerificationStatus
5543                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5544            return null;
5545        }
5546        return result;
5547    }
5548
5549    /**
5550     * Verification statuses are ordered from the worse to the best, except for
5551     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5552     */
5553    private int bestDomainVerificationStatus(int status1, int status2) {
5554        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5555            return status2;
5556        }
5557        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5558            return status1;
5559        }
5560        return (int) MathUtils.max(status1, status2);
5561    }
5562
5563    private boolean isUserEnabled(int userId) {
5564        long callingId = Binder.clearCallingIdentity();
5565        try {
5566            UserInfo userInfo = sUserManager.getUserInfo(userId);
5567            return userInfo != null && userInfo.isEnabled();
5568        } finally {
5569            Binder.restoreCallingIdentity(callingId);
5570        }
5571    }
5572
5573    /**
5574     * Filter out activities with systemUserOnly flag set, when current user is not System.
5575     *
5576     * @return filtered list
5577     */
5578    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5579        if (userId == UserHandle.USER_SYSTEM) {
5580            return resolveInfos;
5581        }
5582        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5583            ResolveInfo info = resolveInfos.get(i);
5584            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5585                resolveInfos.remove(i);
5586            }
5587        }
5588        return resolveInfos;
5589    }
5590
5591    /**
5592     * @param resolveInfos list of resolve infos in descending priority order
5593     * @return if the list contains a resolve info with non-negative priority
5594     */
5595    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5596        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5597    }
5598
5599    private static boolean hasWebURI(Intent intent) {
5600        if (intent.getData() == null) {
5601            return false;
5602        }
5603        final String scheme = intent.getScheme();
5604        if (TextUtils.isEmpty(scheme)) {
5605            return false;
5606        }
5607        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5608    }
5609
5610    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5611            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5612            int userId) {
5613        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5614
5615        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5616            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5617                    candidates.size());
5618        }
5619
5620        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5621        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5622        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5623        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5624        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5625        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5626
5627        synchronized (mPackages) {
5628            final int count = candidates.size();
5629            // First, try to use linked apps. Partition the candidates into four lists:
5630            // one for the final results, one for the "do not use ever", one for "undefined status"
5631            // and finally one for "browser app type".
5632            for (int n=0; n<count; n++) {
5633                ResolveInfo info = candidates.get(n);
5634                String packageName = info.activityInfo.packageName;
5635                PackageSetting ps = mSettings.mPackages.get(packageName);
5636                if (ps != null) {
5637                    // Add to the special match all list (Browser use case)
5638                    if (info.handleAllWebDataURI) {
5639                        matchAllList.add(info);
5640                        continue;
5641                    }
5642                    // Try to get the status from User settings first
5643                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5644                    int status = (int)(packedStatus >> 32);
5645                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5646                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5647                        if (DEBUG_DOMAIN_VERIFICATION) {
5648                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5649                                    + " : linkgen=" + linkGeneration);
5650                        }
5651                        // Use link-enabled generation as preferredOrder, i.e.
5652                        // prefer newly-enabled over earlier-enabled.
5653                        info.preferredOrder = linkGeneration;
5654                        alwaysList.add(info);
5655                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5656                        if (DEBUG_DOMAIN_VERIFICATION) {
5657                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5658                        }
5659                        neverList.add(info);
5660                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5661                        if (DEBUG_DOMAIN_VERIFICATION) {
5662                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5663                        }
5664                        alwaysAskList.add(info);
5665                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5666                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5667                        if (DEBUG_DOMAIN_VERIFICATION) {
5668                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5669                        }
5670                        undefinedList.add(info);
5671                    }
5672                }
5673            }
5674
5675            // We'll want to include browser possibilities in a few cases
5676            boolean includeBrowser = false;
5677
5678            // First try to add the "always" resolution(s) for the current user, if any
5679            if (alwaysList.size() > 0) {
5680                result.addAll(alwaysList);
5681            } else {
5682                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5683                result.addAll(undefinedList);
5684                // Maybe add one for the other profile.
5685                if (xpDomainInfo != null && (
5686                        xpDomainInfo.bestDomainVerificationStatus
5687                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5688                    result.add(xpDomainInfo.resolveInfo);
5689                }
5690                includeBrowser = true;
5691            }
5692
5693            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5694            // If there were 'always' entries their preferred order has been set, so we also
5695            // back that off to make the alternatives equivalent
5696            if (alwaysAskList.size() > 0) {
5697                for (ResolveInfo i : result) {
5698                    i.preferredOrder = 0;
5699                }
5700                result.addAll(alwaysAskList);
5701                includeBrowser = true;
5702            }
5703
5704            if (includeBrowser) {
5705                // Also add browsers (all of them or only the default one)
5706                if (DEBUG_DOMAIN_VERIFICATION) {
5707                    Slog.v(TAG, "   ...including browsers in candidate set");
5708                }
5709                if ((matchFlags & MATCH_ALL) != 0) {
5710                    result.addAll(matchAllList);
5711                } else {
5712                    // Browser/generic handling case.  If there's a default browser, go straight
5713                    // to that (but only if there is no other higher-priority match).
5714                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5715                    int maxMatchPrio = 0;
5716                    ResolveInfo defaultBrowserMatch = null;
5717                    final int numCandidates = matchAllList.size();
5718                    for (int n = 0; n < numCandidates; n++) {
5719                        ResolveInfo info = matchAllList.get(n);
5720                        // track the highest overall match priority...
5721                        if (info.priority > maxMatchPrio) {
5722                            maxMatchPrio = info.priority;
5723                        }
5724                        // ...and the highest-priority default browser match
5725                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5726                            if (defaultBrowserMatch == null
5727                                    || (defaultBrowserMatch.priority < info.priority)) {
5728                                if (debug) {
5729                                    Slog.v(TAG, "Considering default browser match " + info);
5730                                }
5731                                defaultBrowserMatch = info;
5732                            }
5733                        }
5734                    }
5735                    if (defaultBrowserMatch != null
5736                            && defaultBrowserMatch.priority >= maxMatchPrio
5737                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5738                    {
5739                        if (debug) {
5740                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5741                        }
5742                        result.add(defaultBrowserMatch);
5743                    } else {
5744                        result.addAll(matchAllList);
5745                    }
5746                }
5747
5748                // If there is nothing selected, add all candidates and remove the ones that the user
5749                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5750                if (result.size() == 0) {
5751                    result.addAll(candidates);
5752                    result.removeAll(neverList);
5753                }
5754            }
5755        }
5756        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5757            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5758                    result.size());
5759            for (ResolveInfo info : result) {
5760                Slog.v(TAG, "  + " + info.activityInfo);
5761            }
5762        }
5763        return result;
5764    }
5765
5766    // Returns a packed value as a long:
5767    //
5768    // high 'int'-sized word: link status: undefined/ask/never/always.
5769    // low 'int'-sized word: relative priority among 'always' results.
5770    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5771        long result = ps.getDomainVerificationStatusForUser(userId);
5772        // if none available, get the master status
5773        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5774            if (ps.getIntentFilterVerificationInfo() != null) {
5775                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5776            }
5777        }
5778        return result;
5779    }
5780
5781    private ResolveInfo querySkipCurrentProfileIntents(
5782            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5783            int flags, int sourceUserId) {
5784        if (matchingFilters != null) {
5785            int size = matchingFilters.size();
5786            for (int i = 0; i < size; i ++) {
5787                CrossProfileIntentFilter filter = matchingFilters.get(i);
5788                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5789                    // Checking if there are activities in the target user that can handle the
5790                    // intent.
5791                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5792                            resolvedType, flags, sourceUserId);
5793                    if (resolveInfo != null) {
5794                        return resolveInfo;
5795                    }
5796                }
5797            }
5798        }
5799        return null;
5800    }
5801
5802    // Return matching ResolveInfo in target user if any.
5803    private ResolveInfo queryCrossProfileIntents(
5804            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5805            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5806        if (matchingFilters != null) {
5807            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5808            // match the same intent. For performance reasons, it is better not to
5809            // run queryIntent twice for the same userId
5810            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5811            int size = matchingFilters.size();
5812            for (int i = 0; i < size; i++) {
5813                CrossProfileIntentFilter filter = matchingFilters.get(i);
5814                int targetUserId = filter.getTargetUserId();
5815                boolean skipCurrentProfile =
5816                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5817                boolean skipCurrentProfileIfNoMatchFound =
5818                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5819                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5820                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5821                    // Checking if there are activities in the target user that can handle the
5822                    // intent.
5823                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5824                            resolvedType, flags, sourceUserId);
5825                    if (resolveInfo != null) return resolveInfo;
5826                    alreadyTriedUserIds.put(targetUserId, true);
5827                }
5828            }
5829        }
5830        return null;
5831    }
5832
5833    /**
5834     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5835     * will forward the intent to the filter's target user.
5836     * Otherwise, returns null.
5837     */
5838    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5839            String resolvedType, int flags, int sourceUserId) {
5840        int targetUserId = filter.getTargetUserId();
5841        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5842                resolvedType, flags, targetUserId);
5843        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5844            // If all the matches in the target profile are suspended, return null.
5845            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5846                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5847                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5848                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5849                            targetUserId);
5850                }
5851            }
5852        }
5853        return null;
5854    }
5855
5856    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5857            int sourceUserId, int targetUserId) {
5858        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5859        long ident = Binder.clearCallingIdentity();
5860        boolean targetIsProfile;
5861        try {
5862            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5863        } finally {
5864            Binder.restoreCallingIdentity(ident);
5865        }
5866        String className;
5867        if (targetIsProfile) {
5868            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5869        } else {
5870            className = FORWARD_INTENT_TO_PARENT;
5871        }
5872        ComponentName forwardingActivityComponentName = new ComponentName(
5873                mAndroidApplication.packageName, className);
5874        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5875                sourceUserId);
5876        if (!targetIsProfile) {
5877            forwardingActivityInfo.showUserIcon = targetUserId;
5878            forwardingResolveInfo.noResourceId = true;
5879        }
5880        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5881        forwardingResolveInfo.priority = 0;
5882        forwardingResolveInfo.preferredOrder = 0;
5883        forwardingResolveInfo.match = 0;
5884        forwardingResolveInfo.isDefault = true;
5885        forwardingResolveInfo.filter = filter;
5886        forwardingResolveInfo.targetUserId = targetUserId;
5887        return forwardingResolveInfo;
5888    }
5889
5890    @Override
5891    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5892            Intent[] specifics, String[] specificTypes, Intent intent,
5893            String resolvedType, int flags, int userId) {
5894        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5895                specificTypes, intent, resolvedType, flags, userId));
5896    }
5897
5898    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5899            Intent[] specifics, String[] specificTypes, Intent intent,
5900            String resolvedType, int flags, int userId) {
5901        if (!sUserManager.exists(userId)) return Collections.emptyList();
5902        flags = updateFlagsForResolve(flags, userId, intent);
5903        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5904                false /* requireFullPermission */, false /* checkShell */,
5905                "query intent activity options");
5906        final String resultsAction = intent.getAction();
5907
5908        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5909                | PackageManager.GET_RESOLVED_FILTER, userId);
5910
5911        if (DEBUG_INTENT_MATCHING) {
5912            Log.v(TAG, "Query " + intent + ": " + results);
5913        }
5914
5915        int specificsPos = 0;
5916        int N;
5917
5918        // todo: note that the algorithm used here is O(N^2).  This
5919        // isn't a problem in our current environment, but if we start running
5920        // into situations where we have more than 5 or 10 matches then this
5921        // should probably be changed to something smarter...
5922
5923        // First we go through and resolve each of the specific items
5924        // that were supplied, taking care of removing any corresponding
5925        // duplicate items in the generic resolve list.
5926        if (specifics != null) {
5927            for (int i=0; i<specifics.length; i++) {
5928                final Intent sintent = specifics[i];
5929                if (sintent == null) {
5930                    continue;
5931                }
5932
5933                if (DEBUG_INTENT_MATCHING) {
5934                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5935                }
5936
5937                String action = sintent.getAction();
5938                if (resultsAction != null && resultsAction.equals(action)) {
5939                    // If this action was explicitly requested, then don't
5940                    // remove things that have it.
5941                    action = null;
5942                }
5943
5944                ResolveInfo ri = null;
5945                ActivityInfo ai = null;
5946
5947                ComponentName comp = sintent.getComponent();
5948                if (comp == null) {
5949                    ri = resolveIntent(
5950                        sintent,
5951                        specificTypes != null ? specificTypes[i] : null,
5952                            flags, userId);
5953                    if (ri == null) {
5954                        continue;
5955                    }
5956                    if (ri == mResolveInfo) {
5957                        // ACK!  Must do something better with this.
5958                    }
5959                    ai = ri.activityInfo;
5960                    comp = new ComponentName(ai.applicationInfo.packageName,
5961                            ai.name);
5962                } else {
5963                    ai = getActivityInfo(comp, flags, userId);
5964                    if (ai == null) {
5965                        continue;
5966                    }
5967                }
5968
5969                // Look for any generic query activities that are duplicates
5970                // of this specific one, and remove them from the results.
5971                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5972                N = results.size();
5973                int j;
5974                for (j=specificsPos; j<N; j++) {
5975                    ResolveInfo sri = results.get(j);
5976                    if ((sri.activityInfo.name.equals(comp.getClassName())
5977                            && sri.activityInfo.applicationInfo.packageName.equals(
5978                                    comp.getPackageName()))
5979                        || (action != null && sri.filter.matchAction(action))) {
5980                        results.remove(j);
5981                        if (DEBUG_INTENT_MATCHING) Log.v(
5982                            TAG, "Removing duplicate item from " + j
5983                            + " due to specific " + specificsPos);
5984                        if (ri == null) {
5985                            ri = sri;
5986                        }
5987                        j--;
5988                        N--;
5989                    }
5990                }
5991
5992                // Add this specific item to its proper place.
5993                if (ri == null) {
5994                    ri = new ResolveInfo();
5995                    ri.activityInfo = ai;
5996                }
5997                results.add(specificsPos, ri);
5998                ri.specificIndex = i;
5999                specificsPos++;
6000            }
6001        }
6002
6003        // Now we go through the remaining generic results and remove any
6004        // duplicate actions that are found here.
6005        N = results.size();
6006        for (int i=specificsPos; i<N-1; i++) {
6007            final ResolveInfo rii = results.get(i);
6008            if (rii.filter == null) {
6009                continue;
6010            }
6011
6012            // Iterate over all of the actions of this result's intent
6013            // filter...  typically this should be just one.
6014            final Iterator<String> it = rii.filter.actionsIterator();
6015            if (it == null) {
6016                continue;
6017            }
6018            while (it.hasNext()) {
6019                final String action = it.next();
6020                if (resultsAction != null && resultsAction.equals(action)) {
6021                    // If this action was explicitly requested, then don't
6022                    // remove things that have it.
6023                    continue;
6024                }
6025                for (int j=i+1; j<N; j++) {
6026                    final ResolveInfo rij = results.get(j);
6027                    if (rij.filter != null && rij.filter.hasAction(action)) {
6028                        results.remove(j);
6029                        if (DEBUG_INTENT_MATCHING) Log.v(
6030                            TAG, "Removing duplicate item from " + j
6031                            + " due to action " + action + " at " + i);
6032                        j--;
6033                        N--;
6034                    }
6035                }
6036            }
6037
6038            // If the caller didn't request filter information, drop it now
6039            // so we don't have to marshall/unmarshall it.
6040            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6041                rii.filter = null;
6042            }
6043        }
6044
6045        // Filter out the caller activity if so requested.
6046        if (caller != null) {
6047            N = results.size();
6048            for (int i=0; i<N; i++) {
6049                ActivityInfo ainfo = results.get(i).activityInfo;
6050                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6051                        && caller.getClassName().equals(ainfo.name)) {
6052                    results.remove(i);
6053                    break;
6054                }
6055            }
6056        }
6057
6058        // If the caller didn't request filter information,
6059        // drop them now so we don't have to
6060        // marshall/unmarshall it.
6061        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6062            N = results.size();
6063            for (int i=0; i<N; i++) {
6064                results.get(i).filter = null;
6065            }
6066        }
6067
6068        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6069        return results;
6070    }
6071
6072    @Override
6073    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6074            String resolvedType, int flags, int userId) {
6075        return new ParceledListSlice<>(
6076                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6077    }
6078
6079    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6080            String resolvedType, int flags, int userId) {
6081        if (!sUserManager.exists(userId)) return Collections.emptyList();
6082        flags = updateFlagsForResolve(flags, userId, intent);
6083        ComponentName comp = intent.getComponent();
6084        if (comp == null) {
6085            if (intent.getSelector() != null) {
6086                intent = intent.getSelector();
6087                comp = intent.getComponent();
6088            }
6089        }
6090        if (comp != null) {
6091            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6092            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6093            if (ai != null) {
6094                ResolveInfo ri = new ResolveInfo();
6095                ri.activityInfo = ai;
6096                list.add(ri);
6097            }
6098            return list;
6099        }
6100
6101        // reader
6102        synchronized (mPackages) {
6103            String pkgName = intent.getPackage();
6104            if (pkgName == null) {
6105                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6106            }
6107            final PackageParser.Package pkg = mPackages.get(pkgName);
6108            if (pkg != null) {
6109                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6110                        userId);
6111            }
6112            return Collections.emptyList();
6113        }
6114    }
6115
6116    @Override
6117    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6118        if (!sUserManager.exists(userId)) return null;
6119        flags = updateFlagsForResolve(flags, userId, intent);
6120        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6121        if (query != null) {
6122            if (query.size() >= 1) {
6123                // If there is more than one service with the same priority,
6124                // just arbitrarily pick the first one.
6125                return query.get(0);
6126            }
6127        }
6128        return null;
6129    }
6130
6131    @Override
6132    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6133            String resolvedType, int flags, int userId) {
6134        return new ParceledListSlice<>(
6135                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6136    }
6137
6138    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6139            String resolvedType, int flags, int userId) {
6140        if (!sUserManager.exists(userId)) return Collections.emptyList();
6141        flags = updateFlagsForResolve(flags, userId, intent);
6142        ComponentName comp = intent.getComponent();
6143        if (comp == null) {
6144            if (intent.getSelector() != null) {
6145                intent = intent.getSelector();
6146                comp = intent.getComponent();
6147            }
6148        }
6149        if (comp != null) {
6150            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6151            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6152            if (si != null) {
6153                final ResolveInfo ri = new ResolveInfo();
6154                ri.serviceInfo = si;
6155                list.add(ri);
6156            }
6157            return list;
6158        }
6159
6160        // reader
6161        synchronized (mPackages) {
6162            String pkgName = intent.getPackage();
6163            if (pkgName == null) {
6164                return mServices.queryIntent(intent, resolvedType, flags, userId);
6165            }
6166            final PackageParser.Package pkg = mPackages.get(pkgName);
6167            if (pkg != null) {
6168                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6169                        userId);
6170            }
6171            return Collections.emptyList();
6172        }
6173    }
6174
6175    @Override
6176    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6177            String resolvedType, int flags, int userId) {
6178        return new ParceledListSlice<>(
6179                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6180    }
6181
6182    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6183            Intent intent, String resolvedType, int flags, int userId) {
6184        if (!sUserManager.exists(userId)) return Collections.emptyList();
6185        flags = updateFlagsForResolve(flags, userId, intent);
6186        ComponentName comp = intent.getComponent();
6187        if (comp == null) {
6188            if (intent.getSelector() != null) {
6189                intent = intent.getSelector();
6190                comp = intent.getComponent();
6191            }
6192        }
6193        if (comp != null) {
6194            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6195            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6196            if (pi != null) {
6197                final ResolveInfo ri = new ResolveInfo();
6198                ri.providerInfo = pi;
6199                list.add(ri);
6200            }
6201            return list;
6202        }
6203
6204        // reader
6205        synchronized (mPackages) {
6206            String pkgName = intent.getPackage();
6207            if (pkgName == null) {
6208                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6209            }
6210            final PackageParser.Package pkg = mPackages.get(pkgName);
6211            if (pkg != null) {
6212                return mProviders.queryIntentForPackage(
6213                        intent, resolvedType, flags, pkg.providers, userId);
6214            }
6215            return Collections.emptyList();
6216        }
6217    }
6218
6219    @Override
6220    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6221        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6222        flags = updateFlagsForPackage(flags, userId, null);
6223        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6225                true /* requireFullPermission */, false /* checkShell */,
6226                "get installed packages");
6227
6228        // writer
6229        synchronized (mPackages) {
6230            ArrayList<PackageInfo> list;
6231            if (listUninstalled) {
6232                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6233                for (PackageSetting ps : mSettings.mPackages.values()) {
6234                    final PackageInfo pi;
6235                    if (ps.pkg != null) {
6236                        pi = generatePackageInfo(ps, flags, userId);
6237                    } else {
6238                        pi = generatePackageInfo(ps, flags, userId);
6239                    }
6240                    if (pi != null) {
6241                        list.add(pi);
6242                    }
6243                }
6244            } else {
6245                list = new ArrayList<PackageInfo>(mPackages.size());
6246                for (PackageParser.Package p : mPackages.values()) {
6247                    final PackageInfo pi =
6248                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6249                    if (pi != null) {
6250                        list.add(pi);
6251                    }
6252                }
6253            }
6254
6255            return new ParceledListSlice<PackageInfo>(list);
6256        }
6257    }
6258
6259    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6260            String[] permissions, boolean[] tmp, int flags, int userId) {
6261        int numMatch = 0;
6262        final PermissionsState permissionsState = ps.getPermissionsState();
6263        for (int i=0; i<permissions.length; i++) {
6264            final String permission = permissions[i];
6265            if (permissionsState.hasPermission(permission, userId)) {
6266                tmp[i] = true;
6267                numMatch++;
6268            } else {
6269                tmp[i] = false;
6270            }
6271        }
6272        if (numMatch == 0) {
6273            return;
6274        }
6275        final PackageInfo pi;
6276        if (ps.pkg != null) {
6277            pi = generatePackageInfo(ps, flags, userId);
6278        } else {
6279            pi = generatePackageInfo(ps, flags, userId);
6280        }
6281        // The above might return null in cases of uninstalled apps or install-state
6282        // skew across users/profiles.
6283        if (pi != null) {
6284            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6285                if (numMatch == permissions.length) {
6286                    pi.requestedPermissions = permissions;
6287                } else {
6288                    pi.requestedPermissions = new String[numMatch];
6289                    numMatch = 0;
6290                    for (int i=0; i<permissions.length; i++) {
6291                        if (tmp[i]) {
6292                            pi.requestedPermissions[numMatch] = permissions[i];
6293                            numMatch++;
6294                        }
6295                    }
6296                }
6297            }
6298            list.add(pi);
6299        }
6300    }
6301
6302    @Override
6303    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6304            String[] permissions, int flags, int userId) {
6305        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6306        flags = updateFlagsForPackage(flags, userId, permissions);
6307        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6308
6309        // writer
6310        synchronized (mPackages) {
6311            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6312            boolean[] tmpBools = new boolean[permissions.length];
6313            if (listUninstalled) {
6314                for (PackageSetting ps : mSettings.mPackages.values()) {
6315                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6316                }
6317            } else {
6318                for (PackageParser.Package pkg : mPackages.values()) {
6319                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6320                    if (ps != null) {
6321                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6322                                userId);
6323                    }
6324                }
6325            }
6326
6327            return new ParceledListSlice<PackageInfo>(list);
6328        }
6329    }
6330
6331    @Override
6332    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6333        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6334        flags = updateFlagsForApplication(flags, userId, null);
6335        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6336
6337        // writer
6338        synchronized (mPackages) {
6339            ArrayList<ApplicationInfo> list;
6340            if (listUninstalled) {
6341                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6342                for (PackageSetting ps : mSettings.mPackages.values()) {
6343                    ApplicationInfo ai;
6344                    if (ps.pkg != null) {
6345                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6346                                ps.readUserState(userId), userId);
6347                    } else {
6348                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6349                    }
6350                    if (ai != null) {
6351                        list.add(ai);
6352                    }
6353                }
6354            } else {
6355                list = new ArrayList<ApplicationInfo>(mPackages.size());
6356                for (PackageParser.Package p : mPackages.values()) {
6357                    if (p.mExtras != null) {
6358                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6359                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6360                        if (ai != null) {
6361                            list.add(ai);
6362                        }
6363                    }
6364                }
6365            }
6366
6367            return new ParceledListSlice<ApplicationInfo>(list);
6368        }
6369    }
6370
6371    @Override
6372    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6373        if (DISABLE_EPHEMERAL_APPS) {
6374            return null;
6375        }
6376
6377        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6378                "getEphemeralApplications");
6379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6380                true /* requireFullPermission */, false /* checkShell */,
6381                "getEphemeralApplications");
6382        synchronized (mPackages) {
6383            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6384                    .getEphemeralApplicationsLPw(userId);
6385            if (ephemeralApps != null) {
6386                return new ParceledListSlice<>(ephemeralApps);
6387            }
6388        }
6389        return null;
6390    }
6391
6392    @Override
6393    public boolean isEphemeralApplication(String packageName, int userId) {
6394        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6395                true /* requireFullPermission */, false /* checkShell */,
6396                "isEphemeral");
6397        if (DISABLE_EPHEMERAL_APPS) {
6398            return false;
6399        }
6400
6401        if (!isCallerSameApp(packageName)) {
6402            return false;
6403        }
6404        synchronized (mPackages) {
6405            PackageParser.Package pkg = mPackages.get(packageName);
6406            if (pkg != null) {
6407                return pkg.applicationInfo.isEphemeralApp();
6408            }
6409        }
6410        return false;
6411    }
6412
6413    @Override
6414    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6415        if (DISABLE_EPHEMERAL_APPS) {
6416            return null;
6417        }
6418
6419        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6420                true /* requireFullPermission */, false /* checkShell */,
6421                "getCookie");
6422        if (!isCallerSameApp(packageName)) {
6423            return null;
6424        }
6425        synchronized (mPackages) {
6426            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6427                    packageName, userId);
6428        }
6429    }
6430
6431    @Override
6432    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6433        if (DISABLE_EPHEMERAL_APPS) {
6434            return true;
6435        }
6436
6437        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6438                true /* requireFullPermission */, true /* checkShell */,
6439                "setCookie");
6440        if (!isCallerSameApp(packageName)) {
6441            return false;
6442        }
6443        synchronized (mPackages) {
6444            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6445                    packageName, cookie, userId);
6446        }
6447    }
6448
6449    @Override
6450    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6451        if (DISABLE_EPHEMERAL_APPS) {
6452            return null;
6453        }
6454
6455        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6456                "getEphemeralApplicationIcon");
6457        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6458                true /* requireFullPermission */, false /* checkShell */,
6459                "getEphemeralApplicationIcon");
6460        synchronized (mPackages) {
6461            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6462                    packageName, userId);
6463        }
6464    }
6465
6466    private boolean isCallerSameApp(String packageName) {
6467        PackageParser.Package pkg = mPackages.get(packageName);
6468        return pkg != null
6469                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6470    }
6471
6472    @Override
6473    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6474        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6475    }
6476
6477    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6478        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6479
6480        // reader
6481        synchronized (mPackages) {
6482            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6483            final int userId = UserHandle.getCallingUserId();
6484            while (i.hasNext()) {
6485                final PackageParser.Package p = i.next();
6486                if (p.applicationInfo == null) continue;
6487
6488                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6489                        && !p.applicationInfo.isDirectBootAware();
6490                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6491                        && p.applicationInfo.isDirectBootAware();
6492
6493                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6494                        && (!mSafeMode || isSystemApp(p))
6495                        && (matchesUnaware || matchesAware)) {
6496                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6497                    if (ps != null) {
6498                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6499                                ps.readUserState(userId), userId);
6500                        if (ai != null) {
6501                            finalList.add(ai);
6502                        }
6503                    }
6504                }
6505            }
6506        }
6507
6508        return finalList;
6509    }
6510
6511    @Override
6512    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6513        if (!sUserManager.exists(userId)) return null;
6514        flags = updateFlagsForComponent(flags, userId, name);
6515        // reader
6516        synchronized (mPackages) {
6517            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6518            PackageSetting ps = provider != null
6519                    ? mSettings.mPackages.get(provider.owner.packageName)
6520                    : null;
6521            return ps != null
6522                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6523                    ? PackageParser.generateProviderInfo(provider, flags,
6524                            ps.readUserState(userId), userId)
6525                    : null;
6526        }
6527    }
6528
6529    /**
6530     * @deprecated
6531     */
6532    @Deprecated
6533    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6534        // reader
6535        synchronized (mPackages) {
6536            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6537                    .entrySet().iterator();
6538            final int userId = UserHandle.getCallingUserId();
6539            while (i.hasNext()) {
6540                Map.Entry<String, PackageParser.Provider> entry = i.next();
6541                PackageParser.Provider p = entry.getValue();
6542                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6543
6544                if (ps != null && p.syncable
6545                        && (!mSafeMode || (p.info.applicationInfo.flags
6546                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6547                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6548                            ps.readUserState(userId), userId);
6549                    if (info != null) {
6550                        outNames.add(entry.getKey());
6551                        outInfo.add(info);
6552                    }
6553                }
6554            }
6555        }
6556    }
6557
6558    @Override
6559    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6560            int uid, int flags) {
6561        final int userId = processName != null ? UserHandle.getUserId(uid)
6562                : UserHandle.getCallingUserId();
6563        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6564        flags = updateFlagsForComponent(flags, userId, processName);
6565
6566        ArrayList<ProviderInfo> finalList = null;
6567        // reader
6568        synchronized (mPackages) {
6569            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6570            while (i.hasNext()) {
6571                final PackageParser.Provider p = i.next();
6572                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6573                if (ps != null && p.info.authority != null
6574                        && (processName == null
6575                                || (p.info.processName.equals(processName)
6576                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6577                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6578                    if (finalList == null) {
6579                        finalList = new ArrayList<ProviderInfo>(3);
6580                    }
6581                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6582                            ps.readUserState(userId), userId);
6583                    if (info != null) {
6584                        finalList.add(info);
6585                    }
6586                }
6587            }
6588        }
6589
6590        if (finalList != null) {
6591            Collections.sort(finalList, mProviderInitOrderSorter);
6592            return new ParceledListSlice<ProviderInfo>(finalList);
6593        }
6594
6595        return ParceledListSlice.emptyList();
6596    }
6597
6598    @Override
6599    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6600        // reader
6601        synchronized (mPackages) {
6602            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6603            return PackageParser.generateInstrumentationInfo(i, flags);
6604        }
6605    }
6606
6607    @Override
6608    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6609            String targetPackage, int flags) {
6610        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6611    }
6612
6613    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6614            int flags) {
6615        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6616
6617        // reader
6618        synchronized (mPackages) {
6619            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6620            while (i.hasNext()) {
6621                final PackageParser.Instrumentation p = i.next();
6622                if (targetPackage == null
6623                        || targetPackage.equals(p.info.targetPackage)) {
6624                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6625                            flags);
6626                    if (ii != null) {
6627                        finalList.add(ii);
6628                    }
6629                }
6630            }
6631        }
6632
6633        return finalList;
6634    }
6635
6636    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6637        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6638        if (overlays == null) {
6639            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6640            return;
6641        }
6642        for (PackageParser.Package opkg : overlays.values()) {
6643            // Not much to do if idmap fails: we already logged the error
6644            // and we certainly don't want to abort installation of pkg simply
6645            // because an overlay didn't fit properly. For these reasons,
6646            // ignore the return value of createIdmapForPackagePairLI.
6647            createIdmapForPackagePairLI(pkg, opkg);
6648        }
6649    }
6650
6651    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6652            PackageParser.Package opkg) {
6653        if (!opkg.mTrustedOverlay) {
6654            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6655                    opkg.baseCodePath + ": overlay not trusted");
6656            return false;
6657        }
6658        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6659        if (overlaySet == null) {
6660            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6661                    opkg.baseCodePath + " but target package has no known overlays");
6662            return false;
6663        }
6664        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6665        // TODO: generate idmap for split APKs
6666        try {
6667            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6668        } catch (InstallerException e) {
6669            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6670                    + opkg.baseCodePath);
6671            return false;
6672        }
6673        PackageParser.Package[] overlayArray =
6674            overlaySet.values().toArray(new PackageParser.Package[0]);
6675        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6676            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6677                return p1.mOverlayPriority - p2.mOverlayPriority;
6678            }
6679        };
6680        Arrays.sort(overlayArray, cmp);
6681
6682        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6683        int i = 0;
6684        for (PackageParser.Package p : overlayArray) {
6685            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6686        }
6687        return true;
6688    }
6689
6690    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6691        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6692        try {
6693            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6694        } finally {
6695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6696        }
6697    }
6698
6699    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6700        final File[] files = dir.listFiles();
6701        if (ArrayUtils.isEmpty(files)) {
6702            Log.d(TAG, "No files in app dir " + dir);
6703            return;
6704        }
6705
6706        if (DEBUG_PACKAGE_SCANNING) {
6707            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6708                    + " flags=0x" + Integer.toHexString(parseFlags));
6709        }
6710
6711        for (File file : files) {
6712            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6713                    && !PackageInstallerService.isStageName(file.getName());
6714            if (!isPackage) {
6715                // Ignore entries which are not packages
6716                continue;
6717            }
6718            try {
6719                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6720                        scanFlags, currentTime, null);
6721            } catch (PackageManagerException e) {
6722                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6723
6724                // Delete invalid userdata apps
6725                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6726                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6727                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6728                    removeCodePathLI(file);
6729                }
6730            }
6731        }
6732    }
6733
6734    private static File getSettingsProblemFile() {
6735        File dataDir = Environment.getDataDirectory();
6736        File systemDir = new File(dataDir, "system");
6737        File fname = new File(systemDir, "uiderrors.txt");
6738        return fname;
6739    }
6740
6741    static void reportSettingsProblem(int priority, String msg) {
6742        logCriticalInfo(priority, msg);
6743    }
6744
6745    static void logCriticalInfo(int priority, String msg) {
6746        Slog.println(priority, TAG, msg);
6747        EventLogTags.writePmCriticalInfo(msg);
6748        try {
6749            File fname = getSettingsProblemFile();
6750            FileOutputStream out = new FileOutputStream(fname, true);
6751            PrintWriter pw = new FastPrintWriter(out);
6752            SimpleDateFormat formatter = new SimpleDateFormat();
6753            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6754            pw.println(dateString + ": " + msg);
6755            pw.close();
6756            FileUtils.setPermissions(
6757                    fname.toString(),
6758                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6759                    -1, -1);
6760        } catch (java.io.IOException e) {
6761        }
6762    }
6763
6764    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6765            final int policyFlags) throws PackageManagerException {
6766        if (ps != null
6767                && ps.codePath.equals(srcFile)
6768                && ps.timeStamp == srcFile.lastModified()
6769                && !isCompatSignatureUpdateNeeded(pkg)
6770                && !isRecoverSignatureUpdateNeeded(pkg)) {
6771            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6772            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6773            ArraySet<PublicKey> signingKs;
6774            synchronized (mPackages) {
6775                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6776            }
6777            if (ps.signatures.mSignatures != null
6778                    && ps.signatures.mSignatures.length != 0
6779                    && signingKs != null) {
6780                // Optimization: reuse the existing cached certificates
6781                // if the package appears to be unchanged.
6782                pkg.mSignatures = ps.signatures.mSignatures;
6783                pkg.mSigningKeys = signingKs;
6784                return;
6785            }
6786
6787            Slog.w(TAG, "PackageSetting for " + ps.name
6788                    + " is missing signatures.  Collecting certs again to recover them.");
6789        } else {
6790            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6791        }
6792
6793        try {
6794            PackageParser.collectCertificates(pkg, policyFlags);
6795        } catch (PackageParserException e) {
6796            throw PackageManagerException.from(e);
6797        }
6798    }
6799
6800    /**
6801     *  Traces a package scan.
6802     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6803     */
6804    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6805            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6806        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6807        try {
6808            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6809        } finally {
6810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6811        }
6812    }
6813
6814    /**
6815     *  Scans a package and returns the newly parsed package.
6816     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6817     */
6818    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6819            long currentTime, UserHandle user) throws PackageManagerException {
6820        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6821        PackageParser pp = new PackageParser();
6822        pp.setSeparateProcesses(mSeparateProcesses);
6823        pp.setOnlyCoreApps(mOnlyCore);
6824        pp.setDisplayMetrics(mMetrics);
6825
6826        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6827            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6828        }
6829
6830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6831        final PackageParser.Package pkg;
6832        try {
6833            pkg = pp.parsePackage(scanFile, parseFlags);
6834        } catch (PackageParserException e) {
6835            throw PackageManagerException.from(e);
6836        } finally {
6837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6838        }
6839
6840        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6841    }
6842
6843    /**
6844     *  Scans a package and returns the newly parsed package.
6845     *  @throws PackageManagerException on a parse error.
6846     */
6847    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6848            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6849            throws PackageManagerException {
6850        // If the package has children and this is the first dive in the function
6851        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6852        // packages (parent and children) would be successfully scanned before the
6853        // actual scan since scanning mutates internal state and we want to atomically
6854        // install the package and its children.
6855        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6856            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6857                scanFlags |= SCAN_CHECK_ONLY;
6858            }
6859        } else {
6860            scanFlags &= ~SCAN_CHECK_ONLY;
6861        }
6862
6863        // Scan the parent
6864        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6865                scanFlags, currentTime, user);
6866
6867        // Scan the children
6868        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6869        for (int i = 0; i < childCount; i++) {
6870            PackageParser.Package childPackage = pkg.childPackages.get(i);
6871            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6872                    currentTime, user);
6873        }
6874
6875
6876        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6877            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6878        }
6879
6880        return scannedPkg;
6881    }
6882
6883    /**
6884     *  Scans a package and returns the newly parsed package.
6885     *  @throws PackageManagerException on a parse error.
6886     */
6887    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6888            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6889            throws PackageManagerException {
6890        PackageSetting ps = null;
6891        PackageSetting updatedPkg;
6892        // reader
6893        synchronized (mPackages) {
6894            // Look to see if we already know about this package.
6895            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6896            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6897                // This package has been renamed to its original name.  Let's
6898                // use that.
6899                ps = mSettings.peekPackageLPr(oldName);
6900            }
6901            // If there was no original package, see one for the real package name.
6902            if (ps == null) {
6903                ps = mSettings.peekPackageLPr(pkg.packageName);
6904            }
6905            // Check to see if this package could be hiding/updating a system
6906            // package.  Must look for it either under the original or real
6907            // package name depending on our state.
6908            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6909            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6910
6911            // If this is a package we don't know about on the system partition, we
6912            // may need to remove disabled child packages on the system partition
6913            // or may need to not add child packages if the parent apk is updated
6914            // on the data partition and no longer defines this child package.
6915            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6916                // If this is a parent package for an updated system app and this system
6917                // app got an OTA update which no longer defines some of the child packages
6918                // we have to prune them from the disabled system packages.
6919                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6920                if (disabledPs != null) {
6921                    final int scannedChildCount = (pkg.childPackages != null)
6922                            ? pkg.childPackages.size() : 0;
6923                    final int disabledChildCount = disabledPs.childPackageNames != null
6924                            ? disabledPs.childPackageNames.size() : 0;
6925                    for (int i = 0; i < disabledChildCount; i++) {
6926                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6927                        boolean disabledPackageAvailable = false;
6928                        for (int j = 0; j < scannedChildCount; j++) {
6929                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6930                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6931                                disabledPackageAvailable = true;
6932                                break;
6933                            }
6934                         }
6935                         if (!disabledPackageAvailable) {
6936                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6937                         }
6938                    }
6939                }
6940            }
6941        }
6942
6943        boolean updatedPkgBetter = false;
6944        // First check if this is a system package that may involve an update
6945        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6946            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6947            // it needs to drop FLAG_PRIVILEGED.
6948            if (locationIsPrivileged(scanFile)) {
6949                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6950            } else {
6951                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6952            }
6953
6954            if (ps != null && !ps.codePath.equals(scanFile)) {
6955                // The path has changed from what was last scanned...  check the
6956                // version of the new path against what we have stored to determine
6957                // what to do.
6958                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6959                if (pkg.mVersionCode <= ps.versionCode) {
6960                    // The system package has been updated and the code path does not match
6961                    // Ignore entry. Skip it.
6962                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6963                            + " ignored: updated version " + ps.versionCode
6964                            + " better than this " + pkg.mVersionCode);
6965                    if (!updatedPkg.codePath.equals(scanFile)) {
6966                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6967                                + ps.name + " changing from " + updatedPkg.codePathString
6968                                + " to " + scanFile);
6969                        updatedPkg.codePath = scanFile;
6970                        updatedPkg.codePathString = scanFile.toString();
6971                        updatedPkg.resourcePath = scanFile;
6972                        updatedPkg.resourcePathString = scanFile.toString();
6973                    }
6974                    updatedPkg.pkg = pkg;
6975                    updatedPkg.versionCode = pkg.mVersionCode;
6976
6977                    // Update the disabled system child packages to point to the package too.
6978                    final int childCount = updatedPkg.childPackageNames != null
6979                            ? updatedPkg.childPackageNames.size() : 0;
6980                    for (int i = 0; i < childCount; i++) {
6981                        String childPackageName = updatedPkg.childPackageNames.get(i);
6982                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6983                                childPackageName);
6984                        if (updatedChildPkg != null) {
6985                            updatedChildPkg.pkg = pkg;
6986                            updatedChildPkg.versionCode = pkg.mVersionCode;
6987                        }
6988                    }
6989
6990                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6991                            + scanFile + " ignored: updated version " + ps.versionCode
6992                            + " better than this " + pkg.mVersionCode);
6993                } else {
6994                    // The current app on the system partition is better than
6995                    // what we have updated to on the data partition; switch
6996                    // back to the system partition version.
6997                    // At this point, its safely assumed that package installation for
6998                    // apps in system partition will go through. If not there won't be a working
6999                    // version of the app
7000                    // writer
7001                    synchronized (mPackages) {
7002                        // Just remove the loaded entries from package lists.
7003                        mPackages.remove(ps.name);
7004                    }
7005
7006                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7007                            + " reverting from " + ps.codePathString
7008                            + ": new version " + pkg.mVersionCode
7009                            + " better than installed " + ps.versionCode);
7010
7011                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7012                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7013                    synchronized (mInstallLock) {
7014                        args.cleanUpResourcesLI();
7015                    }
7016                    synchronized (mPackages) {
7017                        mSettings.enableSystemPackageLPw(ps.name);
7018                    }
7019                    updatedPkgBetter = true;
7020                }
7021            }
7022        }
7023
7024        if (updatedPkg != null) {
7025            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7026            // initially
7027            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7028
7029            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7030            // flag set initially
7031            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7032                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7033            }
7034        }
7035
7036        // Verify certificates against what was last scanned
7037        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7038
7039        /*
7040         * A new system app appeared, but we already had a non-system one of the
7041         * same name installed earlier.
7042         */
7043        boolean shouldHideSystemApp = false;
7044        if (updatedPkg == null && ps != null
7045                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7046            /*
7047             * Check to make sure the signatures match first. If they don't,
7048             * wipe the installed application and its data.
7049             */
7050            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7051                    != PackageManager.SIGNATURE_MATCH) {
7052                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7053                        + " signatures don't match existing userdata copy; removing");
7054                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7055                        "scanPackageInternalLI")) {
7056                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7057                }
7058                ps = null;
7059            } else {
7060                /*
7061                 * If the newly-added system app is an older version than the
7062                 * already installed version, hide it. It will be scanned later
7063                 * and re-added like an update.
7064                 */
7065                if (pkg.mVersionCode <= ps.versionCode) {
7066                    shouldHideSystemApp = true;
7067                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7068                            + " but new version " + pkg.mVersionCode + " better than installed "
7069                            + ps.versionCode + "; hiding system");
7070                } else {
7071                    /*
7072                     * The newly found system app is a newer version that the
7073                     * one previously installed. Simply remove the
7074                     * already-installed application and replace it with our own
7075                     * while keeping the application data.
7076                     */
7077                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7078                            + " reverting from " + ps.codePathString + ": new version "
7079                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7080                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7081                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7082                    synchronized (mInstallLock) {
7083                        args.cleanUpResourcesLI();
7084                    }
7085                }
7086            }
7087        }
7088
7089        // The apk is forward locked (not public) if its code and resources
7090        // are kept in different files. (except for app in either system or
7091        // vendor path).
7092        // TODO grab this value from PackageSettings
7093        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7094            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7095                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7096            }
7097        }
7098
7099        // TODO: extend to support forward-locked splits
7100        String resourcePath = null;
7101        String baseResourcePath = null;
7102        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7103            if (ps != null && ps.resourcePathString != null) {
7104                resourcePath = ps.resourcePathString;
7105                baseResourcePath = ps.resourcePathString;
7106            } else {
7107                // Should not happen at all. Just log an error.
7108                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7109            }
7110        } else {
7111            resourcePath = pkg.codePath;
7112            baseResourcePath = pkg.baseCodePath;
7113        }
7114
7115        // Set application objects path explicitly.
7116        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7117        pkg.setApplicationInfoCodePath(pkg.codePath);
7118        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7119        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7120        pkg.setApplicationInfoResourcePath(resourcePath);
7121        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7122        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7123
7124        // Note that we invoke the following method only if we are about to unpack an application
7125        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7126                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7127
7128        /*
7129         * If the system app should be overridden by a previously installed
7130         * data, hide the system app now and let the /data/app scan pick it up
7131         * again.
7132         */
7133        if (shouldHideSystemApp) {
7134            synchronized (mPackages) {
7135                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7136            }
7137        }
7138
7139        return scannedPkg;
7140    }
7141
7142    private static String fixProcessName(String defProcessName,
7143            String processName, int uid) {
7144        if (processName == null) {
7145            return defProcessName;
7146        }
7147        return processName;
7148    }
7149
7150    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7151            throws PackageManagerException {
7152        if (pkgSetting.signatures.mSignatures != null) {
7153            // Already existing package. Make sure signatures match
7154            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7155                    == PackageManager.SIGNATURE_MATCH;
7156            if (!match) {
7157                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7158                        == PackageManager.SIGNATURE_MATCH;
7159            }
7160            if (!match) {
7161                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7162                        == PackageManager.SIGNATURE_MATCH;
7163            }
7164            if (!match) {
7165                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7166                        + pkg.packageName + " signatures do not match the "
7167                        + "previously installed version; ignoring!");
7168            }
7169        }
7170
7171        // Check for shared user signatures
7172        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7173            // Already existing package. Make sure signatures match
7174            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7175                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7176            if (!match) {
7177                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7178                        == PackageManager.SIGNATURE_MATCH;
7179            }
7180            if (!match) {
7181                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7182                        == PackageManager.SIGNATURE_MATCH;
7183            }
7184            if (!match) {
7185                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7186                        "Package " + pkg.packageName
7187                        + " has no signatures that match those in shared user "
7188                        + pkgSetting.sharedUser.name + "; ignoring!");
7189            }
7190        }
7191    }
7192
7193    /**
7194     * Enforces that only the system UID or root's UID can call a method exposed
7195     * via Binder.
7196     *
7197     * @param message used as message if SecurityException is thrown
7198     * @throws SecurityException if the caller is not system or root
7199     */
7200    private static final void enforceSystemOrRoot(String message) {
7201        final int uid = Binder.getCallingUid();
7202        if (uid != Process.SYSTEM_UID && uid != 0) {
7203            throw new SecurityException(message);
7204        }
7205    }
7206
7207    @Override
7208    public void performFstrimIfNeeded() {
7209        enforceSystemOrRoot("Only the system can request fstrim");
7210
7211        // Before everything else, see whether we need to fstrim.
7212        try {
7213            IMountService ms = PackageHelper.getMountService();
7214            if (ms != null) {
7215                final boolean isUpgrade = isUpgrade();
7216                boolean doTrim = isUpgrade;
7217                if (doTrim) {
7218                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7219                } else {
7220                    final long interval = android.provider.Settings.Global.getLong(
7221                            mContext.getContentResolver(),
7222                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7223                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7224                    if (interval > 0) {
7225                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7226                        if (timeSinceLast > interval) {
7227                            doTrim = true;
7228                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7229                                    + "; running immediately");
7230                        }
7231                    }
7232                }
7233                if (doTrim) {
7234                    if (!isFirstBoot()) {
7235                        try {
7236                            ActivityManagerNative.getDefault().showBootMessage(
7237                                    mContext.getResources().getString(
7238                                            R.string.android_upgrading_fstrim), true);
7239                        } catch (RemoteException e) {
7240                        }
7241                    }
7242                    ms.runMaintenance();
7243                }
7244            } else {
7245                Slog.e(TAG, "Mount service unavailable!");
7246            }
7247        } catch (RemoteException e) {
7248            // Can't happen; MountService is local
7249        }
7250    }
7251
7252    @Override
7253    public void updatePackagesIfNeeded() {
7254        enforceSystemOrRoot("Only the system can request package update");
7255
7256        // We need to re-extract after an OTA.
7257        boolean causeUpgrade = isUpgrade();
7258
7259        // First boot or factory reset.
7260        // Note: we also handle devices that are upgrading to N right now as if it is their
7261        //       first boot, as they do not have profile data.
7262        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7263
7264        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7265        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7266
7267        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7268            return;
7269        }
7270
7271        List<PackageParser.Package> pkgs;
7272        synchronized (mPackages) {
7273            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7274        }
7275
7276        final long startTime = System.nanoTime();
7277        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7278                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7279
7280        final int elapsedTimeSeconds =
7281                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7282
7283        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7284        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7285        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7286        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7287        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7288    }
7289
7290    /**
7291     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7292     * containing statistics about the invocation. The array consists of three elements,
7293     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7294     * and {@code numberOfPackagesFailed}.
7295     */
7296    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7297            String compilerFilter) {
7298
7299        int numberOfPackagesVisited = 0;
7300        int numberOfPackagesOptimized = 0;
7301        int numberOfPackagesSkipped = 0;
7302        int numberOfPackagesFailed = 0;
7303        final int numberOfPackagesToDexopt = pkgs.size();
7304
7305        for (PackageParser.Package pkg : pkgs) {
7306            numberOfPackagesVisited++;
7307
7308            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7309                if (DEBUG_DEXOPT) {
7310                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7311                }
7312                numberOfPackagesSkipped++;
7313                continue;
7314            }
7315
7316            if (DEBUG_DEXOPT) {
7317                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7318                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7319            }
7320
7321            if (showDialog) {
7322                try {
7323                    ActivityManagerNative.getDefault().showBootMessage(
7324                            mContext.getResources().getString(R.string.android_upgrading_apk,
7325                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7326                } catch (RemoteException e) {
7327                }
7328            }
7329
7330            // checkProfiles is false to avoid merging profiles during boot which
7331            // might interfere with background compilation (b/28612421).
7332            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7333            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7334            // trade-off worth doing to save boot time work.
7335            int dexOptStatus = performDexOptTraced(pkg.packageName,
7336                    false /* checkProfiles */,
7337                    compilerFilter,
7338                    false /* force */);
7339            switch (dexOptStatus) {
7340                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7341                    numberOfPackagesOptimized++;
7342                    break;
7343                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7344                    numberOfPackagesSkipped++;
7345                    break;
7346                case PackageDexOptimizer.DEX_OPT_FAILED:
7347                    numberOfPackagesFailed++;
7348                    break;
7349                default:
7350                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7351                    break;
7352            }
7353        }
7354
7355        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7356                numberOfPackagesFailed };
7357    }
7358
7359    @Override
7360    public void notifyPackageUse(String packageName, int reason) {
7361        synchronized (mPackages) {
7362            PackageParser.Package p = mPackages.get(packageName);
7363            if (p == null) {
7364                return;
7365            }
7366            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7367        }
7368    }
7369
7370    // TODO: this is not used nor needed. Delete it.
7371    @Override
7372    public boolean performDexOptIfNeeded(String packageName) {
7373        int dexOptStatus = performDexOptTraced(packageName,
7374                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7375        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7376    }
7377
7378    @Override
7379    public boolean performDexOpt(String packageName,
7380            boolean checkProfiles, int compileReason, boolean force) {
7381        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7382                getCompilerFilterForReason(compileReason), force);
7383        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7384    }
7385
7386    @Override
7387    public boolean performDexOptMode(String packageName,
7388            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7389        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7390                targetCompilerFilter, force);
7391        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7392    }
7393
7394    private int performDexOptTraced(String packageName,
7395                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7396        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7397        try {
7398            return performDexOptInternal(packageName, checkProfiles,
7399                    targetCompilerFilter, force);
7400        } finally {
7401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7402        }
7403    }
7404
7405    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7406    // if the package can now be considered up to date for the given filter.
7407    private int performDexOptInternal(String packageName,
7408                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7409        PackageParser.Package p;
7410        synchronized (mPackages) {
7411            p = mPackages.get(packageName);
7412            if (p == null) {
7413                // Package could not be found. Report failure.
7414                return PackageDexOptimizer.DEX_OPT_FAILED;
7415            }
7416            mPackageUsage.write(false);
7417        }
7418        long callingId = Binder.clearCallingIdentity();
7419        try {
7420            synchronized (mInstallLock) {
7421                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7422                        targetCompilerFilter, force);
7423            }
7424        } finally {
7425            Binder.restoreCallingIdentity(callingId);
7426        }
7427    }
7428
7429    public ArraySet<String> getOptimizablePackages() {
7430        ArraySet<String> pkgs = new ArraySet<String>();
7431        synchronized (mPackages) {
7432            for (PackageParser.Package p : mPackages.values()) {
7433                if (PackageDexOptimizer.canOptimizePackage(p)) {
7434                    pkgs.add(p.packageName);
7435                }
7436            }
7437        }
7438        return pkgs;
7439    }
7440
7441    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7442            boolean checkProfiles, String targetCompilerFilter,
7443            boolean force) {
7444        // Select the dex optimizer based on the force parameter.
7445        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7446        //       allocate an object here.
7447        PackageDexOptimizer pdo = force
7448                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7449                : mPackageDexOptimizer;
7450
7451        // Optimize all dependencies first. Note: we ignore the return value and march on
7452        // on errors.
7453        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7454        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7455        if (!deps.isEmpty()) {
7456            for (PackageParser.Package depPackage : deps) {
7457                // TODO: Analyze and investigate if we (should) profile libraries.
7458                // Currently this will do a full compilation of the library by default.
7459                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7460                        false /* checkProfiles */,
7461                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7462            }
7463        }
7464        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7465                targetCompilerFilter);
7466    }
7467
7468    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7469        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7470            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7471            Set<String> collectedNames = new HashSet<>();
7472            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7473
7474            retValue.remove(p);
7475
7476            return retValue;
7477        } else {
7478            return Collections.emptyList();
7479        }
7480    }
7481
7482    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7483            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7484        if (!collectedNames.contains(p.packageName)) {
7485            collectedNames.add(p.packageName);
7486            collected.add(p);
7487
7488            if (p.usesLibraries != null) {
7489                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7490            }
7491            if (p.usesOptionalLibraries != null) {
7492                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7493                        collectedNames);
7494            }
7495        }
7496    }
7497
7498    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7499            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7500        for (String libName : libs) {
7501            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7502            if (libPkg != null) {
7503                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7504            }
7505        }
7506    }
7507
7508    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7509        synchronized (mPackages) {
7510            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7511            if (lib != null && lib.apk != null) {
7512                return mPackages.get(lib.apk);
7513            }
7514        }
7515        return null;
7516    }
7517
7518    public void shutdown() {
7519        mPackageUsage.write(true);
7520    }
7521
7522    @Override
7523    public void dumpProfiles(String packageName) {
7524        PackageParser.Package pkg;
7525        synchronized (mPackages) {
7526            pkg = mPackages.get(packageName);
7527            if (pkg == null) {
7528                throw new IllegalArgumentException("Unknown package: " + packageName);
7529            }
7530        }
7531        /* Only the shell, root, or the app user should be able to dump profiles. */
7532        int callingUid = Binder.getCallingUid();
7533        if (callingUid != Process.SHELL_UID &&
7534            callingUid != Process.ROOT_UID &&
7535            callingUid != pkg.applicationInfo.uid) {
7536            throw new SecurityException("dumpProfiles");
7537        }
7538
7539        synchronized (mInstallLock) {
7540            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7541            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7542            try {
7543                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7544                String gid = Integer.toString(sharedGid);
7545                String codePaths = TextUtils.join(";", allCodePaths);
7546                mInstaller.dumpProfiles(gid, packageName, codePaths);
7547            } catch (InstallerException e) {
7548                Slog.w(TAG, "Failed to dump profiles", e);
7549            }
7550            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7551        }
7552    }
7553
7554    @Override
7555    public void forceDexOpt(String packageName) {
7556        enforceSystemOrRoot("forceDexOpt");
7557
7558        PackageParser.Package pkg;
7559        synchronized (mPackages) {
7560            pkg = mPackages.get(packageName);
7561            if (pkg == null) {
7562                throw new IllegalArgumentException("Unknown package: " + packageName);
7563            }
7564        }
7565
7566        synchronized (mInstallLock) {
7567            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7568
7569            // Whoever is calling forceDexOpt wants a fully compiled package.
7570            // Don't use profiles since that may cause compilation to be skipped.
7571            final int res = performDexOptInternalWithDependenciesLI(pkg,
7572                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7573                    true /* force */);
7574
7575            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7576            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7577                throw new IllegalStateException("Failed to dexopt: " + res);
7578            }
7579        }
7580    }
7581
7582    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7583        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7584            Slog.w(TAG, "Unable to update from " + oldPkg.name
7585                    + " to " + newPkg.packageName
7586                    + ": old package not in system partition");
7587            return false;
7588        } else if (mPackages.get(oldPkg.name) != null) {
7589            Slog.w(TAG, "Unable to update from " + oldPkg.name
7590                    + " to " + newPkg.packageName
7591                    + ": old package still exists");
7592            return false;
7593        }
7594        return true;
7595    }
7596
7597    void removeCodePathLI(File codePath) {
7598        if (codePath.isDirectory()) {
7599            try {
7600                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7601            } catch (InstallerException e) {
7602                Slog.w(TAG, "Failed to remove code path", e);
7603            }
7604        } else {
7605            codePath.delete();
7606        }
7607    }
7608
7609    private int[] resolveUserIds(int userId) {
7610        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7611    }
7612
7613    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7614        if (pkg == null) {
7615            Slog.wtf(TAG, "Package was null!", new Throwable());
7616            return;
7617        }
7618        clearAppDataLeafLIF(pkg, userId, flags);
7619        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7620        for (int i = 0; i < childCount; i++) {
7621            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7622        }
7623    }
7624
7625    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7626        final PackageSetting ps;
7627        synchronized (mPackages) {
7628            ps = mSettings.mPackages.get(pkg.packageName);
7629        }
7630        for (int realUserId : resolveUserIds(userId)) {
7631            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7632            try {
7633                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7634                        ceDataInode);
7635            } catch (InstallerException e) {
7636                Slog.w(TAG, String.valueOf(e));
7637            }
7638        }
7639    }
7640
7641    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7642        if (pkg == null) {
7643            Slog.wtf(TAG, "Package was null!", new Throwable());
7644            return;
7645        }
7646        destroyAppDataLeafLIF(pkg, userId, flags);
7647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7648        for (int i = 0; i < childCount; i++) {
7649            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7650        }
7651    }
7652
7653    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7654        final PackageSetting ps;
7655        synchronized (mPackages) {
7656            ps = mSettings.mPackages.get(pkg.packageName);
7657        }
7658        for (int realUserId : resolveUserIds(userId)) {
7659            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7660            try {
7661                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7662                        ceDataInode);
7663            } catch (InstallerException e) {
7664                Slog.w(TAG, String.valueOf(e));
7665            }
7666        }
7667    }
7668
7669    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7670        if (pkg == null) {
7671            Slog.wtf(TAG, "Package was null!", new Throwable());
7672            return;
7673        }
7674        destroyAppProfilesLeafLIF(pkg);
7675        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7676        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7677        for (int i = 0; i < childCount; i++) {
7678            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7679            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7680                    true /* removeBaseMarker */);
7681        }
7682    }
7683
7684    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7685            boolean removeBaseMarker) {
7686        if (pkg.isForwardLocked()) {
7687            return;
7688        }
7689
7690        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7691            try {
7692                path = PackageManagerServiceUtils.realpath(new File(path));
7693            } catch (IOException e) {
7694                // TODO: Should we return early here ?
7695                Slog.w(TAG, "Failed to get canonical path", e);
7696                continue;
7697            }
7698
7699            final String useMarker = path.replace('/', '@');
7700            for (int realUserId : resolveUserIds(userId)) {
7701                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7702                if (removeBaseMarker) {
7703                    File foreignUseMark = new File(profileDir, useMarker);
7704                    if (foreignUseMark.exists()) {
7705                        if (!foreignUseMark.delete()) {
7706                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7707                                    + pkg.packageName);
7708                        }
7709                    }
7710                }
7711
7712                File[] markers = profileDir.listFiles();
7713                if (markers != null) {
7714                    final String searchString = "@" + pkg.packageName + "@";
7715                    // We also delete all markers that contain the package name we're
7716                    // uninstalling. These are associated with secondary dex-files belonging
7717                    // to the package. Reconstructing the path of these dex files is messy
7718                    // in general.
7719                    for (File marker : markers) {
7720                        if (marker.getName().indexOf(searchString) > 0) {
7721                            if (!marker.delete()) {
7722                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7723                                    + pkg.packageName);
7724                            }
7725                        }
7726                    }
7727                }
7728            }
7729        }
7730    }
7731
7732    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7733        try {
7734            mInstaller.destroyAppProfiles(pkg.packageName);
7735        } catch (InstallerException e) {
7736            Slog.w(TAG, String.valueOf(e));
7737        }
7738    }
7739
7740    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7741        if (pkg == null) {
7742            Slog.wtf(TAG, "Package was null!", new Throwable());
7743            return;
7744        }
7745        clearAppProfilesLeafLIF(pkg);
7746        // We don't remove the base foreign use marker when clearing profiles because
7747        // we will rename it when the app is updated. Unlike the actual profile contents,
7748        // the foreign use marker is good across installs.
7749        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7750        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7751        for (int i = 0; i < childCount; i++) {
7752            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7753        }
7754    }
7755
7756    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7757        try {
7758            mInstaller.clearAppProfiles(pkg.packageName);
7759        } catch (InstallerException e) {
7760            Slog.w(TAG, String.valueOf(e));
7761        }
7762    }
7763
7764    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7765            long lastUpdateTime) {
7766        // Set parent install/update time
7767        PackageSetting ps = (PackageSetting) pkg.mExtras;
7768        if (ps != null) {
7769            ps.firstInstallTime = firstInstallTime;
7770            ps.lastUpdateTime = lastUpdateTime;
7771        }
7772        // Set children install/update time
7773        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7774        for (int i = 0; i < childCount; i++) {
7775            PackageParser.Package childPkg = pkg.childPackages.get(i);
7776            ps = (PackageSetting) childPkg.mExtras;
7777            if (ps != null) {
7778                ps.firstInstallTime = firstInstallTime;
7779                ps.lastUpdateTime = lastUpdateTime;
7780            }
7781        }
7782    }
7783
7784    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7785            PackageParser.Package changingLib) {
7786        if (file.path != null) {
7787            usesLibraryFiles.add(file.path);
7788            return;
7789        }
7790        PackageParser.Package p = mPackages.get(file.apk);
7791        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7792            // If we are doing this while in the middle of updating a library apk,
7793            // then we need to make sure to use that new apk for determining the
7794            // dependencies here.  (We haven't yet finished committing the new apk
7795            // to the package manager state.)
7796            if (p == null || p.packageName.equals(changingLib.packageName)) {
7797                p = changingLib;
7798            }
7799        }
7800        if (p != null) {
7801            usesLibraryFiles.addAll(p.getAllCodePaths());
7802        }
7803    }
7804
7805    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7806            PackageParser.Package changingLib) throws PackageManagerException {
7807        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7808            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7809            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7810            for (int i=0; i<N; i++) {
7811                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7812                if (file == null) {
7813                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7814                            "Package " + pkg.packageName + " requires unavailable shared library "
7815                            + pkg.usesLibraries.get(i) + "; failing!");
7816                }
7817                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7818            }
7819            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7820            for (int i=0; i<N; i++) {
7821                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7822                if (file == null) {
7823                    Slog.w(TAG, "Package " + pkg.packageName
7824                            + " desires unavailable shared library "
7825                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7826                } else {
7827                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7828                }
7829            }
7830            N = usesLibraryFiles.size();
7831            if (N > 0) {
7832                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7833            } else {
7834                pkg.usesLibraryFiles = null;
7835            }
7836        }
7837    }
7838
7839    private static boolean hasString(List<String> list, List<String> which) {
7840        if (list == null) {
7841            return false;
7842        }
7843        for (int i=list.size()-1; i>=0; i--) {
7844            for (int j=which.size()-1; j>=0; j--) {
7845                if (which.get(j).equals(list.get(i))) {
7846                    return true;
7847                }
7848            }
7849        }
7850        return false;
7851    }
7852
7853    private void updateAllSharedLibrariesLPw() {
7854        for (PackageParser.Package pkg : mPackages.values()) {
7855            try {
7856                updateSharedLibrariesLPw(pkg, null);
7857            } catch (PackageManagerException e) {
7858                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7859            }
7860        }
7861    }
7862
7863    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7864            PackageParser.Package changingPkg) {
7865        ArrayList<PackageParser.Package> res = null;
7866        for (PackageParser.Package pkg : mPackages.values()) {
7867            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7868                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7869                if (res == null) {
7870                    res = new ArrayList<PackageParser.Package>();
7871                }
7872                res.add(pkg);
7873                try {
7874                    updateSharedLibrariesLPw(pkg, changingPkg);
7875                } catch (PackageManagerException e) {
7876                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7877                }
7878            }
7879        }
7880        return res;
7881    }
7882
7883    /**
7884     * Derive the value of the {@code cpuAbiOverride} based on the provided
7885     * value and an optional stored value from the package settings.
7886     */
7887    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7888        String cpuAbiOverride = null;
7889
7890        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7891            cpuAbiOverride = null;
7892        } else if (abiOverride != null) {
7893            cpuAbiOverride = abiOverride;
7894        } else if (settings != null) {
7895            cpuAbiOverride = settings.cpuAbiOverrideString;
7896        }
7897
7898        return cpuAbiOverride;
7899    }
7900
7901    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7902            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7903                    throws PackageManagerException {
7904        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7905        // If the package has children and this is the first dive in the function
7906        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7907        // whether all packages (parent and children) would be successfully scanned
7908        // before the actual scan since scanning mutates internal state and we want
7909        // to atomically install the package and its children.
7910        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7911            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7912                scanFlags |= SCAN_CHECK_ONLY;
7913            }
7914        } else {
7915            scanFlags &= ~SCAN_CHECK_ONLY;
7916        }
7917
7918        final PackageParser.Package scannedPkg;
7919        try {
7920            // Scan the parent
7921            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7922            // Scan the children
7923            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7924            for (int i = 0; i < childCount; i++) {
7925                PackageParser.Package childPkg = pkg.childPackages.get(i);
7926                scanPackageLI(childPkg, policyFlags,
7927                        scanFlags, currentTime, user);
7928            }
7929        } finally {
7930            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7931        }
7932
7933        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7934            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7935        }
7936
7937        return scannedPkg;
7938    }
7939
7940    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7941            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7942        boolean success = false;
7943        try {
7944            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7945                    currentTime, user);
7946            success = true;
7947            return res;
7948        } finally {
7949            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7950                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7951                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7952                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7953                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7954            }
7955        }
7956    }
7957
7958    /**
7959     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7960     */
7961    private static boolean apkHasCode(String fileName) {
7962        StrictJarFile jarFile = null;
7963        try {
7964            jarFile = new StrictJarFile(fileName,
7965                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7966            return jarFile.findEntry("classes.dex") != null;
7967        } catch (IOException ignore) {
7968        } finally {
7969            try {
7970                jarFile.close();
7971            } catch (IOException ignore) {}
7972        }
7973        return false;
7974    }
7975
7976    /**
7977     * Enforces code policy for the package. This ensures that if an APK has
7978     * declared hasCode="true" in its manifest that the APK actually contains
7979     * code.
7980     *
7981     * @throws PackageManagerException If bytecode could not be found when it should exist
7982     */
7983    private static void enforceCodePolicy(PackageParser.Package pkg)
7984            throws PackageManagerException {
7985        final boolean shouldHaveCode =
7986                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7987        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7988            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7989                    "Package " + pkg.baseCodePath + " code is missing");
7990        }
7991
7992        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7993            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7994                final boolean splitShouldHaveCode =
7995                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7996                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7997                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7998                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7999                }
8000            }
8001        }
8002    }
8003
8004    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8005            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8006            throws PackageManagerException {
8007        final File scanFile = new File(pkg.codePath);
8008        if (pkg.applicationInfo.getCodePath() == null ||
8009                pkg.applicationInfo.getResourcePath() == null) {
8010            // Bail out. The resource and code paths haven't been set.
8011            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8012                    "Code and resource paths haven't been set correctly");
8013        }
8014
8015        // Apply policy
8016        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8017            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8018            if (pkg.applicationInfo.isDirectBootAware()) {
8019                // we're direct boot aware; set for all components
8020                for (PackageParser.Service s : pkg.services) {
8021                    s.info.encryptionAware = s.info.directBootAware = true;
8022                }
8023                for (PackageParser.Provider p : pkg.providers) {
8024                    p.info.encryptionAware = p.info.directBootAware = true;
8025                }
8026                for (PackageParser.Activity a : pkg.activities) {
8027                    a.info.encryptionAware = a.info.directBootAware = true;
8028                }
8029                for (PackageParser.Activity r : pkg.receivers) {
8030                    r.info.encryptionAware = r.info.directBootAware = true;
8031                }
8032            }
8033        } else {
8034            // Only allow system apps to be flagged as core apps.
8035            pkg.coreApp = false;
8036            // clear flags not applicable to regular apps
8037            pkg.applicationInfo.privateFlags &=
8038                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8039            pkg.applicationInfo.privateFlags &=
8040                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8041        }
8042        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8043
8044        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8045            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8046        }
8047
8048        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8049            enforceCodePolicy(pkg);
8050        }
8051
8052        if (mCustomResolverComponentName != null &&
8053                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8054            setUpCustomResolverActivity(pkg);
8055        }
8056
8057        if (pkg.packageName.equals("android")) {
8058            synchronized (mPackages) {
8059                if (mAndroidApplication != null) {
8060                    Slog.w(TAG, "*************************************************");
8061                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8062                    Slog.w(TAG, " file=" + scanFile);
8063                    Slog.w(TAG, "*************************************************");
8064                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8065                            "Core android package being redefined.  Skipping.");
8066                }
8067
8068                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8069                    // Set up information for our fall-back user intent resolution activity.
8070                    mPlatformPackage = pkg;
8071                    pkg.mVersionCode = mSdkVersion;
8072                    mAndroidApplication = pkg.applicationInfo;
8073
8074                    if (!mResolverReplaced) {
8075                        mResolveActivity.applicationInfo = mAndroidApplication;
8076                        mResolveActivity.name = ResolverActivity.class.getName();
8077                        mResolveActivity.packageName = mAndroidApplication.packageName;
8078                        mResolveActivity.processName = "system:ui";
8079                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8080                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8081                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8082                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8083                        mResolveActivity.exported = true;
8084                        mResolveActivity.enabled = true;
8085                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8086                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8087                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8088                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8089                                | ActivityInfo.CONFIG_ORIENTATION
8090                                | ActivityInfo.CONFIG_KEYBOARD
8091                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8092                        mResolveInfo.activityInfo = mResolveActivity;
8093                        mResolveInfo.priority = 0;
8094                        mResolveInfo.preferredOrder = 0;
8095                        mResolveInfo.match = 0;
8096                        mResolveComponentName = new ComponentName(
8097                                mAndroidApplication.packageName, mResolveActivity.name);
8098                    }
8099                }
8100            }
8101        }
8102
8103        if (DEBUG_PACKAGE_SCANNING) {
8104            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8105                Log.d(TAG, "Scanning package " + pkg.packageName);
8106        }
8107
8108        synchronized (mPackages) {
8109            if (mPackages.containsKey(pkg.packageName)
8110                    || mSharedLibraries.containsKey(pkg.packageName)) {
8111                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8112                        "Application package " + pkg.packageName
8113                                + " already installed.  Skipping duplicate.");
8114            }
8115
8116            // If we're only installing presumed-existing packages, require that the
8117            // scanned APK is both already known and at the path previously established
8118            // for it.  Previously unknown packages we pick up normally, but if we have an
8119            // a priori expectation about this package's install presence, enforce it.
8120            // With a singular exception for new system packages. When an OTA contains
8121            // a new system package, we allow the codepath to change from a system location
8122            // to the user-installed location. If we don't allow this change, any newer,
8123            // user-installed version of the application will be ignored.
8124            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8125                if (mExpectingBetter.containsKey(pkg.packageName)) {
8126                    logCriticalInfo(Log.WARN,
8127                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8128                } else {
8129                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8130                    if (known != null) {
8131                        if (DEBUG_PACKAGE_SCANNING) {
8132                            Log.d(TAG, "Examining " + pkg.codePath
8133                                    + " and requiring known paths " + known.codePathString
8134                                    + " & " + known.resourcePathString);
8135                        }
8136                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8137                                || !pkg.applicationInfo.getResourcePath().equals(
8138                                known.resourcePathString)) {
8139                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8140                                    "Application package " + pkg.packageName
8141                                            + " found at " + pkg.applicationInfo.getCodePath()
8142                                            + " but expected at " + known.codePathString
8143                                            + "; ignoring.");
8144                        }
8145                    }
8146                }
8147            }
8148        }
8149
8150        // Initialize package source and resource directories
8151        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8152        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8153
8154        SharedUserSetting suid = null;
8155        PackageSetting pkgSetting = null;
8156
8157        if (!isSystemApp(pkg)) {
8158            // Only system apps can use these features.
8159            pkg.mOriginalPackages = null;
8160            pkg.mRealPackage = null;
8161            pkg.mAdoptPermissions = null;
8162        }
8163
8164        // Getting the package setting may have a side-effect, so if we
8165        // are only checking if scan would succeed, stash a copy of the
8166        // old setting to restore at the end.
8167        PackageSetting nonMutatedPs = null;
8168
8169        // writer
8170        synchronized (mPackages) {
8171            if (pkg.mSharedUserId != null) {
8172                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8173                if (suid == null) {
8174                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8175                            "Creating application package " + pkg.packageName
8176                            + " for shared user failed");
8177                }
8178                if (DEBUG_PACKAGE_SCANNING) {
8179                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8180                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8181                                + "): packages=" + suid.packages);
8182                }
8183            }
8184
8185            // Check if we are renaming from an original package name.
8186            PackageSetting origPackage = null;
8187            String realName = null;
8188            if (pkg.mOriginalPackages != null) {
8189                // This package may need to be renamed to a previously
8190                // installed name.  Let's check on that...
8191                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8192                if (pkg.mOriginalPackages.contains(renamed)) {
8193                    // This package had originally been installed as the
8194                    // original name, and we have already taken care of
8195                    // transitioning to the new one.  Just update the new
8196                    // one to continue using the old name.
8197                    realName = pkg.mRealPackage;
8198                    if (!pkg.packageName.equals(renamed)) {
8199                        // Callers into this function may have already taken
8200                        // care of renaming the package; only do it here if
8201                        // it is not already done.
8202                        pkg.setPackageName(renamed);
8203                    }
8204
8205                } else {
8206                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8207                        if ((origPackage = mSettings.peekPackageLPr(
8208                                pkg.mOriginalPackages.get(i))) != null) {
8209                            // We do have the package already installed under its
8210                            // original name...  should we use it?
8211                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8212                                // New package is not compatible with original.
8213                                origPackage = null;
8214                                continue;
8215                            } else if (origPackage.sharedUser != null) {
8216                                // Make sure uid is compatible between packages.
8217                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8218                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8219                                            + " to " + pkg.packageName + ": old uid "
8220                                            + origPackage.sharedUser.name
8221                                            + " differs from " + pkg.mSharedUserId);
8222                                    origPackage = null;
8223                                    continue;
8224                                }
8225                                // TODO: Add case when shared user id is added [b/28144775]
8226                            } else {
8227                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8228                                        + pkg.packageName + " to old name " + origPackage.name);
8229                            }
8230                            break;
8231                        }
8232                    }
8233                }
8234            }
8235
8236            if (mTransferedPackages.contains(pkg.packageName)) {
8237                Slog.w(TAG, "Package " + pkg.packageName
8238                        + " was transferred to another, but its .apk remains");
8239            }
8240
8241            // See comments in nonMutatedPs declaration
8242            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8243                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8244                if (foundPs != null) {
8245                    nonMutatedPs = new PackageSetting(foundPs);
8246                }
8247            }
8248
8249            // Just create the setting, don't add it yet. For already existing packages
8250            // the PkgSetting exists already and doesn't have to be created.
8251            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8252                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8253                    pkg.applicationInfo.primaryCpuAbi,
8254                    pkg.applicationInfo.secondaryCpuAbi,
8255                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8256                    user, false);
8257            if (pkgSetting == null) {
8258                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8259                        "Creating application package " + pkg.packageName + " failed");
8260            }
8261
8262            if (pkgSetting.origPackage != null) {
8263                // If we are first transitioning from an original package,
8264                // fix up the new package's name now.  We need to do this after
8265                // looking up the package under its new name, so getPackageLP
8266                // can take care of fiddling things correctly.
8267                pkg.setPackageName(origPackage.name);
8268
8269                // File a report about this.
8270                String msg = "New package " + pkgSetting.realName
8271                        + " renamed to replace old package " + pkgSetting.name;
8272                reportSettingsProblem(Log.WARN, msg);
8273
8274                // Make a note of it.
8275                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8276                    mTransferedPackages.add(origPackage.name);
8277                }
8278
8279                // No longer need to retain this.
8280                pkgSetting.origPackage = null;
8281            }
8282
8283            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8284                // Make a note of it.
8285                mTransferedPackages.add(pkg.packageName);
8286            }
8287
8288            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8289                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8290            }
8291
8292            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8293                // Check all shared libraries and map to their actual file path.
8294                // We only do this here for apps not on a system dir, because those
8295                // are the only ones that can fail an install due to this.  We
8296                // will take care of the system apps by updating all of their
8297                // library paths after the scan is done.
8298                updateSharedLibrariesLPw(pkg, null);
8299            }
8300
8301            if (mFoundPolicyFile) {
8302                SELinuxMMAC.assignSeinfoValue(pkg);
8303            }
8304
8305            pkg.applicationInfo.uid = pkgSetting.appId;
8306            pkg.mExtras = pkgSetting;
8307            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8308                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8309                    // We just determined the app is signed correctly, so bring
8310                    // over the latest parsed certs.
8311                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8312                } else {
8313                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8314                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8315                                "Package " + pkg.packageName + " upgrade keys do not match the "
8316                                + "previously installed version");
8317                    } else {
8318                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8319                        String msg = "System package " + pkg.packageName
8320                            + " signature changed; retaining data.";
8321                        reportSettingsProblem(Log.WARN, msg);
8322                    }
8323                }
8324            } else {
8325                try {
8326                    verifySignaturesLP(pkgSetting, pkg);
8327                    // We just determined the app is signed correctly, so bring
8328                    // over the latest parsed certs.
8329                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8330                } catch (PackageManagerException e) {
8331                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8332                        throw e;
8333                    }
8334                    // The signature has changed, but this package is in the system
8335                    // image...  let's recover!
8336                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8337                    // However...  if this package is part of a shared user, but it
8338                    // doesn't match the signature of the shared user, let's fail.
8339                    // What this means is that you can't change the signatures
8340                    // associated with an overall shared user, which doesn't seem all
8341                    // that unreasonable.
8342                    if (pkgSetting.sharedUser != null) {
8343                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8344                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8345                            throw new PackageManagerException(
8346                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8347                                            "Signature mismatch for shared user: "
8348                                            + pkgSetting.sharedUser);
8349                        }
8350                    }
8351                    // File a report about this.
8352                    String msg = "System package " + pkg.packageName
8353                        + " signature changed; retaining data.";
8354                    reportSettingsProblem(Log.WARN, msg);
8355                }
8356            }
8357            // Verify that this new package doesn't have any content providers
8358            // that conflict with existing packages.  Only do this if the
8359            // package isn't already installed, since we don't want to break
8360            // things that are installed.
8361            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8362                final int N = pkg.providers.size();
8363                int i;
8364                for (i=0; i<N; i++) {
8365                    PackageParser.Provider p = pkg.providers.get(i);
8366                    if (p.info.authority != null) {
8367                        String names[] = p.info.authority.split(";");
8368                        for (int j = 0; j < names.length; j++) {
8369                            if (mProvidersByAuthority.containsKey(names[j])) {
8370                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8371                                final String otherPackageName =
8372                                        ((other != null && other.getComponentName() != null) ?
8373                                                other.getComponentName().getPackageName() : "?");
8374                                throw new PackageManagerException(
8375                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8376                                                "Can't install because provider name " + names[j]
8377                                                + " (in package " + pkg.applicationInfo.packageName
8378                                                + ") is already used by " + otherPackageName);
8379                            }
8380                        }
8381                    }
8382                }
8383            }
8384
8385            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8386                // This package wants to adopt ownership of permissions from
8387                // another package.
8388                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8389                    final String origName = pkg.mAdoptPermissions.get(i);
8390                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8391                    if (orig != null) {
8392                        if (verifyPackageUpdateLPr(orig, pkg)) {
8393                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8394                                    + pkg.packageName);
8395                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8396                        }
8397                    }
8398                }
8399            }
8400        }
8401
8402        final String pkgName = pkg.packageName;
8403
8404        final long scanFileTime = scanFile.lastModified();
8405        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8406        pkg.applicationInfo.processName = fixProcessName(
8407                pkg.applicationInfo.packageName,
8408                pkg.applicationInfo.processName,
8409                pkg.applicationInfo.uid);
8410
8411        if (pkg != mPlatformPackage) {
8412            // Get all of our default paths setup
8413            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8414        }
8415
8416        final String path = scanFile.getPath();
8417        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8418
8419        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8420            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8421
8422            // Some system apps still use directory structure for native libraries
8423            // in which case we might end up not detecting abi solely based on apk
8424            // structure. Try to detect abi based on directory structure.
8425            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8426                    pkg.applicationInfo.primaryCpuAbi == null) {
8427                setBundledAppAbisAndRoots(pkg, pkgSetting);
8428                setNativeLibraryPaths(pkg);
8429            }
8430
8431        } else {
8432            if ((scanFlags & SCAN_MOVE) != 0) {
8433                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8434                // but we already have this packages package info in the PackageSetting. We just
8435                // use that and derive the native library path based on the new codepath.
8436                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8437                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8438            }
8439
8440            // Set native library paths again. For moves, the path will be updated based on the
8441            // ABIs we've determined above. For non-moves, the path will be updated based on the
8442            // ABIs we determined during compilation, but the path will depend on the final
8443            // package path (after the rename away from the stage path).
8444            setNativeLibraryPaths(pkg);
8445        }
8446
8447        // This is a special case for the "system" package, where the ABI is
8448        // dictated by the zygote configuration (and init.rc). We should keep track
8449        // of this ABI so that we can deal with "normal" applications that run under
8450        // the same UID correctly.
8451        if (mPlatformPackage == pkg) {
8452            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8453                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8454        }
8455
8456        // If there's a mismatch between the abi-override in the package setting
8457        // and the abiOverride specified for the install. Warn about this because we
8458        // would've already compiled the app without taking the package setting into
8459        // account.
8460        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8461            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8462                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8463                        " for package " + pkg.packageName);
8464            }
8465        }
8466
8467        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8468        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8469        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8470
8471        // Copy the derived override back to the parsed package, so that we can
8472        // update the package settings accordingly.
8473        pkg.cpuAbiOverride = cpuAbiOverride;
8474
8475        if (DEBUG_ABI_SELECTION) {
8476            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8477                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8478                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8479        }
8480
8481        // Push the derived path down into PackageSettings so we know what to
8482        // clean up at uninstall time.
8483        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8484
8485        if (DEBUG_ABI_SELECTION) {
8486            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8487                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8488                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8489        }
8490
8491        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8492            // We don't do this here during boot because we can do it all
8493            // at once after scanning all existing packages.
8494            //
8495            // We also do this *before* we perform dexopt on this package, so that
8496            // we can avoid redundant dexopts, and also to make sure we've got the
8497            // code and package path correct.
8498            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8499                    pkg, true /* boot complete */);
8500        }
8501
8502        if (mFactoryTest && pkg.requestedPermissions.contains(
8503                android.Manifest.permission.FACTORY_TEST)) {
8504            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8505        }
8506
8507        ArrayList<PackageParser.Package> clientLibPkgs = null;
8508
8509        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8510            if (nonMutatedPs != null) {
8511                synchronized (mPackages) {
8512                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8513                }
8514            }
8515            return pkg;
8516        }
8517
8518        // Only privileged apps and updated privileged apps can add child packages.
8519        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8520            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8521                throw new PackageManagerException("Only privileged apps and updated "
8522                        + "privileged apps can add child packages. Ignoring package "
8523                        + pkg.packageName);
8524            }
8525            final int childCount = pkg.childPackages.size();
8526            for (int i = 0; i < childCount; i++) {
8527                PackageParser.Package childPkg = pkg.childPackages.get(i);
8528                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8529                        childPkg.packageName)) {
8530                    throw new PackageManagerException("Cannot override a child package of "
8531                            + "another disabled system app. Ignoring package " + pkg.packageName);
8532                }
8533            }
8534        }
8535
8536        // writer
8537        synchronized (mPackages) {
8538            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8539                // Only system apps can add new shared libraries.
8540                if (pkg.libraryNames != null) {
8541                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8542                        String name = pkg.libraryNames.get(i);
8543                        boolean allowed = false;
8544                        if (pkg.isUpdatedSystemApp()) {
8545                            // New library entries can only be added through the
8546                            // system image.  This is important to get rid of a lot
8547                            // of nasty edge cases: for example if we allowed a non-
8548                            // system update of the app to add a library, then uninstalling
8549                            // the update would make the library go away, and assumptions
8550                            // we made such as through app install filtering would now
8551                            // have allowed apps on the device which aren't compatible
8552                            // with it.  Better to just have the restriction here, be
8553                            // conservative, and create many fewer cases that can negatively
8554                            // impact the user experience.
8555                            final PackageSetting sysPs = mSettings
8556                                    .getDisabledSystemPkgLPr(pkg.packageName);
8557                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8558                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8559                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8560                                        allowed = true;
8561                                        break;
8562                                    }
8563                                }
8564                            }
8565                        } else {
8566                            allowed = true;
8567                        }
8568                        if (allowed) {
8569                            if (!mSharedLibraries.containsKey(name)) {
8570                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8571                            } else if (!name.equals(pkg.packageName)) {
8572                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8573                                        + name + " already exists; skipping");
8574                            }
8575                        } else {
8576                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8577                                    + name + " that is not declared on system image; skipping");
8578                        }
8579                    }
8580                    if ((scanFlags & SCAN_BOOTING) == 0) {
8581                        // If we are not booting, we need to update any applications
8582                        // that are clients of our shared library.  If we are booting,
8583                        // this will all be done once the scan is complete.
8584                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8585                    }
8586                }
8587            }
8588        }
8589
8590        if ((scanFlags & SCAN_BOOTING) != 0) {
8591            // No apps can run during boot scan, so they don't need to be frozen
8592        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8593            // Caller asked to not kill app, so it's probably not frozen
8594        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8595            // Caller asked us to ignore frozen check for some reason; they
8596            // probably didn't know the package name
8597        } else {
8598            // We're doing major surgery on this package, so it better be frozen
8599            // right now to keep it from launching
8600            checkPackageFrozen(pkgName);
8601        }
8602
8603        // Also need to kill any apps that are dependent on the library.
8604        if (clientLibPkgs != null) {
8605            for (int i=0; i<clientLibPkgs.size(); i++) {
8606                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8607                killApplication(clientPkg.applicationInfo.packageName,
8608                        clientPkg.applicationInfo.uid, "update lib");
8609            }
8610        }
8611
8612        // Make sure we're not adding any bogus keyset info
8613        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8614        ksms.assertScannedPackageValid(pkg);
8615
8616        // writer
8617        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8618
8619        boolean createIdmapFailed = false;
8620        synchronized (mPackages) {
8621            // We don't expect installation to fail beyond this point
8622
8623            if (pkgSetting.pkg != null) {
8624                // Note that |user| might be null during the initial boot scan. If a codePath
8625                // for an app has changed during a boot scan, it's due to an app update that's
8626                // part of the system partition and marker changes must be applied to all users.
8627                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8628                    (user != null) ? user : UserHandle.ALL);
8629            }
8630
8631            // Add the new setting to mSettings
8632            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8633            // Add the new setting to mPackages
8634            mPackages.put(pkg.applicationInfo.packageName, pkg);
8635            // Make sure we don't accidentally delete its data.
8636            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8637            while (iter.hasNext()) {
8638                PackageCleanItem item = iter.next();
8639                if (pkgName.equals(item.packageName)) {
8640                    iter.remove();
8641                }
8642            }
8643
8644            // Take care of first install / last update times.
8645            if (currentTime != 0) {
8646                if (pkgSetting.firstInstallTime == 0) {
8647                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8648                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8649                    pkgSetting.lastUpdateTime = currentTime;
8650                }
8651            } else if (pkgSetting.firstInstallTime == 0) {
8652                // We need *something*.  Take time time stamp of the file.
8653                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8654            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8655                if (scanFileTime != pkgSetting.timeStamp) {
8656                    // A package on the system image has changed; consider this
8657                    // to be an update.
8658                    pkgSetting.lastUpdateTime = scanFileTime;
8659                }
8660            }
8661
8662            // Add the package's KeySets to the global KeySetManagerService
8663            ksms.addScannedPackageLPw(pkg);
8664
8665            int N = pkg.providers.size();
8666            StringBuilder r = null;
8667            int i;
8668            for (i=0; i<N; i++) {
8669                PackageParser.Provider p = pkg.providers.get(i);
8670                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8671                        p.info.processName, pkg.applicationInfo.uid);
8672                mProviders.addProvider(p);
8673                p.syncable = p.info.isSyncable;
8674                if (p.info.authority != null) {
8675                    String names[] = p.info.authority.split(";");
8676                    p.info.authority = null;
8677                    for (int j = 0; j < names.length; j++) {
8678                        if (j == 1 && p.syncable) {
8679                            // We only want the first authority for a provider to possibly be
8680                            // syncable, so if we already added this provider using a different
8681                            // authority clear the syncable flag. We copy the provider before
8682                            // changing it because the mProviders object contains a reference
8683                            // to a provider that we don't want to change.
8684                            // Only do this for the second authority since the resulting provider
8685                            // object can be the same for all future authorities for this provider.
8686                            p = new PackageParser.Provider(p);
8687                            p.syncable = false;
8688                        }
8689                        if (!mProvidersByAuthority.containsKey(names[j])) {
8690                            mProvidersByAuthority.put(names[j], p);
8691                            if (p.info.authority == null) {
8692                                p.info.authority = names[j];
8693                            } else {
8694                                p.info.authority = p.info.authority + ";" + names[j];
8695                            }
8696                            if (DEBUG_PACKAGE_SCANNING) {
8697                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8698                                    Log.d(TAG, "Registered content provider: " + names[j]
8699                                            + ", className = " + p.info.name + ", isSyncable = "
8700                                            + p.info.isSyncable);
8701                            }
8702                        } else {
8703                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8704                            Slog.w(TAG, "Skipping provider name " + names[j] +
8705                                    " (in package " + pkg.applicationInfo.packageName +
8706                                    "): name already used by "
8707                                    + ((other != null && other.getComponentName() != null)
8708                                            ? other.getComponentName().getPackageName() : "?"));
8709                        }
8710                    }
8711                }
8712                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8713                    if (r == null) {
8714                        r = new StringBuilder(256);
8715                    } else {
8716                        r.append(' ');
8717                    }
8718                    r.append(p.info.name);
8719                }
8720            }
8721            if (r != null) {
8722                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8723            }
8724
8725            N = pkg.services.size();
8726            r = null;
8727            for (i=0; i<N; i++) {
8728                PackageParser.Service s = pkg.services.get(i);
8729                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8730                        s.info.processName, pkg.applicationInfo.uid);
8731                mServices.addService(s);
8732                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8733                    if (r == null) {
8734                        r = new StringBuilder(256);
8735                    } else {
8736                        r.append(' ');
8737                    }
8738                    r.append(s.info.name);
8739                }
8740            }
8741            if (r != null) {
8742                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8743            }
8744
8745            N = pkg.receivers.size();
8746            r = null;
8747            for (i=0; i<N; i++) {
8748                PackageParser.Activity a = pkg.receivers.get(i);
8749                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8750                        a.info.processName, pkg.applicationInfo.uid);
8751                mReceivers.addActivity(a, "receiver");
8752                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8753                    if (r == null) {
8754                        r = new StringBuilder(256);
8755                    } else {
8756                        r.append(' ');
8757                    }
8758                    r.append(a.info.name);
8759                }
8760            }
8761            if (r != null) {
8762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8763            }
8764
8765            N = pkg.activities.size();
8766            r = null;
8767            for (i=0; i<N; i++) {
8768                PackageParser.Activity a = pkg.activities.get(i);
8769                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8770                        a.info.processName, pkg.applicationInfo.uid);
8771                mActivities.addActivity(a, "activity");
8772                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8773                    if (r == null) {
8774                        r = new StringBuilder(256);
8775                    } else {
8776                        r.append(' ');
8777                    }
8778                    r.append(a.info.name);
8779                }
8780            }
8781            if (r != null) {
8782                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8783            }
8784
8785            N = pkg.permissionGroups.size();
8786            r = null;
8787            for (i=0; i<N; i++) {
8788                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8789                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8790                if (cur == null) {
8791                    mPermissionGroups.put(pg.info.name, pg);
8792                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8793                        if (r == null) {
8794                            r = new StringBuilder(256);
8795                        } else {
8796                            r.append(' ');
8797                        }
8798                        r.append(pg.info.name);
8799                    }
8800                } else {
8801                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8802                            + pg.info.packageName + " ignored: original from "
8803                            + cur.info.packageName);
8804                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8805                        if (r == null) {
8806                            r = new StringBuilder(256);
8807                        } else {
8808                            r.append(' ');
8809                        }
8810                        r.append("DUP:");
8811                        r.append(pg.info.name);
8812                    }
8813                }
8814            }
8815            if (r != null) {
8816                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8817            }
8818
8819            N = pkg.permissions.size();
8820            r = null;
8821            for (i=0; i<N; i++) {
8822                PackageParser.Permission p = pkg.permissions.get(i);
8823
8824                // Assume by default that we did not install this permission into the system.
8825                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8826
8827                // Now that permission groups have a special meaning, we ignore permission
8828                // groups for legacy apps to prevent unexpected behavior. In particular,
8829                // permissions for one app being granted to someone just becase they happen
8830                // to be in a group defined by another app (before this had no implications).
8831                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8832                    p.group = mPermissionGroups.get(p.info.group);
8833                    // Warn for a permission in an unknown group.
8834                    if (p.info.group != null && p.group == null) {
8835                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8836                                + p.info.packageName + " in an unknown group " + p.info.group);
8837                    }
8838                }
8839
8840                ArrayMap<String, BasePermission> permissionMap =
8841                        p.tree ? mSettings.mPermissionTrees
8842                                : mSettings.mPermissions;
8843                BasePermission bp = permissionMap.get(p.info.name);
8844
8845                // Allow system apps to redefine non-system permissions
8846                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8847                    final boolean currentOwnerIsSystem = (bp.perm != null
8848                            && isSystemApp(bp.perm.owner));
8849                    if (isSystemApp(p.owner)) {
8850                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8851                            // It's a built-in permission and no owner, take ownership now
8852                            bp.packageSetting = pkgSetting;
8853                            bp.perm = p;
8854                            bp.uid = pkg.applicationInfo.uid;
8855                            bp.sourcePackage = p.info.packageName;
8856                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8857                        } else if (!currentOwnerIsSystem) {
8858                            String msg = "New decl " + p.owner + " of permission  "
8859                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8860                            reportSettingsProblem(Log.WARN, msg);
8861                            bp = null;
8862                        }
8863                    }
8864                }
8865
8866                if (bp == null) {
8867                    bp = new BasePermission(p.info.name, p.info.packageName,
8868                            BasePermission.TYPE_NORMAL);
8869                    permissionMap.put(p.info.name, bp);
8870                }
8871
8872                if (bp.perm == null) {
8873                    if (bp.sourcePackage == null
8874                            || bp.sourcePackage.equals(p.info.packageName)) {
8875                        BasePermission tree = findPermissionTreeLP(p.info.name);
8876                        if (tree == null
8877                                || tree.sourcePackage.equals(p.info.packageName)) {
8878                            bp.packageSetting = pkgSetting;
8879                            bp.perm = p;
8880                            bp.uid = pkg.applicationInfo.uid;
8881                            bp.sourcePackage = p.info.packageName;
8882                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8883                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8884                                if (r == null) {
8885                                    r = new StringBuilder(256);
8886                                } else {
8887                                    r.append(' ');
8888                                }
8889                                r.append(p.info.name);
8890                            }
8891                        } else {
8892                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8893                                    + p.info.packageName + " ignored: base tree "
8894                                    + tree.name + " is from package "
8895                                    + tree.sourcePackage);
8896                        }
8897                    } else {
8898                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8899                                + p.info.packageName + " ignored: original from "
8900                                + bp.sourcePackage);
8901                    }
8902                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8903                    if (r == null) {
8904                        r = new StringBuilder(256);
8905                    } else {
8906                        r.append(' ');
8907                    }
8908                    r.append("DUP:");
8909                    r.append(p.info.name);
8910                }
8911                if (bp.perm == p) {
8912                    bp.protectionLevel = p.info.protectionLevel;
8913                }
8914            }
8915
8916            if (r != null) {
8917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8918            }
8919
8920            N = pkg.instrumentation.size();
8921            r = null;
8922            for (i=0; i<N; i++) {
8923                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8924                a.info.packageName = pkg.applicationInfo.packageName;
8925                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8926                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8927                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8928                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8929                a.info.dataDir = pkg.applicationInfo.dataDir;
8930                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8931                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8932
8933                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8934                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8935                mInstrumentation.put(a.getComponentName(), a);
8936                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8937                    if (r == null) {
8938                        r = new StringBuilder(256);
8939                    } else {
8940                        r.append(' ');
8941                    }
8942                    r.append(a.info.name);
8943                }
8944            }
8945            if (r != null) {
8946                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8947            }
8948
8949            if (pkg.protectedBroadcasts != null) {
8950                N = pkg.protectedBroadcasts.size();
8951                for (i=0; i<N; i++) {
8952                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8953                }
8954            }
8955
8956            pkgSetting.setTimeStamp(scanFileTime);
8957
8958            // Create idmap files for pairs of (packages, overlay packages).
8959            // Note: "android", ie framework-res.apk, is handled by native layers.
8960            if (pkg.mOverlayTarget != null) {
8961                // This is an overlay package.
8962                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8963                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8964                        mOverlays.put(pkg.mOverlayTarget,
8965                                new ArrayMap<String, PackageParser.Package>());
8966                    }
8967                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8968                    map.put(pkg.packageName, pkg);
8969                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8970                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8971                        createIdmapFailed = true;
8972                    }
8973                }
8974            } else if (mOverlays.containsKey(pkg.packageName) &&
8975                    !pkg.packageName.equals("android")) {
8976                // This is a regular package, with one or more known overlay packages.
8977                createIdmapsForPackageLI(pkg);
8978            }
8979        }
8980
8981        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8982
8983        if (createIdmapFailed) {
8984            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8985                    "scanPackageLI failed to createIdmap");
8986        }
8987        return pkg;
8988    }
8989
8990    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8991            PackageParser.Package update, UserHandle user) {
8992        if (existing.applicationInfo == null || update.applicationInfo == null) {
8993            // This isn't due to an app installation.
8994            return;
8995        }
8996
8997        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8998        final File newCodePath = new File(update.applicationInfo.getCodePath());
8999
9000        // The codePath hasn't changed, so there's nothing for us to do.
9001        if (Objects.equals(oldCodePath, newCodePath)) {
9002            return;
9003        }
9004
9005        File canonicalNewCodePath;
9006        try {
9007            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9008        } catch (IOException e) {
9009            Slog.w(TAG, "Failed to get canonical path.", e);
9010            return;
9011        }
9012
9013        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9014        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9015        // that the last component of the path (i.e, the name) doesn't need canonicalization
9016        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9017        // but may change in the future. Hopefully this function won't exist at that point.
9018        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9019                oldCodePath.getName());
9020
9021        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9022        // with "@".
9023        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9024        if (!oldMarkerPrefix.endsWith("@")) {
9025            oldMarkerPrefix += "@";
9026        }
9027        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9028        if (!newMarkerPrefix.endsWith("@")) {
9029            newMarkerPrefix += "@";
9030        }
9031
9032        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9033        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9034        for (String updatedPath : updatedPaths) {
9035            String updatedPathName = new File(updatedPath).getName();
9036            markerSuffixes.add(updatedPathName.replace('/', '@'));
9037        }
9038
9039        for (int userId : resolveUserIds(user.getIdentifier())) {
9040            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9041
9042            for (String markerSuffix : markerSuffixes) {
9043                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9044                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9045                if (oldForeignUseMark.exists()) {
9046                    try {
9047                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9048                                newForeignUseMark.getAbsolutePath());
9049                    } catch (ErrnoException e) {
9050                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9051                        oldForeignUseMark.delete();
9052                    }
9053                }
9054            }
9055        }
9056    }
9057
9058    /**
9059     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9060     * is derived purely on the basis of the contents of {@code scanFile} and
9061     * {@code cpuAbiOverride}.
9062     *
9063     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9064     */
9065    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9066                                 String cpuAbiOverride, boolean extractLibs)
9067            throws PackageManagerException {
9068        // TODO: We can probably be smarter about this stuff. For installed apps,
9069        // we can calculate this information at install time once and for all. For
9070        // system apps, we can probably assume that this information doesn't change
9071        // after the first boot scan. As things stand, we do lots of unnecessary work.
9072
9073        // Give ourselves some initial paths; we'll come back for another
9074        // pass once we've determined ABI below.
9075        setNativeLibraryPaths(pkg);
9076
9077        // We would never need to extract libs for forward-locked and external packages,
9078        // since the container service will do it for us. We shouldn't attempt to
9079        // extract libs from system app when it was not updated.
9080        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9081                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9082            extractLibs = false;
9083        }
9084
9085        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9086        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9087
9088        NativeLibraryHelper.Handle handle = null;
9089        try {
9090            handle = NativeLibraryHelper.Handle.create(pkg);
9091            // TODO(multiArch): This can be null for apps that didn't go through the
9092            // usual installation process. We can calculate it again, like we
9093            // do during install time.
9094            //
9095            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9096            // unnecessary.
9097            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9098
9099            // Null out the abis so that they can be recalculated.
9100            pkg.applicationInfo.primaryCpuAbi = null;
9101            pkg.applicationInfo.secondaryCpuAbi = null;
9102            if (isMultiArch(pkg.applicationInfo)) {
9103                // Warn if we've set an abiOverride for multi-lib packages..
9104                // By definition, we need to copy both 32 and 64 bit libraries for
9105                // such packages.
9106                if (pkg.cpuAbiOverride != null
9107                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9108                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9109                }
9110
9111                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9112                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9113                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9114                    if (extractLibs) {
9115                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9116                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9117                                useIsaSpecificSubdirs);
9118                    } else {
9119                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9120                    }
9121                }
9122
9123                maybeThrowExceptionForMultiArchCopy(
9124                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9125
9126                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9127                    if (extractLibs) {
9128                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9129                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9130                                useIsaSpecificSubdirs);
9131                    } else {
9132                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9133                    }
9134                }
9135
9136                maybeThrowExceptionForMultiArchCopy(
9137                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9138
9139                if (abi64 >= 0) {
9140                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9141                }
9142
9143                if (abi32 >= 0) {
9144                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9145                    if (abi64 >= 0) {
9146                        if (pkg.use32bitAbi) {
9147                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9148                            pkg.applicationInfo.primaryCpuAbi = abi;
9149                        } else {
9150                            pkg.applicationInfo.secondaryCpuAbi = abi;
9151                        }
9152                    } else {
9153                        pkg.applicationInfo.primaryCpuAbi = abi;
9154                    }
9155                }
9156
9157            } else {
9158                String[] abiList = (cpuAbiOverride != null) ?
9159                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9160
9161                // Enable gross and lame hacks for apps that are built with old
9162                // SDK tools. We must scan their APKs for renderscript bitcode and
9163                // not launch them if it's present. Don't bother checking on devices
9164                // that don't have 64 bit support.
9165                boolean needsRenderScriptOverride = false;
9166                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9167                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9168                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9169                    needsRenderScriptOverride = true;
9170                }
9171
9172                final int copyRet;
9173                if (extractLibs) {
9174                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9175                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9176                } else {
9177                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9178                }
9179
9180                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9181                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9182                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9183                }
9184
9185                if (copyRet >= 0) {
9186                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9187                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9188                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9189                } else if (needsRenderScriptOverride) {
9190                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9191                }
9192            }
9193        } catch (IOException ioe) {
9194            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9195        } finally {
9196            IoUtils.closeQuietly(handle);
9197        }
9198
9199        // Now that we've calculated the ABIs and determined if it's an internal app,
9200        // we will go ahead and populate the nativeLibraryPath.
9201        setNativeLibraryPaths(pkg);
9202    }
9203
9204    /**
9205     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9206     * i.e, so that all packages can be run inside a single process if required.
9207     *
9208     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9209     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9210     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9211     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9212     * updating a package that belongs to a shared user.
9213     *
9214     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9215     * adds unnecessary complexity.
9216     */
9217    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9218            PackageParser.Package scannedPackage, boolean bootComplete) {
9219        String requiredInstructionSet = null;
9220        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9221            requiredInstructionSet = VMRuntime.getInstructionSet(
9222                     scannedPackage.applicationInfo.primaryCpuAbi);
9223        }
9224
9225        PackageSetting requirer = null;
9226        for (PackageSetting ps : packagesForUser) {
9227            // If packagesForUser contains scannedPackage, we skip it. This will happen
9228            // when scannedPackage is an update of an existing package. Without this check,
9229            // we will never be able to change the ABI of any package belonging to a shared
9230            // user, even if it's compatible with other packages.
9231            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9232                if (ps.primaryCpuAbiString == null) {
9233                    continue;
9234                }
9235
9236                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9237                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9238                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9239                    // this but there's not much we can do.
9240                    String errorMessage = "Instruction set mismatch, "
9241                            + ((requirer == null) ? "[caller]" : requirer)
9242                            + " requires " + requiredInstructionSet + " whereas " + ps
9243                            + " requires " + instructionSet;
9244                    Slog.w(TAG, errorMessage);
9245                }
9246
9247                if (requiredInstructionSet == null) {
9248                    requiredInstructionSet = instructionSet;
9249                    requirer = ps;
9250                }
9251            }
9252        }
9253
9254        if (requiredInstructionSet != null) {
9255            String adjustedAbi;
9256            if (requirer != null) {
9257                // requirer != null implies that either scannedPackage was null or that scannedPackage
9258                // did not require an ABI, in which case we have to adjust scannedPackage to match
9259                // the ABI of the set (which is the same as requirer's ABI)
9260                adjustedAbi = requirer.primaryCpuAbiString;
9261                if (scannedPackage != null) {
9262                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9263                }
9264            } else {
9265                // requirer == null implies that we're updating all ABIs in the set to
9266                // match scannedPackage.
9267                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9268            }
9269
9270            for (PackageSetting ps : packagesForUser) {
9271                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9272                    if (ps.primaryCpuAbiString != null) {
9273                        continue;
9274                    }
9275
9276                    ps.primaryCpuAbiString = adjustedAbi;
9277                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9278                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9279                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9280                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9281                                + " (requirer="
9282                                + (requirer == null ? "null" : requirer.pkg.packageName)
9283                                + ", scannedPackage="
9284                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9285                                + ")");
9286                        try {
9287                            mInstaller.rmdex(ps.codePathString,
9288                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9289                        } catch (InstallerException ignored) {
9290                        }
9291                    }
9292                }
9293            }
9294        }
9295    }
9296
9297    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9298        synchronized (mPackages) {
9299            mResolverReplaced = true;
9300            // Set up information for custom user intent resolution activity.
9301            mResolveActivity.applicationInfo = pkg.applicationInfo;
9302            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9303            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9304            mResolveActivity.processName = pkg.applicationInfo.packageName;
9305            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9306            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9307                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9308            mResolveActivity.theme = 0;
9309            mResolveActivity.exported = true;
9310            mResolveActivity.enabled = true;
9311            mResolveInfo.activityInfo = mResolveActivity;
9312            mResolveInfo.priority = 0;
9313            mResolveInfo.preferredOrder = 0;
9314            mResolveInfo.match = 0;
9315            mResolveComponentName = mCustomResolverComponentName;
9316            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9317                    mResolveComponentName);
9318        }
9319    }
9320
9321    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9322        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9323
9324        // Set up information for ephemeral installer activity
9325        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9326        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9327        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9328        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9329        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9330        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9331                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9332        mEphemeralInstallerActivity.theme = 0;
9333        mEphemeralInstallerActivity.exported = true;
9334        mEphemeralInstallerActivity.enabled = true;
9335        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9336        mEphemeralInstallerInfo.priority = 0;
9337        mEphemeralInstallerInfo.preferredOrder = 0;
9338        mEphemeralInstallerInfo.match = 0;
9339
9340        if (DEBUG_EPHEMERAL) {
9341            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9342        }
9343    }
9344
9345    private static String calculateBundledApkRoot(final String codePathString) {
9346        final File codePath = new File(codePathString);
9347        final File codeRoot;
9348        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9349            codeRoot = Environment.getRootDirectory();
9350        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9351            codeRoot = Environment.getOemDirectory();
9352        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9353            codeRoot = Environment.getVendorDirectory();
9354        } else {
9355            // Unrecognized code path; take its top real segment as the apk root:
9356            // e.g. /something/app/blah.apk => /something
9357            try {
9358                File f = codePath.getCanonicalFile();
9359                File parent = f.getParentFile();    // non-null because codePath is a file
9360                File tmp;
9361                while ((tmp = parent.getParentFile()) != null) {
9362                    f = parent;
9363                    parent = tmp;
9364                }
9365                codeRoot = f;
9366                Slog.w(TAG, "Unrecognized code path "
9367                        + codePath + " - using " + codeRoot);
9368            } catch (IOException e) {
9369                // Can't canonicalize the code path -- shenanigans?
9370                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9371                return Environment.getRootDirectory().getPath();
9372            }
9373        }
9374        return codeRoot.getPath();
9375    }
9376
9377    /**
9378     * Derive and set the location of native libraries for the given package,
9379     * which varies depending on where and how the package was installed.
9380     */
9381    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9382        final ApplicationInfo info = pkg.applicationInfo;
9383        final String codePath = pkg.codePath;
9384        final File codeFile = new File(codePath);
9385        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9386        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9387
9388        info.nativeLibraryRootDir = null;
9389        info.nativeLibraryRootRequiresIsa = false;
9390        info.nativeLibraryDir = null;
9391        info.secondaryNativeLibraryDir = null;
9392
9393        if (isApkFile(codeFile)) {
9394            // Monolithic install
9395            if (bundledApp) {
9396                // If "/system/lib64/apkname" exists, assume that is the per-package
9397                // native library directory to use; otherwise use "/system/lib/apkname".
9398                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9399                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9400                        getPrimaryInstructionSet(info));
9401
9402                // This is a bundled system app so choose the path based on the ABI.
9403                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9404                // is just the default path.
9405                final String apkName = deriveCodePathName(codePath);
9406                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9407                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9408                        apkName).getAbsolutePath();
9409
9410                if (info.secondaryCpuAbi != null) {
9411                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9412                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9413                            secondaryLibDir, apkName).getAbsolutePath();
9414                }
9415            } else if (asecApp) {
9416                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9417                        .getAbsolutePath();
9418            } else {
9419                final String apkName = deriveCodePathName(codePath);
9420                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9421                        .getAbsolutePath();
9422            }
9423
9424            info.nativeLibraryRootRequiresIsa = false;
9425            info.nativeLibraryDir = info.nativeLibraryRootDir;
9426        } else {
9427            // Cluster install
9428            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9429            info.nativeLibraryRootRequiresIsa = true;
9430
9431            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9432                    getPrimaryInstructionSet(info)).getAbsolutePath();
9433
9434            if (info.secondaryCpuAbi != null) {
9435                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9436                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9437            }
9438        }
9439    }
9440
9441    /**
9442     * Calculate the abis and roots for a bundled app. These can uniquely
9443     * be determined from the contents of the system partition, i.e whether
9444     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9445     * of this information, and instead assume that the system was built
9446     * sensibly.
9447     */
9448    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9449                                           PackageSetting pkgSetting) {
9450        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9451
9452        // If "/system/lib64/apkname" exists, assume that is the per-package
9453        // native library directory to use; otherwise use "/system/lib/apkname".
9454        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9455        setBundledAppAbi(pkg, apkRoot, apkName);
9456        // pkgSetting might be null during rescan following uninstall of updates
9457        // to a bundled app, so accommodate that possibility.  The settings in
9458        // that case will be established later from the parsed package.
9459        //
9460        // If the settings aren't null, sync them up with what we've just derived.
9461        // note that apkRoot isn't stored in the package settings.
9462        if (pkgSetting != null) {
9463            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9464            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9465        }
9466    }
9467
9468    /**
9469     * Deduces the ABI of a bundled app and sets the relevant fields on the
9470     * parsed pkg object.
9471     *
9472     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9473     *        under which system libraries are installed.
9474     * @param apkName the name of the installed package.
9475     */
9476    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9477        final File codeFile = new File(pkg.codePath);
9478
9479        final boolean has64BitLibs;
9480        final boolean has32BitLibs;
9481        if (isApkFile(codeFile)) {
9482            // Monolithic install
9483            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9484            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9485        } else {
9486            // Cluster install
9487            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9488            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9489                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9490                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9491                has64BitLibs = (new File(rootDir, isa)).exists();
9492            } else {
9493                has64BitLibs = false;
9494            }
9495            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9496                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9497                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9498                has32BitLibs = (new File(rootDir, isa)).exists();
9499            } else {
9500                has32BitLibs = false;
9501            }
9502        }
9503
9504        if (has64BitLibs && !has32BitLibs) {
9505            // The package has 64 bit libs, but not 32 bit libs. Its primary
9506            // ABI should be 64 bit. We can safely assume here that the bundled
9507            // native libraries correspond to the most preferred ABI in the list.
9508
9509            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9510            pkg.applicationInfo.secondaryCpuAbi = null;
9511        } else if (has32BitLibs && !has64BitLibs) {
9512            // The package has 32 bit libs but not 64 bit libs. Its primary
9513            // ABI should be 32 bit.
9514
9515            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9516            pkg.applicationInfo.secondaryCpuAbi = null;
9517        } else if (has32BitLibs && has64BitLibs) {
9518            // The application has both 64 and 32 bit bundled libraries. We check
9519            // here that the app declares multiArch support, and warn if it doesn't.
9520            //
9521            // We will be lenient here and record both ABIs. The primary will be the
9522            // ABI that's higher on the list, i.e, a device that's configured to prefer
9523            // 64 bit apps will see a 64 bit primary ABI,
9524
9525            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9526                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9527            }
9528
9529            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9530                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9531                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9532            } else {
9533                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9534                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9535            }
9536        } else {
9537            pkg.applicationInfo.primaryCpuAbi = null;
9538            pkg.applicationInfo.secondaryCpuAbi = null;
9539        }
9540    }
9541
9542    private void killApplication(String pkgName, int appId, String reason) {
9543        // Request the ActivityManager to kill the process(only for existing packages)
9544        // so that we do not end up in a confused state while the user is still using the older
9545        // version of the application while the new one gets installed.
9546        final long token = Binder.clearCallingIdentity();
9547        try {
9548            IActivityManager am = ActivityManagerNative.getDefault();
9549            if (am != null) {
9550                try {
9551                    am.killApplicationWithAppId(pkgName, appId, reason);
9552                } catch (RemoteException e) {
9553                }
9554            }
9555        } finally {
9556            Binder.restoreCallingIdentity(token);
9557        }
9558    }
9559
9560    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9561        // Remove the parent package setting
9562        PackageSetting ps = (PackageSetting) pkg.mExtras;
9563        if (ps != null) {
9564            removePackageLI(ps, chatty);
9565        }
9566        // Remove the child package setting
9567        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9568        for (int i = 0; i < childCount; i++) {
9569            PackageParser.Package childPkg = pkg.childPackages.get(i);
9570            ps = (PackageSetting) childPkg.mExtras;
9571            if (ps != null) {
9572                removePackageLI(ps, chatty);
9573            }
9574        }
9575    }
9576
9577    void removePackageLI(PackageSetting ps, boolean chatty) {
9578        if (DEBUG_INSTALL) {
9579            if (chatty)
9580                Log.d(TAG, "Removing package " + ps.name);
9581        }
9582
9583        // writer
9584        synchronized (mPackages) {
9585            mPackages.remove(ps.name);
9586            final PackageParser.Package pkg = ps.pkg;
9587            if (pkg != null) {
9588                cleanPackageDataStructuresLILPw(pkg, chatty);
9589            }
9590        }
9591    }
9592
9593    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9594        if (DEBUG_INSTALL) {
9595            if (chatty)
9596                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9597        }
9598
9599        // writer
9600        synchronized (mPackages) {
9601            // Remove the parent package
9602            mPackages.remove(pkg.applicationInfo.packageName);
9603            cleanPackageDataStructuresLILPw(pkg, chatty);
9604
9605            // Remove the child packages
9606            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9607            for (int i = 0; i < childCount; i++) {
9608                PackageParser.Package childPkg = pkg.childPackages.get(i);
9609                mPackages.remove(childPkg.applicationInfo.packageName);
9610                cleanPackageDataStructuresLILPw(childPkg, chatty);
9611            }
9612        }
9613    }
9614
9615    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9616        int N = pkg.providers.size();
9617        StringBuilder r = null;
9618        int i;
9619        for (i=0; i<N; i++) {
9620            PackageParser.Provider p = pkg.providers.get(i);
9621            mProviders.removeProvider(p);
9622            if (p.info.authority == null) {
9623
9624                /* There was another ContentProvider with this authority when
9625                 * this app was installed so this authority is null,
9626                 * Ignore it as we don't have to unregister the provider.
9627                 */
9628                continue;
9629            }
9630            String names[] = p.info.authority.split(";");
9631            for (int j = 0; j < names.length; j++) {
9632                if (mProvidersByAuthority.get(names[j]) == p) {
9633                    mProvidersByAuthority.remove(names[j]);
9634                    if (DEBUG_REMOVE) {
9635                        if (chatty)
9636                            Log.d(TAG, "Unregistered content provider: " + names[j]
9637                                    + ", className = " + p.info.name + ", isSyncable = "
9638                                    + p.info.isSyncable);
9639                    }
9640                }
9641            }
9642            if (DEBUG_REMOVE && chatty) {
9643                if (r == null) {
9644                    r = new StringBuilder(256);
9645                } else {
9646                    r.append(' ');
9647                }
9648                r.append(p.info.name);
9649            }
9650        }
9651        if (r != null) {
9652            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9653        }
9654
9655        N = pkg.services.size();
9656        r = null;
9657        for (i=0; i<N; i++) {
9658            PackageParser.Service s = pkg.services.get(i);
9659            mServices.removeService(s);
9660            if (chatty) {
9661                if (r == null) {
9662                    r = new StringBuilder(256);
9663                } else {
9664                    r.append(' ');
9665                }
9666                r.append(s.info.name);
9667            }
9668        }
9669        if (r != null) {
9670            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9671        }
9672
9673        N = pkg.receivers.size();
9674        r = null;
9675        for (i=0; i<N; i++) {
9676            PackageParser.Activity a = pkg.receivers.get(i);
9677            mReceivers.removeActivity(a, "receiver");
9678            if (DEBUG_REMOVE && chatty) {
9679                if (r == null) {
9680                    r = new StringBuilder(256);
9681                } else {
9682                    r.append(' ');
9683                }
9684                r.append(a.info.name);
9685            }
9686        }
9687        if (r != null) {
9688            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9689        }
9690
9691        N = pkg.activities.size();
9692        r = null;
9693        for (i=0; i<N; i++) {
9694            PackageParser.Activity a = pkg.activities.get(i);
9695            mActivities.removeActivity(a, "activity");
9696            if (DEBUG_REMOVE && chatty) {
9697                if (r == null) {
9698                    r = new StringBuilder(256);
9699                } else {
9700                    r.append(' ');
9701                }
9702                r.append(a.info.name);
9703            }
9704        }
9705        if (r != null) {
9706            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9707        }
9708
9709        N = pkg.permissions.size();
9710        r = null;
9711        for (i=0; i<N; i++) {
9712            PackageParser.Permission p = pkg.permissions.get(i);
9713            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9714            if (bp == null) {
9715                bp = mSettings.mPermissionTrees.get(p.info.name);
9716            }
9717            if (bp != null && bp.perm == p) {
9718                bp.perm = null;
9719                if (DEBUG_REMOVE && chatty) {
9720                    if (r == null) {
9721                        r = new StringBuilder(256);
9722                    } else {
9723                        r.append(' ');
9724                    }
9725                    r.append(p.info.name);
9726                }
9727            }
9728            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9729                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9730                if (appOpPkgs != null) {
9731                    appOpPkgs.remove(pkg.packageName);
9732                }
9733            }
9734        }
9735        if (r != null) {
9736            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9737        }
9738
9739        N = pkg.requestedPermissions.size();
9740        r = null;
9741        for (i=0; i<N; i++) {
9742            String perm = pkg.requestedPermissions.get(i);
9743            BasePermission bp = mSettings.mPermissions.get(perm);
9744            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9745                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9746                if (appOpPkgs != null) {
9747                    appOpPkgs.remove(pkg.packageName);
9748                    if (appOpPkgs.isEmpty()) {
9749                        mAppOpPermissionPackages.remove(perm);
9750                    }
9751                }
9752            }
9753        }
9754        if (r != null) {
9755            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9756        }
9757
9758        N = pkg.instrumentation.size();
9759        r = null;
9760        for (i=0; i<N; i++) {
9761            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9762            mInstrumentation.remove(a.getComponentName());
9763            if (DEBUG_REMOVE && chatty) {
9764                if (r == null) {
9765                    r = new StringBuilder(256);
9766                } else {
9767                    r.append(' ');
9768                }
9769                r.append(a.info.name);
9770            }
9771        }
9772        if (r != null) {
9773            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9774        }
9775
9776        r = null;
9777        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9778            // Only system apps can hold shared libraries.
9779            if (pkg.libraryNames != null) {
9780                for (i=0; i<pkg.libraryNames.size(); i++) {
9781                    String name = pkg.libraryNames.get(i);
9782                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9783                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9784                        mSharedLibraries.remove(name);
9785                        if (DEBUG_REMOVE && chatty) {
9786                            if (r == null) {
9787                                r = new StringBuilder(256);
9788                            } else {
9789                                r.append(' ');
9790                            }
9791                            r.append(name);
9792                        }
9793                    }
9794                }
9795            }
9796        }
9797        if (r != null) {
9798            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9799        }
9800    }
9801
9802    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9803        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9804            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9805                return true;
9806            }
9807        }
9808        return false;
9809    }
9810
9811    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9812    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9813    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9814
9815    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9816        // Update the parent permissions
9817        updatePermissionsLPw(pkg.packageName, pkg, flags);
9818        // Update the child permissions
9819        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9820        for (int i = 0; i < childCount; i++) {
9821            PackageParser.Package childPkg = pkg.childPackages.get(i);
9822            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9823        }
9824    }
9825
9826    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9827            int flags) {
9828        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9829        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9830    }
9831
9832    private void updatePermissionsLPw(String changingPkg,
9833            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9834        // Make sure there are no dangling permission trees.
9835        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9836        while (it.hasNext()) {
9837            final BasePermission bp = it.next();
9838            if (bp.packageSetting == null) {
9839                // We may not yet have parsed the package, so just see if
9840                // we still know about its settings.
9841                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9842            }
9843            if (bp.packageSetting == null) {
9844                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9845                        + " from package " + bp.sourcePackage);
9846                it.remove();
9847            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9848                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9849                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9850                            + " from package " + bp.sourcePackage);
9851                    flags |= UPDATE_PERMISSIONS_ALL;
9852                    it.remove();
9853                }
9854            }
9855        }
9856
9857        // Make sure all dynamic permissions have been assigned to a package,
9858        // and make sure there are no dangling permissions.
9859        it = mSettings.mPermissions.values().iterator();
9860        while (it.hasNext()) {
9861            final BasePermission bp = it.next();
9862            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9863                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9864                        + bp.name + " pkg=" + bp.sourcePackage
9865                        + " info=" + bp.pendingInfo);
9866                if (bp.packageSetting == null && bp.pendingInfo != null) {
9867                    final BasePermission tree = findPermissionTreeLP(bp.name);
9868                    if (tree != null && tree.perm != null) {
9869                        bp.packageSetting = tree.packageSetting;
9870                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9871                                new PermissionInfo(bp.pendingInfo));
9872                        bp.perm.info.packageName = tree.perm.info.packageName;
9873                        bp.perm.info.name = bp.name;
9874                        bp.uid = tree.uid;
9875                    }
9876                }
9877            }
9878            if (bp.packageSetting == null) {
9879                // We may not yet have parsed the package, so just see if
9880                // we still know about its settings.
9881                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9882            }
9883            if (bp.packageSetting == null) {
9884                Slog.w(TAG, "Removing dangling permission: " + bp.name
9885                        + " from package " + bp.sourcePackage);
9886                it.remove();
9887            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9888                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9889                    Slog.i(TAG, "Removing old permission: " + bp.name
9890                            + " from package " + bp.sourcePackage);
9891                    flags |= UPDATE_PERMISSIONS_ALL;
9892                    it.remove();
9893                }
9894            }
9895        }
9896
9897        // Now update the permissions for all packages, in particular
9898        // replace the granted permissions of the system packages.
9899        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9900            for (PackageParser.Package pkg : mPackages.values()) {
9901                if (pkg != pkgInfo) {
9902                    // Only replace for packages on requested volume
9903                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9904                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9905                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9906                    grantPermissionsLPw(pkg, replace, changingPkg);
9907                }
9908            }
9909        }
9910
9911        if (pkgInfo != null) {
9912            // Only replace for packages on requested volume
9913            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9914            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9915                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9916            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9917        }
9918    }
9919
9920    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9921            String packageOfInterest) {
9922        // IMPORTANT: There are two types of permissions: install and runtime.
9923        // Install time permissions are granted when the app is installed to
9924        // all device users and users added in the future. Runtime permissions
9925        // are granted at runtime explicitly to specific users. Normal and signature
9926        // protected permissions are install time permissions. Dangerous permissions
9927        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9928        // otherwise they are runtime permissions. This function does not manage
9929        // runtime permissions except for the case an app targeting Lollipop MR1
9930        // being upgraded to target a newer SDK, in which case dangerous permissions
9931        // are transformed from install time to runtime ones.
9932
9933        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9934        if (ps == null) {
9935            return;
9936        }
9937
9938        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9939
9940        PermissionsState permissionsState = ps.getPermissionsState();
9941        PermissionsState origPermissions = permissionsState;
9942
9943        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9944
9945        boolean runtimePermissionsRevoked = false;
9946        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9947
9948        boolean changedInstallPermission = false;
9949
9950        if (replace) {
9951            ps.installPermissionsFixed = false;
9952            if (!ps.isSharedUser()) {
9953                origPermissions = new PermissionsState(permissionsState);
9954                permissionsState.reset();
9955            } else {
9956                // We need to know only about runtime permission changes since the
9957                // calling code always writes the install permissions state but
9958                // the runtime ones are written only if changed. The only cases of
9959                // changed runtime permissions here are promotion of an install to
9960                // runtime and revocation of a runtime from a shared user.
9961                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9962                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9963                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9964                    runtimePermissionsRevoked = true;
9965                }
9966            }
9967        }
9968
9969        permissionsState.setGlobalGids(mGlobalGids);
9970
9971        final int N = pkg.requestedPermissions.size();
9972        for (int i=0; i<N; i++) {
9973            final String name = pkg.requestedPermissions.get(i);
9974            final BasePermission bp = mSettings.mPermissions.get(name);
9975
9976            if (DEBUG_INSTALL) {
9977                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9978            }
9979
9980            if (bp == null || bp.packageSetting == null) {
9981                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9982                    Slog.w(TAG, "Unknown permission " + name
9983                            + " in package " + pkg.packageName);
9984                }
9985                continue;
9986            }
9987
9988            final String perm = bp.name;
9989            boolean allowedSig = false;
9990            int grant = GRANT_DENIED;
9991
9992            // Keep track of app op permissions.
9993            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9994                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9995                if (pkgs == null) {
9996                    pkgs = new ArraySet<>();
9997                    mAppOpPermissionPackages.put(bp.name, pkgs);
9998                }
9999                pkgs.add(pkg.packageName);
10000            }
10001
10002            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10003            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10004                    >= Build.VERSION_CODES.M;
10005            switch (level) {
10006                case PermissionInfo.PROTECTION_NORMAL: {
10007                    // For all apps normal permissions are install time ones.
10008                    grant = GRANT_INSTALL;
10009                } break;
10010
10011                case PermissionInfo.PROTECTION_DANGEROUS: {
10012                    // If a permission review is required for legacy apps we represent
10013                    // their permissions as always granted runtime ones since we need
10014                    // to keep the review required permission flag per user while an
10015                    // install permission's state is shared across all users.
10016                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10017                        // For legacy apps dangerous permissions are install time ones.
10018                        grant = GRANT_INSTALL;
10019                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10020                        // For legacy apps that became modern, install becomes runtime.
10021                        grant = GRANT_UPGRADE;
10022                    } else if (mPromoteSystemApps
10023                            && isSystemApp(ps)
10024                            && mExistingSystemPackages.contains(ps.name)) {
10025                        // For legacy system apps, install becomes runtime.
10026                        // We cannot check hasInstallPermission() for system apps since those
10027                        // permissions were granted implicitly and not persisted pre-M.
10028                        grant = GRANT_UPGRADE;
10029                    } else {
10030                        // For modern apps keep runtime permissions unchanged.
10031                        grant = GRANT_RUNTIME;
10032                    }
10033                } break;
10034
10035                case PermissionInfo.PROTECTION_SIGNATURE: {
10036                    // For all apps signature permissions are install time ones.
10037                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10038                    if (allowedSig) {
10039                        grant = GRANT_INSTALL;
10040                    }
10041                } break;
10042            }
10043
10044            if (DEBUG_INSTALL) {
10045                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10046            }
10047
10048            if (grant != GRANT_DENIED) {
10049                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10050                    // If this is an existing, non-system package, then
10051                    // we can't add any new permissions to it.
10052                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10053                        // Except...  if this is a permission that was added
10054                        // to the platform (note: need to only do this when
10055                        // updating the platform).
10056                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10057                            grant = GRANT_DENIED;
10058                        }
10059                    }
10060                }
10061
10062                switch (grant) {
10063                    case GRANT_INSTALL: {
10064                        // Revoke this as runtime permission to handle the case of
10065                        // a runtime permission being downgraded to an install one.
10066                        // Also in permission review mode we keep dangerous permissions
10067                        // for legacy apps
10068                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10069                            if (origPermissions.getRuntimePermissionState(
10070                                    bp.name, userId) != null) {
10071                                // Revoke the runtime permission and clear the flags.
10072                                origPermissions.revokeRuntimePermission(bp, userId);
10073                                origPermissions.updatePermissionFlags(bp, userId,
10074                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10075                                // If we revoked a permission permission, we have to write.
10076                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10077                                        changedRuntimePermissionUserIds, userId);
10078                            }
10079                        }
10080                        // Grant an install permission.
10081                        if (permissionsState.grantInstallPermission(bp) !=
10082                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10083                            changedInstallPermission = true;
10084                        }
10085                    } break;
10086
10087                    case GRANT_RUNTIME: {
10088                        // Grant previously granted runtime permissions.
10089                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10090                            PermissionState permissionState = origPermissions
10091                                    .getRuntimePermissionState(bp.name, userId);
10092                            int flags = permissionState != null
10093                                    ? permissionState.getFlags() : 0;
10094                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10095                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10096                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10097                                    // If we cannot put the permission as it was, we have to write.
10098                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10099                                            changedRuntimePermissionUserIds, userId);
10100                                }
10101                                // If the app supports runtime permissions no need for a review.
10102                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10103                                        && appSupportsRuntimePermissions
10104                                        && (flags & PackageManager
10105                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10106                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10107                                    // Since we changed the flags, we have to write.
10108                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10109                                            changedRuntimePermissionUserIds, userId);
10110                                }
10111                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10112                                    && !appSupportsRuntimePermissions) {
10113                                // For legacy apps that need a permission review, every new
10114                                // runtime permission is granted but it is pending a review.
10115                                // We also need to review only platform defined runtime
10116                                // permissions as these are the only ones the platform knows
10117                                // how to disable the API to simulate revocation as legacy
10118                                // apps don't expect to run with revoked permissions.
10119                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10120                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10121                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10122                                        // We changed the flags, hence have to write.
10123                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10124                                                changedRuntimePermissionUserIds, userId);
10125                                    }
10126                                }
10127                                if (permissionsState.grantRuntimePermission(bp, userId)
10128                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10129                                    // We changed the permission, hence have to write.
10130                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10131                                            changedRuntimePermissionUserIds, userId);
10132                                }
10133                            }
10134                            // Propagate the permission flags.
10135                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10136                        }
10137                    } break;
10138
10139                    case GRANT_UPGRADE: {
10140                        // Grant runtime permissions for a previously held install permission.
10141                        PermissionState permissionState = origPermissions
10142                                .getInstallPermissionState(bp.name);
10143                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10144
10145                        if (origPermissions.revokeInstallPermission(bp)
10146                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10147                            // We will be transferring the permission flags, so clear them.
10148                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10149                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10150                            changedInstallPermission = true;
10151                        }
10152
10153                        // If the permission is not to be promoted to runtime we ignore it and
10154                        // also its other flags as they are not applicable to install permissions.
10155                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10156                            for (int userId : currentUserIds) {
10157                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10158                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10159                                    // Transfer the permission flags.
10160                                    permissionsState.updatePermissionFlags(bp, userId,
10161                                            flags, flags);
10162                                    // If we granted the permission, we have to write.
10163                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10164                                            changedRuntimePermissionUserIds, userId);
10165                                }
10166                            }
10167                        }
10168                    } break;
10169
10170                    default: {
10171                        if (packageOfInterest == null
10172                                || packageOfInterest.equals(pkg.packageName)) {
10173                            Slog.w(TAG, "Not granting permission " + perm
10174                                    + " to package " + pkg.packageName
10175                                    + " because it was previously installed without");
10176                        }
10177                    } break;
10178                }
10179            } else {
10180                if (permissionsState.revokeInstallPermission(bp) !=
10181                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10182                    // Also drop the permission flags.
10183                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10184                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10185                    changedInstallPermission = true;
10186                    Slog.i(TAG, "Un-granting permission " + perm
10187                            + " from package " + pkg.packageName
10188                            + " (protectionLevel=" + bp.protectionLevel
10189                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10190                            + ")");
10191                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10192                    // Don't print warning for app op permissions, since it is fine for them
10193                    // not to be granted, there is a UI for the user to decide.
10194                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10195                        Slog.w(TAG, "Not granting permission " + perm
10196                                + " to package " + pkg.packageName
10197                                + " (protectionLevel=" + bp.protectionLevel
10198                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10199                                + ")");
10200                    }
10201                }
10202            }
10203        }
10204
10205        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10206                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10207            // This is the first that we have heard about this package, so the
10208            // permissions we have now selected are fixed until explicitly
10209            // changed.
10210            ps.installPermissionsFixed = true;
10211        }
10212
10213        // Persist the runtime permissions state for users with changes. If permissions
10214        // were revoked because no app in the shared user declares them we have to
10215        // write synchronously to avoid losing runtime permissions state.
10216        for (int userId : changedRuntimePermissionUserIds) {
10217            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10218        }
10219
10220        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10221    }
10222
10223    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10224        boolean allowed = false;
10225        final int NP = PackageParser.NEW_PERMISSIONS.length;
10226        for (int ip=0; ip<NP; ip++) {
10227            final PackageParser.NewPermissionInfo npi
10228                    = PackageParser.NEW_PERMISSIONS[ip];
10229            if (npi.name.equals(perm)
10230                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10231                allowed = true;
10232                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10233                        + pkg.packageName);
10234                break;
10235            }
10236        }
10237        return allowed;
10238    }
10239
10240    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10241            BasePermission bp, PermissionsState origPermissions) {
10242        boolean allowed;
10243        allowed = (compareSignatures(
10244                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10245                        == PackageManager.SIGNATURE_MATCH)
10246                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10247                        == PackageManager.SIGNATURE_MATCH);
10248        if (!allowed && (bp.protectionLevel
10249                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10250            if (isSystemApp(pkg)) {
10251                // For updated system applications, a system permission
10252                // is granted only if it had been defined by the original application.
10253                if (pkg.isUpdatedSystemApp()) {
10254                    final PackageSetting sysPs = mSettings
10255                            .getDisabledSystemPkgLPr(pkg.packageName);
10256                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10257                        // If the original was granted this permission, we take
10258                        // that grant decision as read and propagate it to the
10259                        // update.
10260                        if (sysPs.isPrivileged()) {
10261                            allowed = true;
10262                        }
10263                    } else {
10264                        // The system apk may have been updated with an older
10265                        // version of the one on the data partition, but which
10266                        // granted a new system permission that it didn't have
10267                        // before.  In this case we do want to allow the app to
10268                        // now get the new permission if the ancestral apk is
10269                        // privileged to get it.
10270                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10271                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10272                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10273                                    allowed = true;
10274                                    break;
10275                                }
10276                            }
10277                        }
10278                        // Also if a privileged parent package on the system image or any of
10279                        // its children requested a privileged permission, the updated child
10280                        // packages can also get the permission.
10281                        if (pkg.parentPackage != null) {
10282                            final PackageSetting disabledSysParentPs = mSettings
10283                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10284                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10285                                    && disabledSysParentPs.isPrivileged()) {
10286                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10287                                    allowed = true;
10288                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10289                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10290                                    for (int i = 0; i < count; i++) {
10291                                        PackageParser.Package disabledSysChildPkg =
10292                                                disabledSysParentPs.pkg.childPackages.get(i);
10293                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10294                                                perm)) {
10295                                            allowed = true;
10296                                            break;
10297                                        }
10298                                    }
10299                                }
10300                            }
10301                        }
10302                    }
10303                } else {
10304                    allowed = isPrivilegedApp(pkg);
10305                }
10306            }
10307        }
10308        if (!allowed) {
10309            if (!allowed && (bp.protectionLevel
10310                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10311                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10312                // If this was a previously normal/dangerous permission that got moved
10313                // to a system permission as part of the runtime permission redesign, then
10314                // we still want to blindly grant it to old apps.
10315                allowed = true;
10316            }
10317            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10318                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10319                // If this permission is to be granted to the system installer and
10320                // this app is an installer, then it gets the permission.
10321                allowed = true;
10322            }
10323            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10324                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10325                // If this permission is to be granted to the system verifier and
10326                // this app is a verifier, then it gets the permission.
10327                allowed = true;
10328            }
10329            if (!allowed && (bp.protectionLevel
10330                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10331                    && isSystemApp(pkg)) {
10332                // Any pre-installed system app is allowed to get this permission.
10333                allowed = true;
10334            }
10335            if (!allowed && (bp.protectionLevel
10336                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10337                // For development permissions, a development permission
10338                // is granted only if it was already granted.
10339                allowed = origPermissions.hasInstallPermission(perm);
10340            }
10341            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10342                    && pkg.packageName.equals(mSetupWizardPackage)) {
10343                // If this permission is to be granted to the system setup wizard and
10344                // this app is a setup wizard, then it gets the permission.
10345                allowed = true;
10346            }
10347        }
10348        return allowed;
10349    }
10350
10351    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10352        final int permCount = pkg.requestedPermissions.size();
10353        for (int j = 0; j < permCount; j++) {
10354            String requestedPermission = pkg.requestedPermissions.get(j);
10355            if (permission.equals(requestedPermission)) {
10356                return true;
10357            }
10358        }
10359        return false;
10360    }
10361
10362    final class ActivityIntentResolver
10363            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10364        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10365                boolean defaultOnly, int userId) {
10366            if (!sUserManager.exists(userId)) return null;
10367            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10368            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10369        }
10370
10371        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10372                int userId) {
10373            if (!sUserManager.exists(userId)) return null;
10374            mFlags = flags;
10375            return super.queryIntent(intent, resolvedType,
10376                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10377        }
10378
10379        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10380                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10381            if (!sUserManager.exists(userId)) return null;
10382            if (packageActivities == null) {
10383                return null;
10384            }
10385            mFlags = flags;
10386            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10387            final int N = packageActivities.size();
10388            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10389                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10390
10391            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10392            for (int i = 0; i < N; ++i) {
10393                intentFilters = packageActivities.get(i).intents;
10394                if (intentFilters != null && intentFilters.size() > 0) {
10395                    PackageParser.ActivityIntentInfo[] array =
10396                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10397                    intentFilters.toArray(array);
10398                    listCut.add(array);
10399                }
10400            }
10401            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10402        }
10403
10404        /**
10405         * Finds a privileged activity that matches the specified activity names.
10406         */
10407        private PackageParser.Activity findMatchingActivity(
10408                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10409            for (PackageParser.Activity sysActivity : activityList) {
10410                if (sysActivity.info.name.equals(activityInfo.name)) {
10411                    return sysActivity;
10412                }
10413                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10414                    return sysActivity;
10415                }
10416                if (sysActivity.info.targetActivity != null) {
10417                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10418                        return sysActivity;
10419                    }
10420                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10421                        return sysActivity;
10422                    }
10423                }
10424            }
10425            return null;
10426        }
10427
10428        public class IterGenerator<E> {
10429            public Iterator<E> generate(ActivityIntentInfo info) {
10430                return null;
10431            }
10432        }
10433
10434        public class ActionIterGenerator extends IterGenerator<String> {
10435            @Override
10436            public Iterator<String> generate(ActivityIntentInfo info) {
10437                return info.actionsIterator();
10438            }
10439        }
10440
10441        public class CategoriesIterGenerator extends IterGenerator<String> {
10442            @Override
10443            public Iterator<String> generate(ActivityIntentInfo info) {
10444                return info.categoriesIterator();
10445            }
10446        }
10447
10448        public class SchemesIterGenerator extends IterGenerator<String> {
10449            @Override
10450            public Iterator<String> generate(ActivityIntentInfo info) {
10451                return info.schemesIterator();
10452            }
10453        }
10454
10455        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10456            @Override
10457            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10458                return info.authoritiesIterator();
10459            }
10460        }
10461
10462        /**
10463         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10464         * MODIFIED. Do not pass in a list that should not be changed.
10465         */
10466        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10467                IterGenerator<T> generator, Iterator<T> searchIterator) {
10468            // loop through the set of actions; every one must be found in the intent filter
10469            while (searchIterator.hasNext()) {
10470                // we must have at least one filter in the list to consider a match
10471                if (intentList.size() == 0) {
10472                    break;
10473                }
10474
10475                final T searchAction = searchIterator.next();
10476
10477                // loop through the set of intent filters
10478                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10479                while (intentIter.hasNext()) {
10480                    final ActivityIntentInfo intentInfo = intentIter.next();
10481                    boolean selectionFound = false;
10482
10483                    // loop through the intent filter's selection criteria; at least one
10484                    // of them must match the searched criteria
10485                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10486                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10487                        final T intentSelection = intentSelectionIter.next();
10488                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10489                            selectionFound = true;
10490                            break;
10491                        }
10492                    }
10493
10494                    // the selection criteria wasn't found in this filter's set; this filter
10495                    // is not a potential match
10496                    if (!selectionFound) {
10497                        intentIter.remove();
10498                    }
10499                }
10500            }
10501        }
10502
10503        private boolean isProtectedAction(ActivityIntentInfo filter) {
10504            final Iterator<String> actionsIter = filter.actionsIterator();
10505            while (actionsIter != null && actionsIter.hasNext()) {
10506                final String filterAction = actionsIter.next();
10507                if (PROTECTED_ACTIONS.contains(filterAction)) {
10508                    return true;
10509                }
10510            }
10511            return false;
10512        }
10513
10514        /**
10515         * Adjusts the priority of the given intent filter according to policy.
10516         * <p>
10517         * <ul>
10518         * <li>The priority for non privileged applications is capped to '0'</li>
10519         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10520         * <li>The priority for unbundled updates to privileged applications is capped to the
10521         *      priority defined on the system partition</li>
10522         * </ul>
10523         * <p>
10524         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10525         * allowed to obtain any priority on any action.
10526         */
10527        private void adjustPriority(
10528                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10529            // nothing to do; priority is fine as-is
10530            if (intent.getPriority() <= 0) {
10531                return;
10532            }
10533
10534            final ActivityInfo activityInfo = intent.activity.info;
10535            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10536
10537            final boolean privilegedApp =
10538                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10539            if (!privilegedApp) {
10540                // non-privileged applications can never define a priority >0
10541                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10542                        + " package: " + applicationInfo.packageName
10543                        + " activity: " + intent.activity.className
10544                        + " origPrio: " + intent.getPriority());
10545                intent.setPriority(0);
10546                return;
10547            }
10548
10549            if (systemActivities == null) {
10550                // the system package is not disabled; we're parsing the system partition
10551                if (isProtectedAction(intent)) {
10552                    if (mDeferProtectedFilters) {
10553                        // We can't deal with these just yet. No component should ever obtain a
10554                        // >0 priority for a protected actions, with ONE exception -- the setup
10555                        // wizard. The setup wizard, however, cannot be known until we're able to
10556                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10557                        // until all intent filters have been processed. Chicken, meet egg.
10558                        // Let the filter temporarily have a high priority and rectify the
10559                        // priorities after all system packages have been scanned.
10560                        mProtectedFilters.add(intent);
10561                        if (DEBUG_FILTERS) {
10562                            Slog.i(TAG, "Protected action; save for later;"
10563                                    + " package: " + applicationInfo.packageName
10564                                    + " activity: " + intent.activity.className
10565                                    + " origPrio: " + intent.getPriority());
10566                        }
10567                        return;
10568                    } else {
10569                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10570                            Slog.i(TAG, "No setup wizard;"
10571                                + " All protected intents capped to priority 0");
10572                        }
10573                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10574                            if (DEBUG_FILTERS) {
10575                                Slog.i(TAG, "Found setup wizard;"
10576                                    + " allow priority " + intent.getPriority() + ";"
10577                                    + " package: " + intent.activity.info.packageName
10578                                    + " activity: " + intent.activity.className
10579                                    + " priority: " + intent.getPriority());
10580                            }
10581                            // setup wizard gets whatever it wants
10582                            return;
10583                        }
10584                        Slog.w(TAG, "Protected action; cap priority to 0;"
10585                                + " package: " + intent.activity.info.packageName
10586                                + " activity: " + intent.activity.className
10587                                + " origPrio: " + intent.getPriority());
10588                        intent.setPriority(0);
10589                        return;
10590                    }
10591                }
10592                // privileged apps on the system image get whatever priority they request
10593                return;
10594            }
10595
10596            // privileged app unbundled update ... try to find the same activity
10597            final PackageParser.Activity foundActivity =
10598                    findMatchingActivity(systemActivities, activityInfo);
10599            if (foundActivity == null) {
10600                // this is a new activity; it cannot obtain >0 priority
10601                if (DEBUG_FILTERS) {
10602                    Slog.i(TAG, "New activity; cap priority to 0;"
10603                            + " package: " + applicationInfo.packageName
10604                            + " activity: " + intent.activity.className
10605                            + " origPrio: " + intent.getPriority());
10606                }
10607                intent.setPriority(0);
10608                return;
10609            }
10610
10611            // found activity, now check for filter equivalence
10612
10613            // a shallow copy is enough; we modify the list, not its contents
10614            final List<ActivityIntentInfo> intentListCopy =
10615                    new ArrayList<>(foundActivity.intents);
10616            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10617
10618            // find matching action subsets
10619            final Iterator<String> actionsIterator = intent.actionsIterator();
10620            if (actionsIterator != null) {
10621                getIntentListSubset(
10622                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10623                if (intentListCopy.size() == 0) {
10624                    // no more intents to match; we're not equivalent
10625                    if (DEBUG_FILTERS) {
10626                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10627                                + " package: " + applicationInfo.packageName
10628                                + " activity: " + intent.activity.className
10629                                + " origPrio: " + intent.getPriority());
10630                    }
10631                    intent.setPriority(0);
10632                    return;
10633                }
10634            }
10635
10636            // find matching category subsets
10637            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10638            if (categoriesIterator != null) {
10639                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10640                        categoriesIterator);
10641                if (intentListCopy.size() == 0) {
10642                    // no more intents to match; we're not equivalent
10643                    if (DEBUG_FILTERS) {
10644                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10645                                + " package: " + applicationInfo.packageName
10646                                + " activity: " + intent.activity.className
10647                                + " origPrio: " + intent.getPriority());
10648                    }
10649                    intent.setPriority(0);
10650                    return;
10651                }
10652            }
10653
10654            // find matching schemes subsets
10655            final Iterator<String> schemesIterator = intent.schemesIterator();
10656            if (schemesIterator != null) {
10657                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10658                        schemesIterator);
10659                if (intentListCopy.size() == 0) {
10660                    // no more intents to match; we're not equivalent
10661                    if (DEBUG_FILTERS) {
10662                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10663                                + " package: " + applicationInfo.packageName
10664                                + " activity: " + intent.activity.className
10665                                + " origPrio: " + intent.getPriority());
10666                    }
10667                    intent.setPriority(0);
10668                    return;
10669                }
10670            }
10671
10672            // find matching authorities subsets
10673            final Iterator<IntentFilter.AuthorityEntry>
10674                    authoritiesIterator = intent.authoritiesIterator();
10675            if (authoritiesIterator != null) {
10676                getIntentListSubset(intentListCopy,
10677                        new AuthoritiesIterGenerator(),
10678                        authoritiesIterator);
10679                if (intentListCopy.size() == 0) {
10680                    // no more intents to match; we're not equivalent
10681                    if (DEBUG_FILTERS) {
10682                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10683                                + " package: " + applicationInfo.packageName
10684                                + " activity: " + intent.activity.className
10685                                + " origPrio: " + intent.getPriority());
10686                    }
10687                    intent.setPriority(0);
10688                    return;
10689                }
10690            }
10691
10692            // we found matching filter(s); app gets the max priority of all intents
10693            int cappedPriority = 0;
10694            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10695                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10696            }
10697            if (intent.getPriority() > cappedPriority) {
10698                if (DEBUG_FILTERS) {
10699                    Slog.i(TAG, "Found matching filter(s);"
10700                            + " cap priority to " + cappedPriority + ";"
10701                            + " package: " + applicationInfo.packageName
10702                            + " activity: " + intent.activity.className
10703                            + " origPrio: " + intent.getPriority());
10704                }
10705                intent.setPriority(cappedPriority);
10706                return;
10707            }
10708            // all this for nothing; the requested priority was <= what was on the system
10709        }
10710
10711        public final void addActivity(PackageParser.Activity a, String type) {
10712            mActivities.put(a.getComponentName(), a);
10713            if (DEBUG_SHOW_INFO)
10714                Log.v(
10715                TAG, "  " + type + " " +
10716                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10717            if (DEBUG_SHOW_INFO)
10718                Log.v(TAG, "    Class=" + a.info.name);
10719            final int NI = a.intents.size();
10720            for (int j=0; j<NI; j++) {
10721                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10722                if ("activity".equals(type)) {
10723                    final PackageSetting ps =
10724                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10725                    final List<PackageParser.Activity> systemActivities =
10726                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10727                    adjustPriority(systemActivities, intent);
10728                }
10729                if (DEBUG_SHOW_INFO) {
10730                    Log.v(TAG, "    IntentFilter:");
10731                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10732                }
10733                if (!intent.debugCheck()) {
10734                    Log.w(TAG, "==> For Activity " + a.info.name);
10735                }
10736                addFilter(intent);
10737            }
10738        }
10739
10740        public final void removeActivity(PackageParser.Activity a, String type) {
10741            mActivities.remove(a.getComponentName());
10742            if (DEBUG_SHOW_INFO) {
10743                Log.v(TAG, "  " + type + " "
10744                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10745                                : a.info.name) + ":");
10746                Log.v(TAG, "    Class=" + a.info.name);
10747            }
10748            final int NI = a.intents.size();
10749            for (int j=0; j<NI; j++) {
10750                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10751                if (DEBUG_SHOW_INFO) {
10752                    Log.v(TAG, "    IntentFilter:");
10753                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10754                }
10755                removeFilter(intent);
10756            }
10757        }
10758
10759        @Override
10760        protected boolean allowFilterResult(
10761                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10762            ActivityInfo filterAi = filter.activity.info;
10763            for (int i=dest.size()-1; i>=0; i--) {
10764                ActivityInfo destAi = dest.get(i).activityInfo;
10765                if (destAi.name == filterAi.name
10766                        && destAi.packageName == filterAi.packageName) {
10767                    return false;
10768                }
10769            }
10770            return true;
10771        }
10772
10773        @Override
10774        protected ActivityIntentInfo[] newArray(int size) {
10775            return new ActivityIntentInfo[size];
10776        }
10777
10778        @Override
10779        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10780            if (!sUserManager.exists(userId)) return true;
10781            PackageParser.Package p = filter.activity.owner;
10782            if (p != null) {
10783                PackageSetting ps = (PackageSetting)p.mExtras;
10784                if (ps != null) {
10785                    // System apps are never considered stopped for purposes of
10786                    // filtering, because there may be no way for the user to
10787                    // actually re-launch them.
10788                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10789                            && ps.getStopped(userId);
10790                }
10791            }
10792            return false;
10793        }
10794
10795        @Override
10796        protected boolean isPackageForFilter(String packageName,
10797                PackageParser.ActivityIntentInfo info) {
10798            return packageName.equals(info.activity.owner.packageName);
10799        }
10800
10801        @Override
10802        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10803                int match, int userId) {
10804            if (!sUserManager.exists(userId)) return null;
10805            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10806                return null;
10807            }
10808            final PackageParser.Activity activity = info.activity;
10809            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10810            if (ps == null) {
10811                return null;
10812            }
10813            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10814                    ps.readUserState(userId), userId);
10815            if (ai == null) {
10816                return null;
10817            }
10818            final ResolveInfo res = new ResolveInfo();
10819            res.activityInfo = ai;
10820            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10821                res.filter = info;
10822            }
10823            if (info != null) {
10824                res.handleAllWebDataURI = info.handleAllWebDataURI();
10825            }
10826            res.priority = info.getPriority();
10827            res.preferredOrder = activity.owner.mPreferredOrder;
10828            //System.out.println("Result: " + res.activityInfo.className +
10829            //                   " = " + res.priority);
10830            res.match = match;
10831            res.isDefault = info.hasDefault;
10832            res.labelRes = info.labelRes;
10833            res.nonLocalizedLabel = info.nonLocalizedLabel;
10834            if (userNeedsBadging(userId)) {
10835                res.noResourceId = true;
10836            } else {
10837                res.icon = info.icon;
10838            }
10839            res.iconResourceId = info.icon;
10840            res.system = res.activityInfo.applicationInfo.isSystemApp();
10841            return res;
10842        }
10843
10844        @Override
10845        protected void sortResults(List<ResolveInfo> results) {
10846            Collections.sort(results, mResolvePrioritySorter);
10847        }
10848
10849        @Override
10850        protected void dumpFilter(PrintWriter out, String prefix,
10851                PackageParser.ActivityIntentInfo filter) {
10852            out.print(prefix); out.print(
10853                    Integer.toHexString(System.identityHashCode(filter.activity)));
10854                    out.print(' ');
10855                    filter.activity.printComponentShortName(out);
10856                    out.print(" filter ");
10857                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10858        }
10859
10860        @Override
10861        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10862            return filter.activity;
10863        }
10864
10865        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10866            PackageParser.Activity activity = (PackageParser.Activity)label;
10867            out.print(prefix); out.print(
10868                    Integer.toHexString(System.identityHashCode(activity)));
10869                    out.print(' ');
10870                    activity.printComponentShortName(out);
10871            if (count > 1) {
10872                out.print(" ("); out.print(count); out.print(" filters)");
10873            }
10874            out.println();
10875        }
10876
10877        // Keys are String (activity class name), values are Activity.
10878        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10879                = new ArrayMap<ComponentName, PackageParser.Activity>();
10880        private int mFlags;
10881    }
10882
10883    private final class ServiceIntentResolver
10884            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10885        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10886                boolean defaultOnly, int userId) {
10887            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10888            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10889        }
10890
10891        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10892                int userId) {
10893            if (!sUserManager.exists(userId)) return null;
10894            mFlags = flags;
10895            return super.queryIntent(intent, resolvedType,
10896                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10897        }
10898
10899        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10900                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10901            if (!sUserManager.exists(userId)) return null;
10902            if (packageServices == null) {
10903                return null;
10904            }
10905            mFlags = flags;
10906            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10907            final int N = packageServices.size();
10908            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10909                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10910
10911            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10912            for (int i = 0; i < N; ++i) {
10913                intentFilters = packageServices.get(i).intents;
10914                if (intentFilters != null && intentFilters.size() > 0) {
10915                    PackageParser.ServiceIntentInfo[] array =
10916                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10917                    intentFilters.toArray(array);
10918                    listCut.add(array);
10919                }
10920            }
10921            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10922        }
10923
10924        public final void addService(PackageParser.Service s) {
10925            mServices.put(s.getComponentName(), s);
10926            if (DEBUG_SHOW_INFO) {
10927                Log.v(TAG, "  "
10928                        + (s.info.nonLocalizedLabel != null
10929                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10930                Log.v(TAG, "    Class=" + s.info.name);
10931            }
10932            final int NI = s.intents.size();
10933            int j;
10934            for (j=0; j<NI; j++) {
10935                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10936                if (DEBUG_SHOW_INFO) {
10937                    Log.v(TAG, "    IntentFilter:");
10938                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10939                }
10940                if (!intent.debugCheck()) {
10941                    Log.w(TAG, "==> For Service " + s.info.name);
10942                }
10943                addFilter(intent);
10944            }
10945        }
10946
10947        public final void removeService(PackageParser.Service s) {
10948            mServices.remove(s.getComponentName());
10949            if (DEBUG_SHOW_INFO) {
10950                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10951                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10952                Log.v(TAG, "    Class=" + s.info.name);
10953            }
10954            final int NI = s.intents.size();
10955            int j;
10956            for (j=0; j<NI; j++) {
10957                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10958                if (DEBUG_SHOW_INFO) {
10959                    Log.v(TAG, "    IntentFilter:");
10960                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10961                }
10962                removeFilter(intent);
10963            }
10964        }
10965
10966        @Override
10967        protected boolean allowFilterResult(
10968                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10969            ServiceInfo filterSi = filter.service.info;
10970            for (int i=dest.size()-1; i>=0; i--) {
10971                ServiceInfo destAi = dest.get(i).serviceInfo;
10972                if (destAi.name == filterSi.name
10973                        && destAi.packageName == filterSi.packageName) {
10974                    return false;
10975                }
10976            }
10977            return true;
10978        }
10979
10980        @Override
10981        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10982            return new PackageParser.ServiceIntentInfo[size];
10983        }
10984
10985        @Override
10986        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10987            if (!sUserManager.exists(userId)) return true;
10988            PackageParser.Package p = filter.service.owner;
10989            if (p != null) {
10990                PackageSetting ps = (PackageSetting)p.mExtras;
10991                if (ps != null) {
10992                    // System apps are never considered stopped for purposes of
10993                    // filtering, because there may be no way for the user to
10994                    // actually re-launch them.
10995                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10996                            && ps.getStopped(userId);
10997                }
10998            }
10999            return false;
11000        }
11001
11002        @Override
11003        protected boolean isPackageForFilter(String packageName,
11004                PackageParser.ServiceIntentInfo info) {
11005            return packageName.equals(info.service.owner.packageName);
11006        }
11007
11008        @Override
11009        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11010                int match, int userId) {
11011            if (!sUserManager.exists(userId)) return null;
11012            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11013            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11014                return null;
11015            }
11016            final PackageParser.Service service = info.service;
11017            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11018            if (ps == null) {
11019                return null;
11020            }
11021            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11022                    ps.readUserState(userId), userId);
11023            if (si == null) {
11024                return null;
11025            }
11026            final ResolveInfo res = new ResolveInfo();
11027            res.serviceInfo = si;
11028            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11029                res.filter = filter;
11030            }
11031            res.priority = info.getPriority();
11032            res.preferredOrder = service.owner.mPreferredOrder;
11033            res.match = match;
11034            res.isDefault = info.hasDefault;
11035            res.labelRes = info.labelRes;
11036            res.nonLocalizedLabel = info.nonLocalizedLabel;
11037            res.icon = info.icon;
11038            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11039            return res;
11040        }
11041
11042        @Override
11043        protected void sortResults(List<ResolveInfo> results) {
11044            Collections.sort(results, mResolvePrioritySorter);
11045        }
11046
11047        @Override
11048        protected void dumpFilter(PrintWriter out, String prefix,
11049                PackageParser.ServiceIntentInfo filter) {
11050            out.print(prefix); out.print(
11051                    Integer.toHexString(System.identityHashCode(filter.service)));
11052                    out.print(' ');
11053                    filter.service.printComponentShortName(out);
11054                    out.print(" filter ");
11055                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11056        }
11057
11058        @Override
11059        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11060            return filter.service;
11061        }
11062
11063        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11064            PackageParser.Service service = (PackageParser.Service)label;
11065            out.print(prefix); out.print(
11066                    Integer.toHexString(System.identityHashCode(service)));
11067                    out.print(' ');
11068                    service.printComponentShortName(out);
11069            if (count > 1) {
11070                out.print(" ("); out.print(count); out.print(" filters)");
11071            }
11072            out.println();
11073        }
11074
11075//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11076//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11077//            final List<ResolveInfo> retList = Lists.newArrayList();
11078//            while (i.hasNext()) {
11079//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11080//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11081//                    retList.add(resolveInfo);
11082//                }
11083//            }
11084//            return retList;
11085//        }
11086
11087        // Keys are String (activity class name), values are Activity.
11088        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11089                = new ArrayMap<ComponentName, PackageParser.Service>();
11090        private int mFlags;
11091    };
11092
11093    private final class ProviderIntentResolver
11094            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11096                boolean defaultOnly, int userId) {
11097            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11098            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11099        }
11100
11101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11102                int userId) {
11103            if (!sUserManager.exists(userId))
11104                return null;
11105            mFlags = flags;
11106            return super.queryIntent(intent, resolvedType,
11107                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11108        }
11109
11110        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11111                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11112            if (!sUserManager.exists(userId))
11113                return null;
11114            if (packageProviders == null) {
11115                return null;
11116            }
11117            mFlags = flags;
11118            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11119            final int N = packageProviders.size();
11120            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11121                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11122
11123            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11124            for (int i = 0; i < N; ++i) {
11125                intentFilters = packageProviders.get(i).intents;
11126                if (intentFilters != null && intentFilters.size() > 0) {
11127                    PackageParser.ProviderIntentInfo[] array =
11128                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11129                    intentFilters.toArray(array);
11130                    listCut.add(array);
11131                }
11132            }
11133            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11134        }
11135
11136        public final void addProvider(PackageParser.Provider p) {
11137            if (mProviders.containsKey(p.getComponentName())) {
11138                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11139                return;
11140            }
11141
11142            mProviders.put(p.getComponentName(), p);
11143            if (DEBUG_SHOW_INFO) {
11144                Log.v(TAG, "  "
11145                        + (p.info.nonLocalizedLabel != null
11146                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11147                Log.v(TAG, "    Class=" + p.info.name);
11148            }
11149            final int NI = p.intents.size();
11150            int j;
11151            for (j = 0; j < NI; j++) {
11152                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11153                if (DEBUG_SHOW_INFO) {
11154                    Log.v(TAG, "    IntentFilter:");
11155                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11156                }
11157                if (!intent.debugCheck()) {
11158                    Log.w(TAG, "==> For Provider " + p.info.name);
11159                }
11160                addFilter(intent);
11161            }
11162        }
11163
11164        public final void removeProvider(PackageParser.Provider p) {
11165            mProviders.remove(p.getComponentName());
11166            if (DEBUG_SHOW_INFO) {
11167                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11168                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11169                Log.v(TAG, "    Class=" + p.info.name);
11170            }
11171            final int NI = p.intents.size();
11172            int j;
11173            for (j = 0; j < NI; j++) {
11174                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11175                if (DEBUG_SHOW_INFO) {
11176                    Log.v(TAG, "    IntentFilter:");
11177                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11178                }
11179                removeFilter(intent);
11180            }
11181        }
11182
11183        @Override
11184        protected boolean allowFilterResult(
11185                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11186            ProviderInfo filterPi = filter.provider.info;
11187            for (int i = dest.size() - 1; i >= 0; i--) {
11188                ProviderInfo destPi = dest.get(i).providerInfo;
11189                if (destPi.name == filterPi.name
11190                        && destPi.packageName == filterPi.packageName) {
11191                    return false;
11192                }
11193            }
11194            return true;
11195        }
11196
11197        @Override
11198        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11199            return new PackageParser.ProviderIntentInfo[size];
11200        }
11201
11202        @Override
11203        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11204            if (!sUserManager.exists(userId))
11205                return true;
11206            PackageParser.Package p = filter.provider.owner;
11207            if (p != null) {
11208                PackageSetting ps = (PackageSetting) p.mExtras;
11209                if (ps != null) {
11210                    // System apps are never considered stopped for purposes of
11211                    // filtering, because there may be no way for the user to
11212                    // actually re-launch them.
11213                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11214                            && ps.getStopped(userId);
11215                }
11216            }
11217            return false;
11218        }
11219
11220        @Override
11221        protected boolean isPackageForFilter(String packageName,
11222                PackageParser.ProviderIntentInfo info) {
11223            return packageName.equals(info.provider.owner.packageName);
11224        }
11225
11226        @Override
11227        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11228                int match, int userId) {
11229            if (!sUserManager.exists(userId))
11230                return null;
11231            final PackageParser.ProviderIntentInfo info = filter;
11232            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11233                return null;
11234            }
11235            final PackageParser.Provider provider = info.provider;
11236            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11237            if (ps == null) {
11238                return null;
11239            }
11240            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11241                    ps.readUserState(userId), userId);
11242            if (pi == null) {
11243                return null;
11244            }
11245            final ResolveInfo res = new ResolveInfo();
11246            res.providerInfo = pi;
11247            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11248                res.filter = filter;
11249            }
11250            res.priority = info.getPriority();
11251            res.preferredOrder = provider.owner.mPreferredOrder;
11252            res.match = match;
11253            res.isDefault = info.hasDefault;
11254            res.labelRes = info.labelRes;
11255            res.nonLocalizedLabel = info.nonLocalizedLabel;
11256            res.icon = info.icon;
11257            res.system = res.providerInfo.applicationInfo.isSystemApp();
11258            return res;
11259        }
11260
11261        @Override
11262        protected void sortResults(List<ResolveInfo> results) {
11263            Collections.sort(results, mResolvePrioritySorter);
11264        }
11265
11266        @Override
11267        protected void dumpFilter(PrintWriter out, String prefix,
11268                PackageParser.ProviderIntentInfo filter) {
11269            out.print(prefix);
11270            out.print(
11271                    Integer.toHexString(System.identityHashCode(filter.provider)));
11272            out.print(' ');
11273            filter.provider.printComponentShortName(out);
11274            out.print(" filter ");
11275            out.println(Integer.toHexString(System.identityHashCode(filter)));
11276        }
11277
11278        @Override
11279        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11280            return filter.provider;
11281        }
11282
11283        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11284            PackageParser.Provider provider = (PackageParser.Provider)label;
11285            out.print(prefix); out.print(
11286                    Integer.toHexString(System.identityHashCode(provider)));
11287                    out.print(' ');
11288                    provider.printComponentShortName(out);
11289            if (count > 1) {
11290                out.print(" ("); out.print(count); out.print(" filters)");
11291            }
11292            out.println();
11293        }
11294
11295        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11296                = new ArrayMap<ComponentName, PackageParser.Provider>();
11297        private int mFlags;
11298    }
11299
11300    private static final class EphemeralIntentResolver
11301            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11302        @Override
11303        protected EphemeralResolveIntentInfo[] newArray(int size) {
11304            return new EphemeralResolveIntentInfo[size];
11305        }
11306
11307        @Override
11308        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11309            return true;
11310        }
11311
11312        @Override
11313        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11314                int userId) {
11315            if (!sUserManager.exists(userId)) {
11316                return null;
11317            }
11318            return info.getEphemeralResolveInfo();
11319        }
11320    }
11321
11322    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11323            new Comparator<ResolveInfo>() {
11324        public int compare(ResolveInfo r1, ResolveInfo r2) {
11325            int v1 = r1.priority;
11326            int v2 = r2.priority;
11327            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11328            if (v1 != v2) {
11329                return (v1 > v2) ? -1 : 1;
11330            }
11331            v1 = r1.preferredOrder;
11332            v2 = r2.preferredOrder;
11333            if (v1 != v2) {
11334                return (v1 > v2) ? -1 : 1;
11335            }
11336            if (r1.isDefault != r2.isDefault) {
11337                return r1.isDefault ? -1 : 1;
11338            }
11339            v1 = r1.match;
11340            v2 = r2.match;
11341            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11342            if (v1 != v2) {
11343                return (v1 > v2) ? -1 : 1;
11344            }
11345            if (r1.system != r2.system) {
11346                return r1.system ? -1 : 1;
11347            }
11348            if (r1.activityInfo != null) {
11349                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11350            }
11351            if (r1.serviceInfo != null) {
11352                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11353            }
11354            if (r1.providerInfo != null) {
11355                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11356            }
11357            return 0;
11358        }
11359    };
11360
11361    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11362            new Comparator<ProviderInfo>() {
11363        public int compare(ProviderInfo p1, ProviderInfo p2) {
11364            final int v1 = p1.initOrder;
11365            final int v2 = p2.initOrder;
11366            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11367        }
11368    };
11369
11370    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11371            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11372            final int[] userIds) {
11373        mHandler.post(new Runnable() {
11374            @Override
11375            public void run() {
11376                try {
11377                    final IActivityManager am = ActivityManagerNative.getDefault();
11378                    if (am == null) return;
11379                    final int[] resolvedUserIds;
11380                    if (userIds == null) {
11381                        resolvedUserIds = am.getRunningUserIds();
11382                    } else {
11383                        resolvedUserIds = userIds;
11384                    }
11385                    for (int id : resolvedUserIds) {
11386                        final Intent intent = new Intent(action,
11387                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11388                        if (extras != null) {
11389                            intent.putExtras(extras);
11390                        }
11391                        if (targetPkg != null) {
11392                            intent.setPackage(targetPkg);
11393                        }
11394                        // Modify the UID when posting to other users
11395                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11396                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11397                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11398                            intent.putExtra(Intent.EXTRA_UID, uid);
11399                        }
11400                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11401                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11402                        if (DEBUG_BROADCASTS) {
11403                            RuntimeException here = new RuntimeException("here");
11404                            here.fillInStackTrace();
11405                            Slog.d(TAG, "Sending to user " + id + ": "
11406                                    + intent.toShortString(false, true, false, false)
11407                                    + " " + intent.getExtras(), here);
11408                        }
11409                        am.broadcastIntent(null, intent, null, finishedReceiver,
11410                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11411                                null, finishedReceiver != null, false, id);
11412                    }
11413                } catch (RemoteException ex) {
11414                }
11415            }
11416        });
11417    }
11418
11419    /**
11420     * Check if the external storage media is available. This is true if there
11421     * is a mounted external storage medium or if the external storage is
11422     * emulated.
11423     */
11424    private boolean isExternalMediaAvailable() {
11425        return mMediaMounted || Environment.isExternalStorageEmulated();
11426    }
11427
11428    @Override
11429    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11430        // writer
11431        synchronized (mPackages) {
11432            if (!isExternalMediaAvailable()) {
11433                // If the external storage is no longer mounted at this point,
11434                // the caller may not have been able to delete all of this
11435                // packages files and can not delete any more.  Bail.
11436                return null;
11437            }
11438            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11439            if (lastPackage != null) {
11440                pkgs.remove(lastPackage);
11441            }
11442            if (pkgs.size() > 0) {
11443                return pkgs.get(0);
11444            }
11445        }
11446        return null;
11447    }
11448
11449    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11450        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11451                userId, andCode ? 1 : 0, packageName);
11452        if (mSystemReady) {
11453            msg.sendToTarget();
11454        } else {
11455            if (mPostSystemReadyMessages == null) {
11456                mPostSystemReadyMessages = new ArrayList<>();
11457            }
11458            mPostSystemReadyMessages.add(msg);
11459        }
11460    }
11461
11462    void startCleaningPackages() {
11463        // reader
11464        if (!isExternalMediaAvailable()) {
11465            return;
11466        }
11467        synchronized (mPackages) {
11468            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11469                return;
11470            }
11471        }
11472        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11473        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11474        IActivityManager am = ActivityManagerNative.getDefault();
11475        if (am != null) {
11476            try {
11477                am.startService(null, intent, null, mContext.getOpPackageName(),
11478                        UserHandle.USER_SYSTEM);
11479            } catch (RemoteException e) {
11480            }
11481        }
11482    }
11483
11484    @Override
11485    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11486            int installFlags, String installerPackageName, int userId) {
11487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11488
11489        final int callingUid = Binder.getCallingUid();
11490        enforceCrossUserPermission(callingUid, userId,
11491                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11492
11493        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11494            try {
11495                if (observer != null) {
11496                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11497                }
11498            } catch (RemoteException re) {
11499            }
11500            return;
11501        }
11502
11503        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11504            installFlags |= PackageManager.INSTALL_FROM_ADB;
11505
11506        } else {
11507            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11508            // about installerPackageName.
11509
11510            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11511            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11512        }
11513
11514        UserHandle user;
11515        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11516            user = UserHandle.ALL;
11517        } else {
11518            user = new UserHandle(userId);
11519        }
11520
11521        // Only system components can circumvent runtime permissions when installing.
11522        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11523                && mContext.checkCallingOrSelfPermission(Manifest.permission
11524                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11525            throw new SecurityException("You need the "
11526                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11527                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11528        }
11529
11530        final File originFile = new File(originPath);
11531        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11532
11533        final Message msg = mHandler.obtainMessage(INIT_COPY);
11534        final VerificationInfo verificationInfo = new VerificationInfo(
11535                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11536        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11537                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11538                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11539                null /*certificates*/);
11540        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11541        msg.obj = params;
11542
11543        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11544                System.identityHashCode(msg.obj));
11545        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11546                System.identityHashCode(msg.obj));
11547
11548        mHandler.sendMessage(msg);
11549    }
11550
11551    void installStage(String packageName, File stagedDir, String stagedCid,
11552            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11553            String installerPackageName, int installerUid, UserHandle user,
11554            Certificate[][] certificates) {
11555        if (DEBUG_EPHEMERAL) {
11556            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11557                Slog.d(TAG, "Ephemeral install of " + packageName);
11558            }
11559        }
11560        final VerificationInfo verificationInfo = new VerificationInfo(
11561                sessionParams.originatingUri, sessionParams.referrerUri,
11562                sessionParams.originatingUid, installerUid);
11563
11564        final OriginInfo origin;
11565        if (stagedDir != null) {
11566            origin = OriginInfo.fromStagedFile(stagedDir);
11567        } else {
11568            origin = OriginInfo.fromStagedContainer(stagedCid);
11569        }
11570
11571        final Message msg = mHandler.obtainMessage(INIT_COPY);
11572        final InstallParams params = new InstallParams(origin, null, observer,
11573                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11574                verificationInfo, user, sessionParams.abiOverride,
11575                sessionParams.grantedRuntimePermissions, certificates);
11576        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11577        msg.obj = params;
11578
11579        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11580                System.identityHashCode(msg.obj));
11581        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11582                System.identityHashCode(msg.obj));
11583
11584        mHandler.sendMessage(msg);
11585    }
11586
11587    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11588            int userId) {
11589        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11590        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11591    }
11592
11593    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11594            int appId, int userId) {
11595        Bundle extras = new Bundle(1);
11596        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11597
11598        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11599                packageName, extras, 0, null, null, new int[] {userId});
11600        try {
11601            IActivityManager am = ActivityManagerNative.getDefault();
11602            if (isSystem && am.isUserRunning(userId, 0)) {
11603                // The just-installed/enabled app is bundled on the system, so presumed
11604                // to be able to run automatically without needing an explicit launch.
11605                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11606                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11607                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11608                        .setPackage(packageName);
11609                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11610                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11611            }
11612        } catch (RemoteException e) {
11613            // shouldn't happen
11614            Slog.w(TAG, "Unable to bootstrap installed package", e);
11615        }
11616    }
11617
11618    @Override
11619    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11620            int userId) {
11621        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11622        PackageSetting pkgSetting;
11623        final int uid = Binder.getCallingUid();
11624        enforceCrossUserPermission(uid, userId,
11625                true /* requireFullPermission */, true /* checkShell */,
11626                "setApplicationHiddenSetting for user " + userId);
11627
11628        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11629            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11630            return false;
11631        }
11632
11633        long callingId = Binder.clearCallingIdentity();
11634        try {
11635            boolean sendAdded = false;
11636            boolean sendRemoved = false;
11637            // writer
11638            synchronized (mPackages) {
11639                pkgSetting = mSettings.mPackages.get(packageName);
11640                if (pkgSetting == null) {
11641                    return false;
11642                }
11643                if (pkgSetting.getHidden(userId) != hidden) {
11644                    pkgSetting.setHidden(hidden, userId);
11645                    mSettings.writePackageRestrictionsLPr(userId);
11646                    if (hidden) {
11647                        sendRemoved = true;
11648                    } else {
11649                        sendAdded = true;
11650                    }
11651                }
11652            }
11653            if (sendAdded) {
11654                sendPackageAddedForUser(packageName, pkgSetting, userId);
11655                return true;
11656            }
11657            if (sendRemoved) {
11658                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11659                        "hiding pkg");
11660                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11661                return true;
11662            }
11663        } finally {
11664            Binder.restoreCallingIdentity(callingId);
11665        }
11666        return false;
11667    }
11668
11669    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11670            int userId) {
11671        final PackageRemovedInfo info = new PackageRemovedInfo();
11672        info.removedPackage = packageName;
11673        info.removedUsers = new int[] {userId};
11674        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11675        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11676    }
11677
11678    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11679        if (pkgList.length > 0) {
11680            Bundle extras = new Bundle(1);
11681            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11682
11683            sendPackageBroadcast(
11684                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11685                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11686                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11687                    new int[] {userId});
11688        }
11689    }
11690
11691    /**
11692     * Returns true if application is not found or there was an error. Otherwise it returns
11693     * the hidden state of the package for the given user.
11694     */
11695    @Override
11696    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11699                true /* requireFullPermission */, false /* checkShell */,
11700                "getApplicationHidden for user " + userId);
11701        PackageSetting pkgSetting;
11702        long callingId = Binder.clearCallingIdentity();
11703        try {
11704            // writer
11705            synchronized (mPackages) {
11706                pkgSetting = mSettings.mPackages.get(packageName);
11707                if (pkgSetting == null) {
11708                    return true;
11709                }
11710                return pkgSetting.getHidden(userId);
11711            }
11712        } finally {
11713            Binder.restoreCallingIdentity(callingId);
11714        }
11715    }
11716
11717    /**
11718     * @hide
11719     */
11720    @Override
11721    public int installExistingPackageAsUser(String packageName, int userId) {
11722        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11723                null);
11724        PackageSetting pkgSetting;
11725        final int uid = Binder.getCallingUid();
11726        enforceCrossUserPermission(uid, userId,
11727                true /* requireFullPermission */, true /* checkShell */,
11728                "installExistingPackage for user " + userId);
11729        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11730            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11731        }
11732
11733        long callingId = Binder.clearCallingIdentity();
11734        try {
11735            boolean installed = false;
11736
11737            // writer
11738            synchronized (mPackages) {
11739                pkgSetting = mSettings.mPackages.get(packageName);
11740                if (pkgSetting == null) {
11741                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11742                }
11743                if (!pkgSetting.getInstalled(userId)) {
11744                    pkgSetting.setInstalled(true, userId);
11745                    pkgSetting.setHidden(false, userId);
11746                    mSettings.writePackageRestrictionsLPr(userId);
11747                    installed = true;
11748                }
11749            }
11750
11751            if (installed) {
11752                if (pkgSetting.pkg != null) {
11753                    synchronized (mInstallLock) {
11754                        // We don't need to freeze for a brand new install
11755                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11756                    }
11757                }
11758                sendPackageAddedForUser(packageName, pkgSetting, userId);
11759            }
11760        } finally {
11761            Binder.restoreCallingIdentity(callingId);
11762        }
11763
11764        return PackageManager.INSTALL_SUCCEEDED;
11765    }
11766
11767    boolean isUserRestricted(int userId, String restrictionKey) {
11768        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11769        if (restrictions.getBoolean(restrictionKey, false)) {
11770            Log.w(TAG, "User is restricted: " + restrictionKey);
11771            return true;
11772        }
11773        return false;
11774    }
11775
11776    @Override
11777    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11778            int userId) {
11779        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11780        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11781                true /* requireFullPermission */, true /* checkShell */,
11782                "setPackagesSuspended for user " + userId);
11783
11784        if (ArrayUtils.isEmpty(packageNames)) {
11785            return packageNames;
11786        }
11787
11788        // List of package names for whom the suspended state has changed.
11789        List<String> changedPackages = new ArrayList<>(packageNames.length);
11790        // List of package names for whom the suspended state is not set as requested in this
11791        // method.
11792        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11793        long callingId = Binder.clearCallingIdentity();
11794        try {
11795            for (int i = 0; i < packageNames.length; i++) {
11796                String packageName = packageNames[i];
11797                boolean changed = false;
11798                final int appId;
11799                synchronized (mPackages) {
11800                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11801                    if (pkgSetting == null) {
11802                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11803                                + "\". Skipping suspending/un-suspending.");
11804                        unactionedPackages.add(packageName);
11805                        continue;
11806                    }
11807                    appId = pkgSetting.appId;
11808                    if (pkgSetting.getSuspended(userId) != suspended) {
11809                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11810                            unactionedPackages.add(packageName);
11811                            continue;
11812                        }
11813                        pkgSetting.setSuspended(suspended, userId);
11814                        mSettings.writePackageRestrictionsLPr(userId);
11815                        changed = true;
11816                        changedPackages.add(packageName);
11817                    }
11818                }
11819
11820                if (changed && suspended) {
11821                    killApplication(packageName, UserHandle.getUid(userId, appId),
11822                            "suspending package");
11823                }
11824            }
11825        } finally {
11826            Binder.restoreCallingIdentity(callingId);
11827        }
11828
11829        if (!changedPackages.isEmpty()) {
11830            sendPackagesSuspendedForUser(changedPackages.toArray(
11831                    new String[changedPackages.size()]), userId, suspended);
11832        }
11833
11834        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11835    }
11836
11837    @Override
11838    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11839        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11840                true /* requireFullPermission */, false /* checkShell */,
11841                "isPackageSuspendedForUser for user " + userId);
11842        synchronized (mPackages) {
11843            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11844            if (pkgSetting == null) {
11845                throw new IllegalArgumentException("Unknown target package: " + packageName);
11846            }
11847            return pkgSetting.getSuspended(userId);
11848        }
11849    }
11850
11851    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11852        if (isPackageDeviceAdmin(packageName, userId)) {
11853            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11854                    + "\": has an active device admin");
11855            return false;
11856        }
11857
11858        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11859        if (packageName.equals(activeLauncherPackageName)) {
11860            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11861                    + "\": contains the active launcher");
11862            return false;
11863        }
11864
11865        if (packageName.equals(mRequiredInstallerPackage)) {
11866            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11867                    + "\": required for package installation");
11868            return false;
11869        }
11870
11871        if (packageName.equals(mRequiredVerifierPackage)) {
11872            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11873                    + "\": required for package verification");
11874            return false;
11875        }
11876
11877        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11878            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11879                    + "\": is the default dialer");
11880            return false;
11881        }
11882
11883        return true;
11884    }
11885
11886    private String getActiveLauncherPackageName(int userId) {
11887        Intent intent = new Intent(Intent.ACTION_MAIN);
11888        intent.addCategory(Intent.CATEGORY_HOME);
11889        ResolveInfo resolveInfo = resolveIntent(
11890                intent,
11891                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11892                PackageManager.MATCH_DEFAULT_ONLY,
11893                userId);
11894
11895        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11896    }
11897
11898    private String getDefaultDialerPackageName(int userId) {
11899        synchronized (mPackages) {
11900            return mSettings.getDefaultDialerPackageNameLPw(userId);
11901        }
11902    }
11903
11904    @Override
11905    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11906        mContext.enforceCallingOrSelfPermission(
11907                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11908                "Only package verification agents can verify applications");
11909
11910        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11911        final PackageVerificationResponse response = new PackageVerificationResponse(
11912                verificationCode, Binder.getCallingUid());
11913        msg.arg1 = id;
11914        msg.obj = response;
11915        mHandler.sendMessage(msg);
11916    }
11917
11918    @Override
11919    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11920            long millisecondsToDelay) {
11921        mContext.enforceCallingOrSelfPermission(
11922                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11923                "Only package verification agents can extend verification timeouts");
11924
11925        final PackageVerificationState state = mPendingVerification.get(id);
11926        final PackageVerificationResponse response = new PackageVerificationResponse(
11927                verificationCodeAtTimeout, Binder.getCallingUid());
11928
11929        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11930            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11931        }
11932        if (millisecondsToDelay < 0) {
11933            millisecondsToDelay = 0;
11934        }
11935        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11936                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11937            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11938        }
11939
11940        if ((state != null) && !state.timeoutExtended()) {
11941            state.extendTimeout();
11942
11943            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11944            msg.arg1 = id;
11945            msg.obj = response;
11946            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11947        }
11948    }
11949
11950    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11951            int verificationCode, UserHandle user) {
11952        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11953        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11954        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11955        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11956        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11957
11958        mContext.sendBroadcastAsUser(intent, user,
11959                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11960    }
11961
11962    private ComponentName matchComponentForVerifier(String packageName,
11963            List<ResolveInfo> receivers) {
11964        ActivityInfo targetReceiver = null;
11965
11966        final int NR = receivers.size();
11967        for (int i = 0; i < NR; i++) {
11968            final ResolveInfo info = receivers.get(i);
11969            if (info.activityInfo == null) {
11970                continue;
11971            }
11972
11973            if (packageName.equals(info.activityInfo.packageName)) {
11974                targetReceiver = info.activityInfo;
11975                break;
11976            }
11977        }
11978
11979        if (targetReceiver == null) {
11980            return null;
11981        }
11982
11983        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11984    }
11985
11986    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11987            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11988        if (pkgInfo.verifiers.length == 0) {
11989            return null;
11990        }
11991
11992        final int N = pkgInfo.verifiers.length;
11993        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11994        for (int i = 0; i < N; i++) {
11995            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11996
11997            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11998                    receivers);
11999            if (comp == null) {
12000                continue;
12001            }
12002
12003            final int verifierUid = getUidForVerifier(verifierInfo);
12004            if (verifierUid == -1) {
12005                continue;
12006            }
12007
12008            if (DEBUG_VERIFY) {
12009                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12010                        + " with the correct signature");
12011            }
12012            sufficientVerifiers.add(comp);
12013            verificationState.addSufficientVerifier(verifierUid);
12014        }
12015
12016        return sufficientVerifiers;
12017    }
12018
12019    private int getUidForVerifier(VerifierInfo verifierInfo) {
12020        synchronized (mPackages) {
12021            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12022            if (pkg == null) {
12023                return -1;
12024            } else if (pkg.mSignatures.length != 1) {
12025                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12026                        + " has more than one signature; ignoring");
12027                return -1;
12028            }
12029
12030            /*
12031             * If the public key of the package's signature does not match
12032             * our expected public key, then this is a different package and
12033             * we should skip.
12034             */
12035
12036            final byte[] expectedPublicKey;
12037            try {
12038                final Signature verifierSig = pkg.mSignatures[0];
12039                final PublicKey publicKey = verifierSig.getPublicKey();
12040                expectedPublicKey = publicKey.getEncoded();
12041            } catch (CertificateException e) {
12042                return -1;
12043            }
12044
12045            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12046
12047            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12048                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12049                        + " does not have the expected public key; ignoring");
12050                return -1;
12051            }
12052
12053            return pkg.applicationInfo.uid;
12054        }
12055    }
12056
12057    @Override
12058    public void finishPackageInstall(int token, boolean didLaunch) {
12059        enforceSystemOrRoot("Only the system is allowed to finish installs");
12060
12061        if (DEBUG_INSTALL) {
12062            Slog.v(TAG, "BM finishing package install for " + token);
12063        }
12064        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12065
12066        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12067        mHandler.sendMessage(msg);
12068    }
12069
12070    /**
12071     * Get the verification agent timeout.
12072     *
12073     * @return verification timeout in milliseconds
12074     */
12075    private long getVerificationTimeout() {
12076        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12077                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12078                DEFAULT_VERIFICATION_TIMEOUT);
12079    }
12080
12081    /**
12082     * Get the default verification agent response code.
12083     *
12084     * @return default verification response code
12085     */
12086    private int getDefaultVerificationResponse() {
12087        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12088                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12089                DEFAULT_VERIFICATION_RESPONSE);
12090    }
12091
12092    /**
12093     * Check whether or not package verification has been enabled.
12094     *
12095     * @return true if verification should be performed
12096     */
12097    private boolean isVerificationEnabled(int userId, int installFlags) {
12098        if (!DEFAULT_VERIFY_ENABLE) {
12099            return false;
12100        }
12101        // Ephemeral apps don't get the full verification treatment
12102        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12103            if (DEBUG_EPHEMERAL) {
12104                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12105            }
12106            return false;
12107        }
12108
12109        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12110
12111        // Check if installing from ADB
12112        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12113            // Do not run verification in a test harness environment
12114            if (ActivityManager.isRunningInTestHarness()) {
12115                return false;
12116            }
12117            if (ensureVerifyAppsEnabled) {
12118                return true;
12119            }
12120            // Check if the developer does not want package verification for ADB installs
12121            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12122                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12123                return false;
12124            }
12125        }
12126
12127        if (ensureVerifyAppsEnabled) {
12128            return true;
12129        }
12130
12131        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12132                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12133    }
12134
12135    @Override
12136    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12137            throws RemoteException {
12138        mContext.enforceCallingOrSelfPermission(
12139                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12140                "Only intentfilter verification agents can verify applications");
12141
12142        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12143        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12144                Binder.getCallingUid(), verificationCode, failedDomains);
12145        msg.arg1 = id;
12146        msg.obj = response;
12147        mHandler.sendMessage(msg);
12148    }
12149
12150    @Override
12151    public int getIntentVerificationStatus(String packageName, int userId) {
12152        synchronized (mPackages) {
12153            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12154        }
12155    }
12156
12157    @Override
12158    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12159        mContext.enforceCallingOrSelfPermission(
12160                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12161
12162        boolean result = false;
12163        synchronized (mPackages) {
12164            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12165        }
12166        if (result) {
12167            scheduleWritePackageRestrictionsLocked(userId);
12168        }
12169        return result;
12170    }
12171
12172    @Override
12173    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12174            String packageName) {
12175        synchronized (mPackages) {
12176            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12177        }
12178    }
12179
12180    @Override
12181    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12182        if (TextUtils.isEmpty(packageName)) {
12183            return ParceledListSlice.emptyList();
12184        }
12185        synchronized (mPackages) {
12186            PackageParser.Package pkg = mPackages.get(packageName);
12187            if (pkg == null || pkg.activities == null) {
12188                return ParceledListSlice.emptyList();
12189            }
12190            final int count = pkg.activities.size();
12191            ArrayList<IntentFilter> result = new ArrayList<>();
12192            for (int n=0; n<count; n++) {
12193                PackageParser.Activity activity = pkg.activities.get(n);
12194                if (activity.intents != null && activity.intents.size() > 0) {
12195                    result.addAll(activity.intents);
12196                }
12197            }
12198            return new ParceledListSlice<>(result);
12199        }
12200    }
12201
12202    @Override
12203    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12204        mContext.enforceCallingOrSelfPermission(
12205                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12206
12207        synchronized (mPackages) {
12208            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12209            if (packageName != null) {
12210                result |= updateIntentVerificationStatus(packageName,
12211                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12212                        userId);
12213                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12214                        packageName, userId);
12215            }
12216            return result;
12217        }
12218    }
12219
12220    @Override
12221    public String getDefaultBrowserPackageName(int userId) {
12222        synchronized (mPackages) {
12223            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12224        }
12225    }
12226
12227    /**
12228     * Get the "allow unknown sources" setting.
12229     *
12230     * @return the current "allow unknown sources" setting
12231     */
12232    private int getUnknownSourcesSettings() {
12233        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12234                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12235                -1);
12236    }
12237
12238    @Override
12239    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12240        final int uid = Binder.getCallingUid();
12241        // writer
12242        synchronized (mPackages) {
12243            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12244            if (targetPackageSetting == null) {
12245                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12246            }
12247
12248            PackageSetting installerPackageSetting;
12249            if (installerPackageName != null) {
12250                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12251                if (installerPackageSetting == null) {
12252                    throw new IllegalArgumentException("Unknown installer package: "
12253                            + installerPackageName);
12254                }
12255            } else {
12256                installerPackageSetting = null;
12257            }
12258
12259            Signature[] callerSignature;
12260            Object obj = mSettings.getUserIdLPr(uid);
12261            if (obj != null) {
12262                if (obj instanceof SharedUserSetting) {
12263                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12264                } else if (obj instanceof PackageSetting) {
12265                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12266                } else {
12267                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12268                }
12269            } else {
12270                throw new SecurityException("Unknown calling UID: " + uid);
12271            }
12272
12273            // Verify: can't set installerPackageName to a package that is
12274            // not signed with the same cert as the caller.
12275            if (installerPackageSetting != null) {
12276                if (compareSignatures(callerSignature,
12277                        installerPackageSetting.signatures.mSignatures)
12278                        != PackageManager.SIGNATURE_MATCH) {
12279                    throw new SecurityException(
12280                            "Caller does not have same cert as new installer package "
12281                            + installerPackageName);
12282                }
12283            }
12284
12285            // Verify: if target already has an installer package, it must
12286            // be signed with the same cert as the caller.
12287            if (targetPackageSetting.installerPackageName != null) {
12288                PackageSetting setting = mSettings.mPackages.get(
12289                        targetPackageSetting.installerPackageName);
12290                // If the currently set package isn't valid, then it's always
12291                // okay to change it.
12292                if (setting != null) {
12293                    if (compareSignatures(callerSignature,
12294                            setting.signatures.mSignatures)
12295                            != PackageManager.SIGNATURE_MATCH) {
12296                        throw new SecurityException(
12297                                "Caller does not have same cert as old installer package "
12298                                + targetPackageSetting.installerPackageName);
12299                    }
12300                }
12301            }
12302
12303            // Okay!
12304            targetPackageSetting.installerPackageName = installerPackageName;
12305            if (installerPackageName != null) {
12306                mSettings.mInstallerPackages.add(installerPackageName);
12307            }
12308            scheduleWriteSettingsLocked();
12309        }
12310    }
12311
12312    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12313        // Queue up an async operation since the package installation may take a little while.
12314        mHandler.post(new Runnable() {
12315            public void run() {
12316                mHandler.removeCallbacks(this);
12317                 // Result object to be returned
12318                PackageInstalledInfo res = new PackageInstalledInfo();
12319                res.setReturnCode(currentStatus);
12320                res.uid = -1;
12321                res.pkg = null;
12322                res.removedInfo = null;
12323                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12324                    args.doPreInstall(res.returnCode);
12325                    synchronized (mInstallLock) {
12326                        installPackageTracedLI(args, res);
12327                    }
12328                    args.doPostInstall(res.returnCode, res.uid);
12329                }
12330
12331                // A restore should be performed at this point if (a) the install
12332                // succeeded, (b) the operation is not an update, and (c) the new
12333                // package has not opted out of backup participation.
12334                final boolean update = res.removedInfo != null
12335                        && res.removedInfo.removedPackage != null;
12336                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12337                boolean doRestore = !update
12338                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12339
12340                // Set up the post-install work request bookkeeping.  This will be used
12341                // and cleaned up by the post-install event handling regardless of whether
12342                // there's a restore pass performed.  Token values are >= 1.
12343                int token;
12344                if (mNextInstallToken < 0) mNextInstallToken = 1;
12345                token = mNextInstallToken++;
12346
12347                PostInstallData data = new PostInstallData(args, res);
12348                mRunningInstalls.put(token, data);
12349                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12350
12351                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12352                    // Pass responsibility to the Backup Manager.  It will perform a
12353                    // restore if appropriate, then pass responsibility back to the
12354                    // Package Manager to run the post-install observer callbacks
12355                    // and broadcasts.
12356                    IBackupManager bm = IBackupManager.Stub.asInterface(
12357                            ServiceManager.getService(Context.BACKUP_SERVICE));
12358                    if (bm != null) {
12359                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12360                                + " to BM for possible restore");
12361                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12362                        try {
12363                            // TODO: http://b/22388012
12364                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12365                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12366                            } else {
12367                                doRestore = false;
12368                            }
12369                        } catch (RemoteException e) {
12370                            // can't happen; the backup manager is local
12371                        } catch (Exception e) {
12372                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12373                            doRestore = false;
12374                        }
12375                    } else {
12376                        Slog.e(TAG, "Backup Manager not found!");
12377                        doRestore = false;
12378                    }
12379                }
12380
12381                if (!doRestore) {
12382                    // No restore possible, or the Backup Manager was mysteriously not
12383                    // available -- just fire the post-install work request directly.
12384                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12385
12386                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12387
12388                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12389                    mHandler.sendMessage(msg);
12390                }
12391            }
12392        });
12393    }
12394
12395    /**
12396     * Callback from PackageSettings whenever an app is first transitioned out of the
12397     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12398     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12399     * here whether the app is the target of an ongoing install, and only send the
12400     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12401     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12402     * handling.
12403     */
12404    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12405        // Serialize this with the rest of the install-process message chain.  In the
12406        // restore-at-install case, this Runnable will necessarily run before the
12407        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12408        // are coherent.  In the non-restore case, the app has already completed install
12409        // and been launched through some other means, so it is not in a problematic
12410        // state for observers to see the FIRST_LAUNCH signal.
12411        mHandler.post(new Runnable() {
12412            @Override
12413            public void run() {
12414                for (int i = 0; i < mRunningInstalls.size(); i++) {
12415                    final PostInstallData data = mRunningInstalls.valueAt(i);
12416                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12417                        // right package; but is it for the right user?
12418                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12419                            if (userId == data.res.newUsers[uIndex]) {
12420                                if (DEBUG_BACKUP) {
12421                                    Slog.i(TAG, "Package " + pkgName
12422                                            + " being restored so deferring FIRST_LAUNCH");
12423                                }
12424                                return;
12425                            }
12426                        }
12427                    }
12428                }
12429                // didn't find it, so not being restored
12430                if (DEBUG_BACKUP) {
12431                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12432                }
12433                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12434            }
12435        });
12436    }
12437
12438    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12439        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12440                installerPkg, null, userIds);
12441    }
12442
12443    private abstract class HandlerParams {
12444        private static final int MAX_RETRIES = 4;
12445
12446        /**
12447         * Number of times startCopy() has been attempted and had a non-fatal
12448         * error.
12449         */
12450        private int mRetries = 0;
12451
12452        /** User handle for the user requesting the information or installation. */
12453        private final UserHandle mUser;
12454        String traceMethod;
12455        int traceCookie;
12456
12457        HandlerParams(UserHandle user) {
12458            mUser = user;
12459        }
12460
12461        UserHandle getUser() {
12462            return mUser;
12463        }
12464
12465        HandlerParams setTraceMethod(String traceMethod) {
12466            this.traceMethod = traceMethod;
12467            return this;
12468        }
12469
12470        HandlerParams setTraceCookie(int traceCookie) {
12471            this.traceCookie = traceCookie;
12472            return this;
12473        }
12474
12475        final boolean startCopy() {
12476            boolean res;
12477            try {
12478                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12479
12480                if (++mRetries > MAX_RETRIES) {
12481                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12482                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12483                    handleServiceError();
12484                    return false;
12485                } else {
12486                    handleStartCopy();
12487                    res = true;
12488                }
12489            } catch (RemoteException e) {
12490                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12491                mHandler.sendEmptyMessage(MCS_RECONNECT);
12492                res = false;
12493            }
12494            handleReturnCode();
12495            return res;
12496        }
12497
12498        final void serviceError() {
12499            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12500            handleServiceError();
12501            handleReturnCode();
12502        }
12503
12504        abstract void handleStartCopy() throws RemoteException;
12505        abstract void handleServiceError();
12506        abstract void handleReturnCode();
12507    }
12508
12509    class MeasureParams extends HandlerParams {
12510        private final PackageStats mStats;
12511        private boolean mSuccess;
12512
12513        private final IPackageStatsObserver mObserver;
12514
12515        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12516            super(new UserHandle(stats.userHandle));
12517            mObserver = observer;
12518            mStats = stats;
12519        }
12520
12521        @Override
12522        public String toString() {
12523            return "MeasureParams{"
12524                + Integer.toHexString(System.identityHashCode(this))
12525                + " " + mStats.packageName + "}";
12526        }
12527
12528        @Override
12529        void handleStartCopy() throws RemoteException {
12530            synchronized (mInstallLock) {
12531                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12532            }
12533
12534            if (mSuccess) {
12535                final boolean mounted;
12536                if (Environment.isExternalStorageEmulated()) {
12537                    mounted = true;
12538                } else {
12539                    final String status = Environment.getExternalStorageState();
12540                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12541                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12542                }
12543
12544                if (mounted) {
12545                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12546
12547                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12548                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12549
12550                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12551                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12552
12553                    // Always subtract cache size, since it's a subdirectory
12554                    mStats.externalDataSize -= mStats.externalCacheSize;
12555
12556                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12557                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12558
12559                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12560                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12561                }
12562            }
12563        }
12564
12565        @Override
12566        void handleReturnCode() {
12567            if (mObserver != null) {
12568                try {
12569                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12570                } catch (RemoteException e) {
12571                    Slog.i(TAG, "Observer no longer exists.");
12572                }
12573            }
12574        }
12575
12576        @Override
12577        void handleServiceError() {
12578            Slog.e(TAG, "Could not measure application " + mStats.packageName
12579                            + " external storage");
12580        }
12581    }
12582
12583    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12584            throws RemoteException {
12585        long result = 0;
12586        for (File path : paths) {
12587            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12588        }
12589        return result;
12590    }
12591
12592    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12593        for (File path : paths) {
12594            try {
12595                mcs.clearDirectory(path.getAbsolutePath());
12596            } catch (RemoteException e) {
12597            }
12598        }
12599    }
12600
12601    static class OriginInfo {
12602        /**
12603         * Location where install is coming from, before it has been
12604         * copied/renamed into place. This could be a single monolithic APK
12605         * file, or a cluster directory. This location may be untrusted.
12606         */
12607        final File file;
12608        final String cid;
12609
12610        /**
12611         * Flag indicating that {@link #file} or {@link #cid} has already been
12612         * staged, meaning downstream users don't need to defensively copy the
12613         * contents.
12614         */
12615        final boolean staged;
12616
12617        /**
12618         * Flag indicating that {@link #file} or {@link #cid} is an already
12619         * installed app that is being moved.
12620         */
12621        final boolean existing;
12622
12623        final String resolvedPath;
12624        final File resolvedFile;
12625
12626        static OriginInfo fromNothing() {
12627            return new OriginInfo(null, null, false, false);
12628        }
12629
12630        static OriginInfo fromUntrustedFile(File file) {
12631            return new OriginInfo(file, null, false, false);
12632        }
12633
12634        static OriginInfo fromExistingFile(File file) {
12635            return new OriginInfo(file, null, false, true);
12636        }
12637
12638        static OriginInfo fromStagedFile(File file) {
12639            return new OriginInfo(file, null, true, false);
12640        }
12641
12642        static OriginInfo fromStagedContainer(String cid) {
12643            return new OriginInfo(null, cid, true, false);
12644        }
12645
12646        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12647            this.file = file;
12648            this.cid = cid;
12649            this.staged = staged;
12650            this.existing = existing;
12651
12652            if (cid != null) {
12653                resolvedPath = PackageHelper.getSdDir(cid);
12654                resolvedFile = new File(resolvedPath);
12655            } else if (file != null) {
12656                resolvedPath = file.getAbsolutePath();
12657                resolvedFile = file;
12658            } else {
12659                resolvedPath = null;
12660                resolvedFile = null;
12661            }
12662        }
12663    }
12664
12665    static class MoveInfo {
12666        final int moveId;
12667        final String fromUuid;
12668        final String toUuid;
12669        final String packageName;
12670        final String dataAppName;
12671        final int appId;
12672        final String seinfo;
12673        final int targetSdkVersion;
12674
12675        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12676                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12677            this.moveId = moveId;
12678            this.fromUuid = fromUuid;
12679            this.toUuid = toUuid;
12680            this.packageName = packageName;
12681            this.dataAppName = dataAppName;
12682            this.appId = appId;
12683            this.seinfo = seinfo;
12684            this.targetSdkVersion = targetSdkVersion;
12685        }
12686    }
12687
12688    static class VerificationInfo {
12689        /** A constant used to indicate that a uid value is not present. */
12690        public static final int NO_UID = -1;
12691
12692        /** URI referencing where the package was downloaded from. */
12693        final Uri originatingUri;
12694
12695        /** HTTP referrer URI associated with the originatingURI. */
12696        final Uri referrer;
12697
12698        /** UID of the application that the install request originated from. */
12699        final int originatingUid;
12700
12701        /** UID of application requesting the install */
12702        final int installerUid;
12703
12704        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12705            this.originatingUri = originatingUri;
12706            this.referrer = referrer;
12707            this.originatingUid = originatingUid;
12708            this.installerUid = installerUid;
12709        }
12710    }
12711
12712    class InstallParams extends HandlerParams {
12713        final OriginInfo origin;
12714        final MoveInfo move;
12715        final IPackageInstallObserver2 observer;
12716        int installFlags;
12717        final String installerPackageName;
12718        final String volumeUuid;
12719        private InstallArgs mArgs;
12720        private int mRet;
12721        final String packageAbiOverride;
12722        final String[] grantedRuntimePermissions;
12723        final VerificationInfo verificationInfo;
12724        final Certificate[][] certificates;
12725
12726        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12727                int installFlags, String installerPackageName, String volumeUuid,
12728                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12729                String[] grantedPermissions, Certificate[][] certificates) {
12730            super(user);
12731            this.origin = origin;
12732            this.move = move;
12733            this.observer = observer;
12734            this.installFlags = installFlags;
12735            this.installerPackageName = installerPackageName;
12736            this.volumeUuid = volumeUuid;
12737            this.verificationInfo = verificationInfo;
12738            this.packageAbiOverride = packageAbiOverride;
12739            this.grantedRuntimePermissions = grantedPermissions;
12740            this.certificates = certificates;
12741        }
12742
12743        @Override
12744        public String toString() {
12745            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12746                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12747        }
12748
12749        private int installLocationPolicy(PackageInfoLite pkgLite) {
12750            String packageName = pkgLite.packageName;
12751            int installLocation = pkgLite.installLocation;
12752            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12753            // reader
12754            synchronized (mPackages) {
12755                // Currently installed package which the new package is attempting to replace or
12756                // null if no such package is installed.
12757                PackageParser.Package installedPkg = mPackages.get(packageName);
12758                // Package which currently owns the data which the new package will own if installed.
12759                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12760                // will be null whereas dataOwnerPkg will contain information about the package
12761                // which was uninstalled while keeping its data.
12762                PackageParser.Package dataOwnerPkg = installedPkg;
12763                if (dataOwnerPkg  == null) {
12764                    PackageSetting ps = mSettings.mPackages.get(packageName);
12765                    if (ps != null) {
12766                        dataOwnerPkg = ps.pkg;
12767                    }
12768                }
12769
12770                if (dataOwnerPkg != null) {
12771                    // If installed, the package will get access to data left on the device by its
12772                    // predecessor. As a security measure, this is permited only if this is not a
12773                    // version downgrade or if the predecessor package is marked as debuggable and
12774                    // a downgrade is explicitly requested.
12775                    //
12776                    // On debuggable platform builds, downgrades are permitted even for
12777                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12778                    // not offer security guarantees and thus it's OK to disable some security
12779                    // mechanisms to make debugging/testing easier on those builds. However, even on
12780                    // debuggable builds downgrades of packages are permitted only if requested via
12781                    // installFlags. This is because we aim to keep the behavior of debuggable
12782                    // platform builds as close as possible to the behavior of non-debuggable
12783                    // platform builds.
12784                    final boolean downgradeRequested =
12785                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12786                    final boolean packageDebuggable =
12787                                (dataOwnerPkg.applicationInfo.flags
12788                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12789                    final boolean downgradePermitted =
12790                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12791                    if (!downgradePermitted) {
12792                        try {
12793                            checkDowngrade(dataOwnerPkg, pkgLite);
12794                        } catch (PackageManagerException e) {
12795                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12796                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12797                        }
12798                    }
12799                }
12800
12801                if (installedPkg != null) {
12802                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12803                        // Check for updated system application.
12804                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12805                            if (onSd) {
12806                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12807                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12808                            }
12809                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12810                        } else {
12811                            if (onSd) {
12812                                // Install flag overrides everything.
12813                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12814                            }
12815                            // If current upgrade specifies particular preference
12816                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12817                                // Application explicitly specified internal.
12818                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12819                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12820                                // App explictly prefers external. Let policy decide
12821                            } else {
12822                                // Prefer previous location
12823                                if (isExternal(installedPkg)) {
12824                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12825                                }
12826                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12827                            }
12828                        }
12829                    } else {
12830                        // Invalid install. Return error code
12831                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12832                    }
12833                }
12834            }
12835            // All the special cases have been taken care of.
12836            // Return result based on recommended install location.
12837            if (onSd) {
12838                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12839            }
12840            return pkgLite.recommendedInstallLocation;
12841        }
12842
12843        /*
12844         * Invoke remote method to get package information and install
12845         * location values. Override install location based on default
12846         * policy if needed and then create install arguments based
12847         * on the install location.
12848         */
12849        public void handleStartCopy() throws RemoteException {
12850            int ret = PackageManager.INSTALL_SUCCEEDED;
12851
12852            // If we're already staged, we've firmly committed to an install location
12853            if (origin.staged) {
12854                if (origin.file != null) {
12855                    installFlags |= PackageManager.INSTALL_INTERNAL;
12856                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12857                } else if (origin.cid != null) {
12858                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12859                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12860                } else {
12861                    throw new IllegalStateException("Invalid stage location");
12862                }
12863            }
12864
12865            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12866            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12867            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12868            PackageInfoLite pkgLite = null;
12869
12870            if (onInt && onSd) {
12871                // Check if both bits are set.
12872                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12873                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12874            } else if (onSd && ephemeral) {
12875                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12876                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12877            } else {
12878                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12879                        packageAbiOverride);
12880
12881                if (DEBUG_EPHEMERAL && ephemeral) {
12882                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12883                }
12884
12885                /*
12886                 * If we have too little free space, try to free cache
12887                 * before giving up.
12888                 */
12889                if (!origin.staged && pkgLite.recommendedInstallLocation
12890                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12891                    // TODO: focus freeing disk space on the target device
12892                    final StorageManager storage = StorageManager.from(mContext);
12893                    final long lowThreshold = storage.getStorageLowBytes(
12894                            Environment.getDataDirectory());
12895
12896                    final long sizeBytes = mContainerService.calculateInstalledSize(
12897                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12898
12899                    try {
12900                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12901                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12902                                installFlags, packageAbiOverride);
12903                    } catch (InstallerException e) {
12904                        Slog.w(TAG, "Failed to free cache", e);
12905                    }
12906
12907                    /*
12908                     * The cache free must have deleted the file we
12909                     * downloaded to install.
12910                     *
12911                     * TODO: fix the "freeCache" call to not delete
12912                     *       the file we care about.
12913                     */
12914                    if (pkgLite.recommendedInstallLocation
12915                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12916                        pkgLite.recommendedInstallLocation
12917                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12918                    }
12919                }
12920            }
12921
12922            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12923                int loc = pkgLite.recommendedInstallLocation;
12924                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12925                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12926                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12927                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12928                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12929                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12930                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12931                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12932                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12933                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12934                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12935                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12936                } else {
12937                    // Override with defaults if needed.
12938                    loc = installLocationPolicy(pkgLite);
12939                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12940                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12941                    } else if (!onSd && !onInt) {
12942                        // Override install location with flags
12943                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12944                            // Set the flag to install on external media.
12945                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12946                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12947                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12948                            if (DEBUG_EPHEMERAL) {
12949                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12950                            }
12951                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12952                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12953                                    |PackageManager.INSTALL_INTERNAL);
12954                        } else {
12955                            // Make sure the flag for installing on external
12956                            // media is unset
12957                            installFlags |= PackageManager.INSTALL_INTERNAL;
12958                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12959                        }
12960                    }
12961                }
12962            }
12963
12964            final InstallArgs args = createInstallArgs(this);
12965            mArgs = args;
12966
12967            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12968                // TODO: http://b/22976637
12969                // Apps installed for "all" users use the device owner to verify the app
12970                UserHandle verifierUser = getUser();
12971                if (verifierUser == UserHandle.ALL) {
12972                    verifierUser = UserHandle.SYSTEM;
12973                }
12974
12975                /*
12976                 * Determine if we have any installed package verifiers. If we
12977                 * do, then we'll defer to them to verify the packages.
12978                 */
12979                final int requiredUid = mRequiredVerifierPackage == null ? -1
12980                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12981                                verifierUser.getIdentifier());
12982                if (!origin.existing && requiredUid != -1
12983                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12984                    final Intent verification = new Intent(
12985                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12986                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12987                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12988                            PACKAGE_MIME_TYPE);
12989                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12990
12991                    // Query all live verifiers based on current user state
12992                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12993                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12994
12995                    if (DEBUG_VERIFY) {
12996                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12997                                + verification.toString() + " with " + pkgLite.verifiers.length
12998                                + " optional verifiers");
12999                    }
13000
13001                    final int verificationId = mPendingVerificationToken++;
13002
13003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13004
13005                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13006                            installerPackageName);
13007
13008                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13009                            installFlags);
13010
13011                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13012                            pkgLite.packageName);
13013
13014                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13015                            pkgLite.versionCode);
13016
13017                    if (verificationInfo != null) {
13018                        if (verificationInfo.originatingUri != null) {
13019                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13020                                    verificationInfo.originatingUri);
13021                        }
13022                        if (verificationInfo.referrer != null) {
13023                            verification.putExtra(Intent.EXTRA_REFERRER,
13024                                    verificationInfo.referrer);
13025                        }
13026                        if (verificationInfo.originatingUid >= 0) {
13027                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13028                                    verificationInfo.originatingUid);
13029                        }
13030                        if (verificationInfo.installerUid >= 0) {
13031                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13032                                    verificationInfo.installerUid);
13033                        }
13034                    }
13035
13036                    final PackageVerificationState verificationState = new PackageVerificationState(
13037                            requiredUid, args);
13038
13039                    mPendingVerification.append(verificationId, verificationState);
13040
13041                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13042                            receivers, verificationState);
13043
13044                    /*
13045                     * If any sufficient verifiers were listed in the package
13046                     * manifest, attempt to ask them.
13047                     */
13048                    if (sufficientVerifiers != null) {
13049                        final int N = sufficientVerifiers.size();
13050                        if (N == 0) {
13051                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13052                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13053                        } else {
13054                            for (int i = 0; i < N; i++) {
13055                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13056
13057                                final Intent sufficientIntent = new Intent(verification);
13058                                sufficientIntent.setComponent(verifierComponent);
13059                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13060                            }
13061                        }
13062                    }
13063
13064                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13065                            mRequiredVerifierPackage, receivers);
13066                    if (ret == PackageManager.INSTALL_SUCCEEDED
13067                            && mRequiredVerifierPackage != null) {
13068                        Trace.asyncTraceBegin(
13069                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13070                        /*
13071                         * Send the intent to the required verification agent,
13072                         * but only start the verification timeout after the
13073                         * target BroadcastReceivers have run.
13074                         */
13075                        verification.setComponent(requiredVerifierComponent);
13076                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13077                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13078                                new BroadcastReceiver() {
13079                                    @Override
13080                                    public void onReceive(Context context, Intent intent) {
13081                                        final Message msg = mHandler
13082                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13083                                        msg.arg1 = verificationId;
13084                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13085                                    }
13086                                }, null, 0, null, null);
13087
13088                        /*
13089                         * We don't want the copy to proceed until verification
13090                         * succeeds, so null out this field.
13091                         */
13092                        mArgs = null;
13093                    }
13094                } else {
13095                    /*
13096                     * No package verification is enabled, so immediately start
13097                     * the remote call to initiate copy using temporary file.
13098                     */
13099                    ret = args.copyApk(mContainerService, true);
13100                }
13101            }
13102
13103            mRet = ret;
13104        }
13105
13106        @Override
13107        void handleReturnCode() {
13108            // If mArgs is null, then MCS couldn't be reached. When it
13109            // reconnects, it will try again to install. At that point, this
13110            // will succeed.
13111            if (mArgs != null) {
13112                processPendingInstall(mArgs, mRet);
13113            }
13114        }
13115
13116        @Override
13117        void handleServiceError() {
13118            mArgs = createInstallArgs(this);
13119            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13120        }
13121
13122        public boolean isForwardLocked() {
13123            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13124        }
13125    }
13126
13127    /**
13128     * Used during creation of InstallArgs
13129     *
13130     * @param installFlags package installation flags
13131     * @return true if should be installed on external storage
13132     */
13133    private static boolean installOnExternalAsec(int installFlags) {
13134        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13135            return false;
13136        }
13137        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13138            return true;
13139        }
13140        return false;
13141    }
13142
13143    /**
13144     * Used during creation of InstallArgs
13145     *
13146     * @param installFlags package installation flags
13147     * @return true if should be installed as forward locked
13148     */
13149    private static boolean installForwardLocked(int installFlags) {
13150        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13151    }
13152
13153    private InstallArgs createInstallArgs(InstallParams params) {
13154        if (params.move != null) {
13155            return new MoveInstallArgs(params);
13156        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13157            return new AsecInstallArgs(params);
13158        } else {
13159            return new FileInstallArgs(params);
13160        }
13161    }
13162
13163    /**
13164     * Create args that describe an existing installed package. Typically used
13165     * when cleaning up old installs, or used as a move source.
13166     */
13167    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13168            String resourcePath, String[] instructionSets) {
13169        final boolean isInAsec;
13170        if (installOnExternalAsec(installFlags)) {
13171            /* Apps on SD card are always in ASEC containers. */
13172            isInAsec = true;
13173        } else if (installForwardLocked(installFlags)
13174                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13175            /*
13176             * Forward-locked apps are only in ASEC containers if they're the
13177             * new style
13178             */
13179            isInAsec = true;
13180        } else {
13181            isInAsec = false;
13182        }
13183
13184        if (isInAsec) {
13185            return new AsecInstallArgs(codePath, instructionSets,
13186                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13187        } else {
13188            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13189        }
13190    }
13191
13192    static abstract class InstallArgs {
13193        /** @see InstallParams#origin */
13194        final OriginInfo origin;
13195        /** @see InstallParams#move */
13196        final MoveInfo move;
13197
13198        final IPackageInstallObserver2 observer;
13199        // Always refers to PackageManager flags only
13200        final int installFlags;
13201        final String installerPackageName;
13202        final String volumeUuid;
13203        final UserHandle user;
13204        final String abiOverride;
13205        final String[] installGrantPermissions;
13206        /** If non-null, drop an async trace when the install completes */
13207        final String traceMethod;
13208        final int traceCookie;
13209        final Certificate[][] certificates;
13210
13211        // The list of instruction sets supported by this app. This is currently
13212        // only used during the rmdex() phase to clean up resources. We can get rid of this
13213        // if we move dex files under the common app path.
13214        /* nullable */ String[] instructionSets;
13215
13216        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13217                int installFlags, String installerPackageName, String volumeUuid,
13218                UserHandle user, String[] instructionSets,
13219                String abiOverride, String[] installGrantPermissions,
13220                String traceMethod, int traceCookie, Certificate[][] certificates) {
13221            this.origin = origin;
13222            this.move = move;
13223            this.installFlags = installFlags;
13224            this.observer = observer;
13225            this.installerPackageName = installerPackageName;
13226            this.volumeUuid = volumeUuid;
13227            this.user = user;
13228            this.instructionSets = instructionSets;
13229            this.abiOverride = abiOverride;
13230            this.installGrantPermissions = installGrantPermissions;
13231            this.traceMethod = traceMethod;
13232            this.traceCookie = traceCookie;
13233            this.certificates = certificates;
13234        }
13235
13236        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13237        abstract int doPreInstall(int status);
13238
13239        /**
13240         * Rename package into final resting place. All paths on the given
13241         * scanned package should be updated to reflect the rename.
13242         */
13243        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13244        abstract int doPostInstall(int status, int uid);
13245
13246        /** @see PackageSettingBase#codePathString */
13247        abstract String getCodePath();
13248        /** @see PackageSettingBase#resourcePathString */
13249        abstract String getResourcePath();
13250
13251        // Need installer lock especially for dex file removal.
13252        abstract void cleanUpResourcesLI();
13253        abstract boolean doPostDeleteLI(boolean delete);
13254
13255        /**
13256         * Called before the source arguments are copied. This is used mostly
13257         * for MoveParams when it needs to read the source file to put it in the
13258         * destination.
13259         */
13260        int doPreCopy() {
13261            return PackageManager.INSTALL_SUCCEEDED;
13262        }
13263
13264        /**
13265         * Called after the source arguments are copied. This is used mostly for
13266         * MoveParams when it needs to read the source file to put it in the
13267         * destination.
13268         */
13269        int doPostCopy(int uid) {
13270            return PackageManager.INSTALL_SUCCEEDED;
13271        }
13272
13273        protected boolean isFwdLocked() {
13274            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13275        }
13276
13277        protected boolean isExternalAsec() {
13278            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13279        }
13280
13281        protected boolean isEphemeral() {
13282            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13283        }
13284
13285        UserHandle getUser() {
13286            return user;
13287        }
13288    }
13289
13290    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13291        if (!allCodePaths.isEmpty()) {
13292            if (instructionSets == null) {
13293                throw new IllegalStateException("instructionSet == null");
13294            }
13295            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13296            for (String codePath : allCodePaths) {
13297                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13298                    try {
13299                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13300                    } catch (InstallerException ignored) {
13301                    }
13302                }
13303            }
13304        }
13305    }
13306
13307    /**
13308     * Logic to handle installation of non-ASEC applications, including copying
13309     * and renaming logic.
13310     */
13311    class FileInstallArgs extends InstallArgs {
13312        private File codeFile;
13313        private File resourceFile;
13314
13315        // Example topology:
13316        // /data/app/com.example/base.apk
13317        // /data/app/com.example/split_foo.apk
13318        // /data/app/com.example/lib/arm/libfoo.so
13319        // /data/app/com.example/lib/arm64/libfoo.so
13320        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13321
13322        /** New install */
13323        FileInstallArgs(InstallParams params) {
13324            super(params.origin, params.move, params.observer, params.installFlags,
13325                    params.installerPackageName, params.volumeUuid,
13326                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13327                    params.grantedRuntimePermissions,
13328                    params.traceMethod, params.traceCookie, params.certificates);
13329            if (isFwdLocked()) {
13330                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13331            }
13332        }
13333
13334        /** Existing install */
13335        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13336            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13337                    null, null, null, 0, null /*certificates*/);
13338            this.codeFile = (codePath != null) ? new File(codePath) : null;
13339            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13340        }
13341
13342        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13343            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13344            try {
13345                return doCopyApk(imcs, temp);
13346            } finally {
13347                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13348            }
13349        }
13350
13351        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13352            if (origin.staged) {
13353                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13354                codeFile = origin.file;
13355                resourceFile = origin.file;
13356                return PackageManager.INSTALL_SUCCEEDED;
13357            }
13358
13359            try {
13360                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13361                final File tempDir =
13362                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13363                codeFile = tempDir;
13364                resourceFile = tempDir;
13365            } catch (IOException e) {
13366                Slog.w(TAG, "Failed to create copy file: " + e);
13367                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13368            }
13369
13370            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13371                @Override
13372                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13373                    if (!FileUtils.isValidExtFilename(name)) {
13374                        throw new IllegalArgumentException("Invalid filename: " + name);
13375                    }
13376                    try {
13377                        final File file = new File(codeFile, name);
13378                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13379                                O_RDWR | O_CREAT, 0644);
13380                        Os.chmod(file.getAbsolutePath(), 0644);
13381                        return new ParcelFileDescriptor(fd);
13382                    } catch (ErrnoException e) {
13383                        throw new RemoteException("Failed to open: " + e.getMessage());
13384                    }
13385                }
13386            };
13387
13388            int ret = PackageManager.INSTALL_SUCCEEDED;
13389            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13390            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13391                Slog.e(TAG, "Failed to copy package");
13392                return ret;
13393            }
13394
13395            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13396            NativeLibraryHelper.Handle handle = null;
13397            try {
13398                handle = NativeLibraryHelper.Handle.create(codeFile);
13399                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13400                        abiOverride);
13401            } catch (IOException e) {
13402                Slog.e(TAG, "Copying native libraries failed", e);
13403                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13404            } finally {
13405                IoUtils.closeQuietly(handle);
13406            }
13407
13408            return ret;
13409        }
13410
13411        int doPreInstall(int status) {
13412            if (status != PackageManager.INSTALL_SUCCEEDED) {
13413                cleanUp();
13414            }
13415            return status;
13416        }
13417
13418        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13419            if (status != PackageManager.INSTALL_SUCCEEDED) {
13420                cleanUp();
13421                return false;
13422            }
13423
13424            final File targetDir = codeFile.getParentFile();
13425            final File beforeCodeFile = codeFile;
13426            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13427
13428            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13429            try {
13430                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13431            } catch (ErrnoException e) {
13432                Slog.w(TAG, "Failed to rename", e);
13433                return false;
13434            }
13435
13436            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13437                Slog.w(TAG, "Failed to restorecon");
13438                return false;
13439            }
13440
13441            // Reflect the rename internally
13442            codeFile = afterCodeFile;
13443            resourceFile = afterCodeFile;
13444
13445            // Reflect the rename in scanned details
13446            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13447            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13448                    afterCodeFile, pkg.baseCodePath));
13449            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13450                    afterCodeFile, pkg.splitCodePaths));
13451
13452            // Reflect the rename in app info
13453            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13454            pkg.setApplicationInfoCodePath(pkg.codePath);
13455            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13456            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13457            pkg.setApplicationInfoResourcePath(pkg.codePath);
13458            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13459            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13460
13461            return true;
13462        }
13463
13464        int doPostInstall(int status, int uid) {
13465            if (status != PackageManager.INSTALL_SUCCEEDED) {
13466                cleanUp();
13467            }
13468            return status;
13469        }
13470
13471        @Override
13472        String getCodePath() {
13473            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13474        }
13475
13476        @Override
13477        String getResourcePath() {
13478            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13479        }
13480
13481        private boolean cleanUp() {
13482            if (codeFile == null || !codeFile.exists()) {
13483                return false;
13484            }
13485
13486            removeCodePathLI(codeFile);
13487
13488            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13489                resourceFile.delete();
13490            }
13491
13492            return true;
13493        }
13494
13495        void cleanUpResourcesLI() {
13496            // Try enumerating all code paths before deleting
13497            List<String> allCodePaths = Collections.EMPTY_LIST;
13498            if (codeFile != null && codeFile.exists()) {
13499                try {
13500                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13501                    allCodePaths = pkg.getAllCodePaths();
13502                } catch (PackageParserException e) {
13503                    // Ignored; we tried our best
13504                }
13505            }
13506
13507            cleanUp();
13508            removeDexFiles(allCodePaths, instructionSets);
13509        }
13510
13511        boolean doPostDeleteLI(boolean delete) {
13512            // XXX err, shouldn't we respect the delete flag?
13513            cleanUpResourcesLI();
13514            return true;
13515        }
13516    }
13517
13518    private boolean isAsecExternal(String cid) {
13519        final String asecPath = PackageHelper.getSdFilesystem(cid);
13520        return !asecPath.startsWith(mAsecInternalPath);
13521    }
13522
13523    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13524            PackageManagerException {
13525        if (copyRet < 0) {
13526            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13527                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13528                throw new PackageManagerException(copyRet, message);
13529            }
13530        }
13531    }
13532
13533    /**
13534     * Extract the MountService "container ID" from the full code path of an
13535     * .apk.
13536     */
13537    static String cidFromCodePath(String fullCodePath) {
13538        int eidx = fullCodePath.lastIndexOf("/");
13539        String subStr1 = fullCodePath.substring(0, eidx);
13540        int sidx = subStr1.lastIndexOf("/");
13541        return subStr1.substring(sidx+1, eidx);
13542    }
13543
13544    /**
13545     * Logic to handle installation of ASEC applications, including copying and
13546     * renaming logic.
13547     */
13548    class AsecInstallArgs extends InstallArgs {
13549        static final String RES_FILE_NAME = "pkg.apk";
13550        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13551
13552        String cid;
13553        String packagePath;
13554        String resourcePath;
13555
13556        /** New install */
13557        AsecInstallArgs(InstallParams params) {
13558            super(params.origin, params.move, params.observer, params.installFlags,
13559                    params.installerPackageName, params.volumeUuid,
13560                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13561                    params.grantedRuntimePermissions,
13562                    params.traceMethod, params.traceCookie, params.certificates);
13563        }
13564
13565        /** Existing install */
13566        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13567                        boolean isExternal, boolean isForwardLocked) {
13568            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13569              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13570                    instructionSets, null, null, null, 0, null /*certificates*/);
13571            // Hackily pretend we're still looking at a full code path
13572            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13573                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13574            }
13575
13576            // Extract cid from fullCodePath
13577            int eidx = fullCodePath.lastIndexOf("/");
13578            String subStr1 = fullCodePath.substring(0, eidx);
13579            int sidx = subStr1.lastIndexOf("/");
13580            cid = subStr1.substring(sidx+1, eidx);
13581            setMountPath(subStr1);
13582        }
13583
13584        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13585            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13586              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13587                    instructionSets, null, null, null, 0, null /*certificates*/);
13588            this.cid = cid;
13589            setMountPath(PackageHelper.getSdDir(cid));
13590        }
13591
13592        void createCopyFile() {
13593            cid = mInstallerService.allocateExternalStageCidLegacy();
13594        }
13595
13596        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13597            if (origin.staged && origin.cid != null) {
13598                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13599                cid = origin.cid;
13600                setMountPath(PackageHelper.getSdDir(cid));
13601                return PackageManager.INSTALL_SUCCEEDED;
13602            }
13603
13604            if (temp) {
13605                createCopyFile();
13606            } else {
13607                /*
13608                 * Pre-emptively destroy the container since it's destroyed if
13609                 * copying fails due to it existing anyway.
13610                 */
13611                PackageHelper.destroySdDir(cid);
13612            }
13613
13614            final String newMountPath = imcs.copyPackageToContainer(
13615                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13616                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13617
13618            if (newMountPath != null) {
13619                setMountPath(newMountPath);
13620                return PackageManager.INSTALL_SUCCEEDED;
13621            } else {
13622                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13623            }
13624        }
13625
13626        @Override
13627        String getCodePath() {
13628            return packagePath;
13629        }
13630
13631        @Override
13632        String getResourcePath() {
13633            return resourcePath;
13634        }
13635
13636        int doPreInstall(int status) {
13637            if (status != PackageManager.INSTALL_SUCCEEDED) {
13638                // Destroy container
13639                PackageHelper.destroySdDir(cid);
13640            } else {
13641                boolean mounted = PackageHelper.isContainerMounted(cid);
13642                if (!mounted) {
13643                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13644                            Process.SYSTEM_UID);
13645                    if (newMountPath != null) {
13646                        setMountPath(newMountPath);
13647                    } else {
13648                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13649                    }
13650                }
13651            }
13652            return status;
13653        }
13654
13655        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13656            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13657            String newMountPath = null;
13658            if (PackageHelper.isContainerMounted(cid)) {
13659                // Unmount the container
13660                if (!PackageHelper.unMountSdDir(cid)) {
13661                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13662                    return false;
13663                }
13664            }
13665            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13666                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13667                        " which might be stale. Will try to clean up.");
13668                // Clean up the stale container and proceed to recreate.
13669                if (!PackageHelper.destroySdDir(newCacheId)) {
13670                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13671                    return false;
13672                }
13673                // Successfully cleaned up stale container. Try to rename again.
13674                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13675                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13676                            + " inspite of cleaning it up.");
13677                    return false;
13678                }
13679            }
13680            if (!PackageHelper.isContainerMounted(newCacheId)) {
13681                Slog.w(TAG, "Mounting container " + newCacheId);
13682                newMountPath = PackageHelper.mountSdDir(newCacheId,
13683                        getEncryptKey(), Process.SYSTEM_UID);
13684            } else {
13685                newMountPath = PackageHelper.getSdDir(newCacheId);
13686            }
13687            if (newMountPath == null) {
13688                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13689                return false;
13690            }
13691            Log.i(TAG, "Succesfully renamed " + cid +
13692                    " to " + newCacheId +
13693                    " at new path: " + newMountPath);
13694            cid = newCacheId;
13695
13696            final File beforeCodeFile = new File(packagePath);
13697            setMountPath(newMountPath);
13698            final File afterCodeFile = new File(packagePath);
13699
13700            // Reflect the rename in scanned details
13701            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13702            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13703                    afterCodeFile, pkg.baseCodePath));
13704            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13705                    afterCodeFile, pkg.splitCodePaths));
13706
13707            // Reflect the rename in app info
13708            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13709            pkg.setApplicationInfoCodePath(pkg.codePath);
13710            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13711            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13712            pkg.setApplicationInfoResourcePath(pkg.codePath);
13713            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13714            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13715
13716            return true;
13717        }
13718
13719        private void setMountPath(String mountPath) {
13720            final File mountFile = new File(mountPath);
13721
13722            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13723            if (monolithicFile.exists()) {
13724                packagePath = monolithicFile.getAbsolutePath();
13725                if (isFwdLocked()) {
13726                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13727                } else {
13728                    resourcePath = packagePath;
13729                }
13730            } else {
13731                packagePath = mountFile.getAbsolutePath();
13732                resourcePath = packagePath;
13733            }
13734        }
13735
13736        int doPostInstall(int status, int uid) {
13737            if (status != PackageManager.INSTALL_SUCCEEDED) {
13738                cleanUp();
13739            } else {
13740                final int groupOwner;
13741                final String protectedFile;
13742                if (isFwdLocked()) {
13743                    groupOwner = UserHandle.getSharedAppGid(uid);
13744                    protectedFile = RES_FILE_NAME;
13745                } else {
13746                    groupOwner = -1;
13747                    protectedFile = null;
13748                }
13749
13750                if (uid < Process.FIRST_APPLICATION_UID
13751                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13752                    Slog.e(TAG, "Failed to finalize " + cid);
13753                    PackageHelper.destroySdDir(cid);
13754                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13755                }
13756
13757                boolean mounted = PackageHelper.isContainerMounted(cid);
13758                if (!mounted) {
13759                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13760                }
13761            }
13762            return status;
13763        }
13764
13765        private void cleanUp() {
13766            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13767
13768            // Destroy secure container
13769            PackageHelper.destroySdDir(cid);
13770        }
13771
13772        private List<String> getAllCodePaths() {
13773            final File codeFile = new File(getCodePath());
13774            if (codeFile != null && codeFile.exists()) {
13775                try {
13776                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13777                    return pkg.getAllCodePaths();
13778                } catch (PackageParserException e) {
13779                    // Ignored; we tried our best
13780                }
13781            }
13782            return Collections.EMPTY_LIST;
13783        }
13784
13785        void cleanUpResourcesLI() {
13786            // Enumerate all code paths before deleting
13787            cleanUpResourcesLI(getAllCodePaths());
13788        }
13789
13790        private void cleanUpResourcesLI(List<String> allCodePaths) {
13791            cleanUp();
13792            removeDexFiles(allCodePaths, instructionSets);
13793        }
13794
13795        String getPackageName() {
13796            return getAsecPackageName(cid);
13797        }
13798
13799        boolean doPostDeleteLI(boolean delete) {
13800            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13801            final List<String> allCodePaths = getAllCodePaths();
13802            boolean mounted = PackageHelper.isContainerMounted(cid);
13803            if (mounted) {
13804                // Unmount first
13805                if (PackageHelper.unMountSdDir(cid)) {
13806                    mounted = false;
13807                }
13808            }
13809            if (!mounted && delete) {
13810                cleanUpResourcesLI(allCodePaths);
13811            }
13812            return !mounted;
13813        }
13814
13815        @Override
13816        int doPreCopy() {
13817            if (isFwdLocked()) {
13818                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13819                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13820                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13821                }
13822            }
13823
13824            return PackageManager.INSTALL_SUCCEEDED;
13825        }
13826
13827        @Override
13828        int doPostCopy(int uid) {
13829            if (isFwdLocked()) {
13830                if (uid < Process.FIRST_APPLICATION_UID
13831                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13832                                RES_FILE_NAME)) {
13833                    Slog.e(TAG, "Failed to finalize " + cid);
13834                    PackageHelper.destroySdDir(cid);
13835                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13836                }
13837            }
13838
13839            return PackageManager.INSTALL_SUCCEEDED;
13840        }
13841    }
13842
13843    /**
13844     * Logic to handle movement of existing installed applications.
13845     */
13846    class MoveInstallArgs extends InstallArgs {
13847        private File codeFile;
13848        private File resourceFile;
13849
13850        /** New install */
13851        MoveInstallArgs(InstallParams params) {
13852            super(params.origin, params.move, params.observer, params.installFlags,
13853                    params.installerPackageName, params.volumeUuid,
13854                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13855                    params.grantedRuntimePermissions,
13856                    params.traceMethod, params.traceCookie, params.certificates);
13857        }
13858
13859        int copyApk(IMediaContainerService imcs, boolean temp) {
13860            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13861                    + move.fromUuid + " to " + move.toUuid);
13862            synchronized (mInstaller) {
13863                try {
13864                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13865                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13866                } catch (InstallerException e) {
13867                    Slog.w(TAG, "Failed to move app", e);
13868                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13869                }
13870            }
13871
13872            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13873            resourceFile = codeFile;
13874            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13875
13876            return PackageManager.INSTALL_SUCCEEDED;
13877        }
13878
13879        int doPreInstall(int status) {
13880            if (status != PackageManager.INSTALL_SUCCEEDED) {
13881                cleanUp(move.toUuid);
13882            }
13883            return status;
13884        }
13885
13886        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13887            if (status != PackageManager.INSTALL_SUCCEEDED) {
13888                cleanUp(move.toUuid);
13889                return false;
13890            }
13891
13892            // Reflect the move in app info
13893            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13894            pkg.setApplicationInfoCodePath(pkg.codePath);
13895            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13896            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13897            pkg.setApplicationInfoResourcePath(pkg.codePath);
13898            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13899            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13900
13901            return true;
13902        }
13903
13904        int doPostInstall(int status, int uid) {
13905            if (status == PackageManager.INSTALL_SUCCEEDED) {
13906                cleanUp(move.fromUuid);
13907            } else {
13908                cleanUp(move.toUuid);
13909            }
13910            return status;
13911        }
13912
13913        @Override
13914        String getCodePath() {
13915            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13916        }
13917
13918        @Override
13919        String getResourcePath() {
13920            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13921        }
13922
13923        private boolean cleanUp(String volumeUuid) {
13924            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13925                    move.dataAppName);
13926            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13927            final int[] userIds = sUserManager.getUserIds();
13928            synchronized (mInstallLock) {
13929                // Clean up both app data and code
13930                // All package moves are frozen until finished
13931                for (int userId : userIds) {
13932                    try {
13933                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13934                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13935                    } catch (InstallerException e) {
13936                        Slog.w(TAG, String.valueOf(e));
13937                    }
13938                }
13939                removeCodePathLI(codeFile);
13940            }
13941            return true;
13942        }
13943
13944        void cleanUpResourcesLI() {
13945            throw new UnsupportedOperationException();
13946        }
13947
13948        boolean doPostDeleteLI(boolean delete) {
13949            throw new UnsupportedOperationException();
13950        }
13951    }
13952
13953    static String getAsecPackageName(String packageCid) {
13954        int idx = packageCid.lastIndexOf("-");
13955        if (idx == -1) {
13956            return packageCid;
13957        }
13958        return packageCid.substring(0, idx);
13959    }
13960
13961    // Utility method used to create code paths based on package name and available index.
13962    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13963        String idxStr = "";
13964        int idx = 1;
13965        // Fall back to default value of idx=1 if prefix is not
13966        // part of oldCodePath
13967        if (oldCodePath != null) {
13968            String subStr = oldCodePath;
13969            // Drop the suffix right away
13970            if (suffix != null && subStr.endsWith(suffix)) {
13971                subStr = subStr.substring(0, subStr.length() - suffix.length());
13972            }
13973            // If oldCodePath already contains prefix find out the
13974            // ending index to either increment or decrement.
13975            int sidx = subStr.lastIndexOf(prefix);
13976            if (sidx != -1) {
13977                subStr = subStr.substring(sidx + prefix.length());
13978                if (subStr != null) {
13979                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13980                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13981                    }
13982                    try {
13983                        idx = Integer.parseInt(subStr);
13984                        if (idx <= 1) {
13985                            idx++;
13986                        } else {
13987                            idx--;
13988                        }
13989                    } catch(NumberFormatException e) {
13990                    }
13991                }
13992            }
13993        }
13994        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13995        return prefix + idxStr;
13996    }
13997
13998    private File getNextCodePath(File targetDir, String packageName) {
13999        int suffix = 1;
14000        File result;
14001        do {
14002            result = new File(targetDir, packageName + "-" + suffix);
14003            suffix++;
14004        } while (result.exists());
14005        return result;
14006    }
14007
14008    // Utility method that returns the relative package path with respect
14009    // to the installation directory. Like say for /data/data/com.test-1.apk
14010    // string com.test-1 is returned.
14011    static String deriveCodePathName(String codePath) {
14012        if (codePath == null) {
14013            return null;
14014        }
14015        final File codeFile = new File(codePath);
14016        final String name = codeFile.getName();
14017        if (codeFile.isDirectory()) {
14018            return name;
14019        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14020            final int lastDot = name.lastIndexOf('.');
14021            return name.substring(0, lastDot);
14022        } else {
14023            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14024            return null;
14025        }
14026    }
14027
14028    static class PackageInstalledInfo {
14029        String name;
14030        int uid;
14031        // The set of users that originally had this package installed.
14032        int[] origUsers;
14033        // The set of users that now have this package installed.
14034        int[] newUsers;
14035        PackageParser.Package pkg;
14036        int returnCode;
14037        String returnMsg;
14038        PackageRemovedInfo removedInfo;
14039        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14040
14041        public void setError(int code, String msg) {
14042            setReturnCode(code);
14043            setReturnMessage(msg);
14044            Slog.w(TAG, msg);
14045        }
14046
14047        public void setError(String msg, PackageParserException e) {
14048            setReturnCode(e.error);
14049            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14050            Slog.w(TAG, msg, e);
14051        }
14052
14053        public void setError(String msg, PackageManagerException e) {
14054            returnCode = e.error;
14055            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14056            Slog.w(TAG, msg, e);
14057        }
14058
14059        public void setReturnCode(int returnCode) {
14060            this.returnCode = returnCode;
14061            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14062            for (int i = 0; i < childCount; i++) {
14063                addedChildPackages.valueAt(i).returnCode = returnCode;
14064            }
14065        }
14066
14067        private void setReturnMessage(String returnMsg) {
14068            this.returnMsg = returnMsg;
14069            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14070            for (int i = 0; i < childCount; i++) {
14071                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14072            }
14073        }
14074
14075        // In some error cases we want to convey more info back to the observer
14076        String origPackage;
14077        String origPermission;
14078    }
14079
14080    /*
14081     * Install a non-existing package.
14082     */
14083    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14084            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14085            PackageInstalledInfo res) {
14086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14087
14088        // Remember this for later, in case we need to rollback this install
14089        String pkgName = pkg.packageName;
14090
14091        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14092
14093        synchronized(mPackages) {
14094            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14095                // A package with the same name is already installed, though
14096                // it has been renamed to an older name.  The package we
14097                // are trying to install should be installed as an update to
14098                // the existing one, but that has not been requested, so bail.
14099                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14100                        + " without first uninstalling package running as "
14101                        + mSettings.mRenamedPackages.get(pkgName));
14102                return;
14103            }
14104            if (mPackages.containsKey(pkgName)) {
14105                // Don't allow installation over an existing package with the same name.
14106                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14107                        + " without first uninstalling.");
14108                return;
14109            }
14110        }
14111
14112        try {
14113            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14114                    System.currentTimeMillis(), user);
14115
14116            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14117
14118            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14119                prepareAppDataAfterInstallLIF(newPackage);
14120
14121            } else {
14122                // Remove package from internal structures, but keep around any
14123                // data that might have already existed
14124                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14125                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14126            }
14127        } catch (PackageManagerException e) {
14128            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14129        }
14130
14131        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14132    }
14133
14134    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14135        // Can't rotate keys during boot or if sharedUser.
14136        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14137                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14138            return false;
14139        }
14140        // app is using upgradeKeySets; make sure all are valid
14141        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14142        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14143        for (int i = 0; i < upgradeKeySets.length; i++) {
14144            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14145                Slog.wtf(TAG, "Package "
14146                         + (oldPs.name != null ? oldPs.name : "<null>")
14147                         + " contains upgrade-key-set reference to unknown key-set: "
14148                         + upgradeKeySets[i]
14149                         + " reverting to signatures check.");
14150                return false;
14151            }
14152        }
14153        return true;
14154    }
14155
14156    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14157        // Upgrade keysets are being used.  Determine if new package has a superset of the
14158        // required keys.
14159        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14160        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14161        for (int i = 0; i < upgradeKeySets.length; i++) {
14162            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14163            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14164                return true;
14165            }
14166        }
14167        return false;
14168    }
14169
14170    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14171        try (DigestInputStream digestStream =
14172                new DigestInputStream(new FileInputStream(file), digest)) {
14173            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14174        }
14175    }
14176
14177    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14178            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14179        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14180
14181        final PackageParser.Package oldPackage;
14182        final String pkgName = pkg.packageName;
14183        final int[] allUsers;
14184        final int[] installedUsers;
14185
14186        synchronized(mPackages) {
14187            oldPackage = mPackages.get(pkgName);
14188            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14189
14190            // don't allow upgrade to target a release SDK from a pre-release SDK
14191            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14192                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14193            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14194                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14195            if (oldTargetsPreRelease
14196                    && !newTargetsPreRelease
14197                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14198                Slog.w(TAG, "Can't install package targeting released sdk");
14199                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14200                return;
14201            }
14202
14203            // don't allow an upgrade from full to ephemeral
14204            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14205            if (isEphemeral && !oldIsEphemeral) {
14206                // can't downgrade from full to ephemeral
14207                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14208                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14209                return;
14210            }
14211
14212            // verify signatures are valid
14213            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14214            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14215                if (!checkUpgradeKeySetLP(ps, pkg)) {
14216                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14217                            "New package not signed by keys specified by upgrade-keysets: "
14218                                    + pkgName);
14219                    return;
14220                }
14221            } else {
14222                // default to original signature matching
14223                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14224                        != PackageManager.SIGNATURE_MATCH) {
14225                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14226                            "New package has a different signature: " + pkgName);
14227                    return;
14228                }
14229            }
14230
14231            // don't allow a system upgrade unless the upgrade hash matches
14232            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14233                byte[] digestBytes = null;
14234                try {
14235                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14236                    updateDigest(digest, new File(pkg.baseCodePath));
14237                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14238                        for (String path : pkg.splitCodePaths) {
14239                            updateDigest(digest, new File(path));
14240                        }
14241                    }
14242                    digestBytes = digest.digest();
14243                } catch (NoSuchAlgorithmException | IOException e) {
14244                    res.setError(INSTALL_FAILED_INVALID_APK,
14245                            "Could not compute hash: " + pkgName);
14246                    return;
14247                }
14248                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14249                    res.setError(INSTALL_FAILED_INVALID_APK,
14250                            "New package fails restrict-update check: " + pkgName);
14251                    return;
14252                }
14253                // retain upgrade restriction
14254                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14255            }
14256
14257            // Check for shared user id changes
14258            String invalidPackageName =
14259                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14260            if (invalidPackageName != null) {
14261                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14262                        "Package " + invalidPackageName + " tried to change user "
14263                                + oldPackage.mSharedUserId);
14264                return;
14265            }
14266
14267            // In case of rollback, remember per-user/profile install state
14268            allUsers = sUserManager.getUserIds();
14269            installedUsers = ps.queryInstalledUsers(allUsers, true);
14270        }
14271
14272        // Update what is removed
14273        res.removedInfo = new PackageRemovedInfo();
14274        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14275        res.removedInfo.removedPackage = oldPackage.packageName;
14276        res.removedInfo.isUpdate = true;
14277        res.removedInfo.origUsers = installedUsers;
14278        final int childCount = (oldPackage.childPackages != null)
14279                ? oldPackage.childPackages.size() : 0;
14280        for (int i = 0; i < childCount; i++) {
14281            boolean childPackageUpdated = false;
14282            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14283            if (res.addedChildPackages != null) {
14284                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14285                if (childRes != null) {
14286                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14287                    childRes.removedInfo.removedPackage = childPkg.packageName;
14288                    childRes.removedInfo.isUpdate = true;
14289                    childPackageUpdated = true;
14290                }
14291            }
14292            if (!childPackageUpdated) {
14293                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14294                childRemovedRes.removedPackage = childPkg.packageName;
14295                childRemovedRes.isUpdate = false;
14296                childRemovedRes.dataRemoved = true;
14297                synchronized (mPackages) {
14298                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14299                    if (childPs != null) {
14300                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14301                    }
14302                }
14303                if (res.removedInfo.removedChildPackages == null) {
14304                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14305                }
14306                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14307            }
14308        }
14309
14310        boolean sysPkg = (isSystemApp(oldPackage));
14311        if (sysPkg) {
14312            // Set the system/privileged flags as needed
14313            final boolean privileged =
14314                    (oldPackage.applicationInfo.privateFlags
14315                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14316            final int systemPolicyFlags = policyFlags
14317                    | PackageParser.PARSE_IS_SYSTEM
14318                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14319
14320            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14321                    user, allUsers, installerPackageName, res);
14322        } else {
14323            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14324                    user, allUsers, installerPackageName, res);
14325        }
14326    }
14327
14328    public List<String> getPreviousCodePaths(String packageName) {
14329        final PackageSetting ps = mSettings.mPackages.get(packageName);
14330        final List<String> result = new ArrayList<String>();
14331        if (ps != null && ps.oldCodePaths != null) {
14332            result.addAll(ps.oldCodePaths);
14333        }
14334        return result;
14335    }
14336
14337    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14338            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14339            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14340        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14341                + deletedPackage);
14342
14343        String pkgName = deletedPackage.packageName;
14344        boolean deletedPkg = true;
14345        boolean addedPkg = false;
14346        boolean updatedSettings = false;
14347        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14348        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14349                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14350
14351        final long origUpdateTime = (pkg.mExtras != null)
14352                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14353
14354        // First delete the existing package while retaining the data directory
14355        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14356                res.removedInfo, true, pkg)) {
14357            // If the existing package wasn't successfully deleted
14358            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14359            deletedPkg = false;
14360        } else {
14361            // Successfully deleted the old package; proceed with replace.
14362
14363            // If deleted package lived in a container, give users a chance to
14364            // relinquish resources before killing.
14365            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14366                if (DEBUG_INSTALL) {
14367                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14368                }
14369                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14370                final ArrayList<String> pkgList = new ArrayList<String>(1);
14371                pkgList.add(deletedPackage.applicationInfo.packageName);
14372                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14373            }
14374
14375            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14376                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14377            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14378
14379            try {
14380                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14381                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14382                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14383
14384                // Update the in-memory copy of the previous code paths.
14385                PackageSetting ps = mSettings.mPackages.get(pkgName);
14386                if (!killApp) {
14387                    if (ps.oldCodePaths == null) {
14388                        ps.oldCodePaths = new ArraySet<>();
14389                    }
14390                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14391                    if (deletedPackage.splitCodePaths != null) {
14392                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14393                    }
14394                } else {
14395                    ps.oldCodePaths = null;
14396                }
14397                if (ps.childPackageNames != null) {
14398                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14399                        final String childPkgName = ps.childPackageNames.get(i);
14400                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14401                        childPs.oldCodePaths = ps.oldCodePaths;
14402                    }
14403                }
14404                prepareAppDataAfterInstallLIF(newPackage);
14405                addedPkg = true;
14406            } catch (PackageManagerException e) {
14407                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14408            }
14409        }
14410
14411        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14412            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14413
14414            // Revert all internal state mutations and added folders for the failed install
14415            if (addedPkg) {
14416                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14417                        res.removedInfo, true, null);
14418            }
14419
14420            // Restore the old package
14421            if (deletedPkg) {
14422                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14423                File restoreFile = new File(deletedPackage.codePath);
14424                // Parse old package
14425                boolean oldExternal = isExternal(deletedPackage);
14426                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14427                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14428                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14429                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14430                try {
14431                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14432                            null);
14433                } catch (PackageManagerException e) {
14434                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14435                            + e.getMessage());
14436                    return;
14437                }
14438
14439                synchronized (mPackages) {
14440                    // Ensure the installer package name up to date
14441                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14442
14443                    // Update permissions for restored package
14444                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14445
14446                    mSettings.writeLPr();
14447                }
14448
14449                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14450            }
14451        } else {
14452            synchronized (mPackages) {
14453                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14454                if (ps != null) {
14455                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14456                    if (res.removedInfo.removedChildPackages != null) {
14457                        final int childCount = res.removedInfo.removedChildPackages.size();
14458                        // Iterate in reverse as we may modify the collection
14459                        for (int i = childCount - 1; i >= 0; i--) {
14460                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14461                            if (res.addedChildPackages.containsKey(childPackageName)) {
14462                                res.removedInfo.removedChildPackages.removeAt(i);
14463                            } else {
14464                                PackageRemovedInfo childInfo = res.removedInfo
14465                                        .removedChildPackages.valueAt(i);
14466                                childInfo.removedForAllUsers = mPackages.get(
14467                                        childInfo.removedPackage) == null;
14468                            }
14469                        }
14470                    }
14471                }
14472            }
14473        }
14474    }
14475
14476    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14477            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14478            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14479        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14480                + ", old=" + deletedPackage);
14481
14482        final boolean disabledSystem;
14483
14484        // Remove existing system package
14485        removePackageLI(deletedPackage, true);
14486
14487        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14488        if (!disabledSystem) {
14489            // We didn't need to disable the .apk as a current system package,
14490            // which means we are replacing another update that is already
14491            // installed.  We need to make sure to delete the older one's .apk.
14492            res.removedInfo.args = createInstallArgsForExisting(0,
14493                    deletedPackage.applicationInfo.getCodePath(),
14494                    deletedPackage.applicationInfo.getResourcePath(),
14495                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14496        } else {
14497            res.removedInfo.args = null;
14498        }
14499
14500        // Successfully disabled the old package. Now proceed with re-installation
14501        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14502                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14503        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14504
14505        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14506        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14507                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14508
14509        PackageParser.Package newPackage = null;
14510        try {
14511            // Add the package to the internal data structures
14512            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14513
14514            // Set the update and install times
14515            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14516            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14517                    System.currentTimeMillis());
14518
14519            // Update the package dynamic state if succeeded
14520            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14521                // Now that the install succeeded make sure we remove data
14522                // directories for any child package the update removed.
14523                final int deletedChildCount = (deletedPackage.childPackages != null)
14524                        ? deletedPackage.childPackages.size() : 0;
14525                final int newChildCount = (newPackage.childPackages != null)
14526                        ? newPackage.childPackages.size() : 0;
14527                for (int i = 0; i < deletedChildCount; i++) {
14528                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14529                    boolean childPackageDeleted = true;
14530                    for (int j = 0; j < newChildCount; j++) {
14531                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14532                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14533                            childPackageDeleted = false;
14534                            break;
14535                        }
14536                    }
14537                    if (childPackageDeleted) {
14538                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14539                                deletedChildPkg.packageName);
14540                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14541                            PackageRemovedInfo removedChildRes = res.removedInfo
14542                                    .removedChildPackages.get(deletedChildPkg.packageName);
14543                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14544                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14545                        }
14546                    }
14547                }
14548
14549                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14550                prepareAppDataAfterInstallLIF(newPackage);
14551            }
14552        } catch (PackageManagerException e) {
14553            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14554            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14555        }
14556
14557        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14558            // Re installation failed. Restore old information
14559            // Remove new pkg information
14560            if (newPackage != null) {
14561                removeInstalledPackageLI(newPackage, true);
14562            }
14563            // Add back the old system package
14564            try {
14565                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14566            } catch (PackageManagerException e) {
14567                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14568            }
14569
14570            synchronized (mPackages) {
14571                if (disabledSystem) {
14572                    enableSystemPackageLPw(deletedPackage);
14573                }
14574
14575                // Ensure the installer package name up to date
14576                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14577
14578                // Update permissions for restored package
14579                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14580
14581                mSettings.writeLPr();
14582            }
14583
14584            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14585                    + " after failed upgrade");
14586        }
14587    }
14588
14589    /**
14590     * Checks whether the parent or any of the child packages have a change shared
14591     * user. For a package to be a valid update the shred users of the parent and
14592     * the children should match. We may later support changing child shared users.
14593     * @param oldPkg The updated package.
14594     * @param newPkg The update package.
14595     * @return The shared user that change between the versions.
14596     */
14597    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14598            PackageParser.Package newPkg) {
14599        // Check parent shared user
14600        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14601            return newPkg.packageName;
14602        }
14603        // Check child shared users
14604        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14605        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14606        for (int i = 0; i < newChildCount; i++) {
14607            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14608            // If this child was present, did it have the same shared user?
14609            for (int j = 0; j < oldChildCount; j++) {
14610                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14611                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14612                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14613                    return newChildPkg.packageName;
14614                }
14615            }
14616        }
14617        return null;
14618    }
14619
14620    private void removeNativeBinariesLI(PackageSetting ps) {
14621        // Remove the lib path for the parent package
14622        if (ps != null) {
14623            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14624            // Remove the lib path for the child packages
14625            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14626            for (int i = 0; i < childCount; i++) {
14627                PackageSetting childPs = null;
14628                synchronized (mPackages) {
14629                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14630                }
14631                if (childPs != null) {
14632                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14633                            .legacyNativeLibraryPathString);
14634                }
14635            }
14636        }
14637    }
14638
14639    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14640        // Enable the parent package
14641        mSettings.enableSystemPackageLPw(pkg.packageName);
14642        // Enable the child packages
14643        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14644        for (int i = 0; i < childCount; i++) {
14645            PackageParser.Package childPkg = pkg.childPackages.get(i);
14646            mSettings.enableSystemPackageLPw(childPkg.packageName);
14647        }
14648    }
14649
14650    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14651            PackageParser.Package newPkg) {
14652        // Disable the parent package (parent always replaced)
14653        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14654        // Disable the child packages
14655        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14656        for (int i = 0; i < childCount; i++) {
14657            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14658            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14659            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14660        }
14661        return disabled;
14662    }
14663
14664    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14665            String installerPackageName) {
14666        // Enable the parent package
14667        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14668        // Enable the child packages
14669        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14670        for (int i = 0; i < childCount; i++) {
14671            PackageParser.Package childPkg = pkg.childPackages.get(i);
14672            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14673        }
14674    }
14675
14676    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14677        // Collect all used permissions in the UID
14678        ArraySet<String> usedPermissions = new ArraySet<>();
14679        final int packageCount = su.packages.size();
14680        for (int i = 0; i < packageCount; i++) {
14681            PackageSetting ps = su.packages.valueAt(i);
14682            if (ps.pkg == null) {
14683                continue;
14684            }
14685            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14686            for (int j = 0; j < requestedPermCount; j++) {
14687                String permission = ps.pkg.requestedPermissions.get(j);
14688                BasePermission bp = mSettings.mPermissions.get(permission);
14689                if (bp != null) {
14690                    usedPermissions.add(permission);
14691                }
14692            }
14693        }
14694
14695        PermissionsState permissionsState = su.getPermissionsState();
14696        // Prune install permissions
14697        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14698        final int installPermCount = installPermStates.size();
14699        for (int i = installPermCount - 1; i >= 0;  i--) {
14700            PermissionState permissionState = installPermStates.get(i);
14701            if (!usedPermissions.contains(permissionState.getName())) {
14702                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14703                if (bp != null) {
14704                    permissionsState.revokeInstallPermission(bp);
14705                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14706                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14707                }
14708            }
14709        }
14710
14711        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14712
14713        // Prune runtime permissions
14714        for (int userId : allUserIds) {
14715            List<PermissionState> runtimePermStates = permissionsState
14716                    .getRuntimePermissionStates(userId);
14717            final int runtimePermCount = runtimePermStates.size();
14718            for (int i = runtimePermCount - 1; i >= 0; i--) {
14719                PermissionState permissionState = runtimePermStates.get(i);
14720                if (!usedPermissions.contains(permissionState.getName())) {
14721                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14722                    if (bp != null) {
14723                        permissionsState.revokeRuntimePermission(bp, userId);
14724                        permissionsState.updatePermissionFlags(bp, userId,
14725                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14726                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14727                                runtimePermissionChangedUserIds, userId);
14728                    }
14729                }
14730            }
14731        }
14732
14733        return runtimePermissionChangedUserIds;
14734    }
14735
14736    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14737            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14738        // Update the parent package setting
14739        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14740                res, user);
14741        // Update the child packages setting
14742        final int childCount = (newPackage.childPackages != null)
14743                ? newPackage.childPackages.size() : 0;
14744        for (int i = 0; i < childCount; i++) {
14745            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14746            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14747            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14748                    childRes.origUsers, childRes, user);
14749        }
14750    }
14751
14752    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14753            String installerPackageName, int[] allUsers, int[] installedForUsers,
14754            PackageInstalledInfo res, UserHandle user) {
14755        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14756
14757        String pkgName = newPackage.packageName;
14758        synchronized (mPackages) {
14759            //write settings. the installStatus will be incomplete at this stage.
14760            //note that the new package setting would have already been
14761            //added to mPackages. It hasn't been persisted yet.
14762            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14763            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14764            mSettings.writeLPr();
14765            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14766        }
14767
14768        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14769        synchronized (mPackages) {
14770            updatePermissionsLPw(newPackage.packageName, newPackage,
14771                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14772                            ? UPDATE_PERMISSIONS_ALL : 0));
14773            // For system-bundled packages, we assume that installing an upgraded version
14774            // of the package implies that the user actually wants to run that new code,
14775            // so we enable the package.
14776            PackageSetting ps = mSettings.mPackages.get(pkgName);
14777            final int userId = user.getIdentifier();
14778            if (ps != null) {
14779                if (isSystemApp(newPackage)) {
14780                    if (DEBUG_INSTALL) {
14781                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14782                    }
14783                    // Enable system package for requested users
14784                    if (res.origUsers != null) {
14785                        for (int origUserId : res.origUsers) {
14786                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14787                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14788                                        origUserId, installerPackageName);
14789                            }
14790                        }
14791                    }
14792                    // Also convey the prior install/uninstall state
14793                    if (allUsers != null && installedForUsers != null) {
14794                        for (int currentUserId : allUsers) {
14795                            final boolean installed = ArrayUtils.contains(
14796                                    installedForUsers, currentUserId);
14797                            if (DEBUG_INSTALL) {
14798                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14799                            }
14800                            ps.setInstalled(installed, currentUserId);
14801                        }
14802                        // these install state changes will be persisted in the
14803                        // upcoming call to mSettings.writeLPr().
14804                    }
14805                }
14806                // It's implied that when a user requests installation, they want the app to be
14807                // installed and enabled.
14808                if (userId != UserHandle.USER_ALL) {
14809                    ps.setInstalled(true, userId);
14810                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14811                }
14812            }
14813            res.name = pkgName;
14814            res.uid = newPackage.applicationInfo.uid;
14815            res.pkg = newPackage;
14816            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14817            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14818            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14819            //to update install status
14820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14821            mSettings.writeLPr();
14822            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14823        }
14824
14825        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14826    }
14827
14828    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14829        try {
14830            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14831            installPackageLI(args, res);
14832        } finally {
14833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14834        }
14835    }
14836
14837    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14838        final int installFlags = args.installFlags;
14839        final String installerPackageName = args.installerPackageName;
14840        final String volumeUuid = args.volumeUuid;
14841        final File tmpPackageFile = new File(args.getCodePath());
14842        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14843        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14844                || (args.volumeUuid != null));
14845        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14846        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14847        boolean replace = false;
14848        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14849        if (args.move != null) {
14850            // moving a complete application; perform an initial scan on the new install location
14851            scanFlags |= SCAN_INITIAL;
14852        }
14853        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14854            scanFlags |= SCAN_DONT_KILL_APP;
14855        }
14856
14857        // Result object to be returned
14858        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14859
14860        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14861
14862        // Sanity check
14863        if (ephemeral && (forwardLocked || onExternal)) {
14864            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14865                    + " external=" + onExternal);
14866            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14867            return;
14868        }
14869
14870        // Retrieve PackageSettings and parse package
14871        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14872                | PackageParser.PARSE_ENFORCE_CODE
14873                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14874                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14875                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14876                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14877        PackageParser pp = new PackageParser();
14878        pp.setSeparateProcesses(mSeparateProcesses);
14879        pp.setDisplayMetrics(mMetrics);
14880
14881        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14882        final PackageParser.Package pkg;
14883        try {
14884            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14885        } catch (PackageParserException e) {
14886            res.setError("Failed parse during installPackageLI", e);
14887            return;
14888        } finally {
14889            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14890        }
14891
14892        // If we are installing a clustered package add results for the children
14893        if (pkg.childPackages != null) {
14894            synchronized (mPackages) {
14895                final int childCount = pkg.childPackages.size();
14896                for (int i = 0; i < childCount; i++) {
14897                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14898                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14899                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14900                    childRes.pkg = childPkg;
14901                    childRes.name = childPkg.packageName;
14902                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14903                    if (childPs != null) {
14904                        childRes.origUsers = childPs.queryInstalledUsers(
14905                                sUserManager.getUserIds(), true);
14906                    }
14907                    if ((mPackages.containsKey(childPkg.packageName))) {
14908                        childRes.removedInfo = new PackageRemovedInfo();
14909                        childRes.removedInfo.removedPackage = childPkg.packageName;
14910                    }
14911                    if (res.addedChildPackages == null) {
14912                        res.addedChildPackages = new ArrayMap<>();
14913                    }
14914                    res.addedChildPackages.put(childPkg.packageName, childRes);
14915                }
14916            }
14917        }
14918
14919        // If package doesn't declare API override, mark that we have an install
14920        // time CPU ABI override.
14921        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14922            pkg.cpuAbiOverride = args.abiOverride;
14923        }
14924
14925        String pkgName = res.name = pkg.packageName;
14926        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14927            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14928                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14929                return;
14930            }
14931        }
14932
14933        try {
14934            // either use what we've been given or parse directly from the APK
14935            if (args.certificates != null) {
14936                try {
14937                    PackageParser.populateCertificates(pkg, args.certificates);
14938                } catch (PackageParserException e) {
14939                    // there was something wrong with the certificates we were given;
14940                    // try to pull them from the APK
14941                    PackageParser.collectCertificates(pkg, parseFlags);
14942                }
14943            } else {
14944                PackageParser.collectCertificates(pkg, parseFlags);
14945            }
14946        } catch (PackageParserException e) {
14947            res.setError("Failed collect during installPackageLI", e);
14948            return;
14949        }
14950
14951        // Get rid of all references to package scan path via parser.
14952        pp = null;
14953        String oldCodePath = null;
14954        boolean systemApp = false;
14955        synchronized (mPackages) {
14956            // Check if installing already existing package
14957            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14958                String oldName = mSettings.mRenamedPackages.get(pkgName);
14959                if (pkg.mOriginalPackages != null
14960                        && pkg.mOriginalPackages.contains(oldName)
14961                        && mPackages.containsKey(oldName)) {
14962                    // This package is derived from an original package,
14963                    // and this device has been updating from that original
14964                    // name.  We must continue using the original name, so
14965                    // rename the new package here.
14966                    pkg.setPackageName(oldName);
14967                    pkgName = pkg.packageName;
14968                    replace = true;
14969                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14970                            + oldName + " pkgName=" + pkgName);
14971                } else if (mPackages.containsKey(pkgName)) {
14972                    // This package, under its official name, already exists
14973                    // on the device; we should replace it.
14974                    replace = true;
14975                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14976                }
14977
14978                // Child packages are installed through the parent package
14979                if (pkg.parentPackage != null) {
14980                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14981                            "Package " + pkg.packageName + " is child of package "
14982                                    + pkg.parentPackage.parentPackage + ". Child packages "
14983                                    + "can be updated only through the parent package.");
14984                    return;
14985                }
14986
14987                if (replace) {
14988                    // Prevent apps opting out from runtime permissions
14989                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14990                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14991                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14992                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14993                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14994                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14995                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14996                                        + " doesn't support runtime permissions but the old"
14997                                        + " target SDK " + oldTargetSdk + " does.");
14998                        return;
14999                    }
15000
15001                    // Prevent installing of child packages
15002                    if (oldPackage.parentPackage != null) {
15003                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15004                                "Package " + pkg.packageName + " is child of package "
15005                                        + oldPackage.parentPackage + ". Child packages "
15006                                        + "can be updated only through the parent package.");
15007                        return;
15008                    }
15009                }
15010            }
15011
15012            PackageSetting ps = mSettings.mPackages.get(pkgName);
15013            if (ps != null) {
15014                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15015
15016                // Quick sanity check that we're signed correctly if updating;
15017                // we'll check this again later when scanning, but we want to
15018                // bail early here before tripping over redefined permissions.
15019                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15020                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15021                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15022                                + pkg.packageName + " upgrade keys do not match the "
15023                                + "previously installed version");
15024                        return;
15025                    }
15026                } else {
15027                    try {
15028                        verifySignaturesLP(ps, pkg);
15029                    } catch (PackageManagerException e) {
15030                        res.setError(e.error, e.getMessage());
15031                        return;
15032                    }
15033                }
15034
15035                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15036                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15037                    systemApp = (ps.pkg.applicationInfo.flags &
15038                            ApplicationInfo.FLAG_SYSTEM) != 0;
15039                }
15040                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15041            }
15042
15043            // Check whether the newly-scanned package wants to define an already-defined perm
15044            int N = pkg.permissions.size();
15045            for (int i = N-1; i >= 0; i--) {
15046                PackageParser.Permission perm = pkg.permissions.get(i);
15047                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15048                if (bp != null) {
15049                    // If the defining package is signed with our cert, it's okay.  This
15050                    // also includes the "updating the same package" case, of course.
15051                    // "updating same package" could also involve key-rotation.
15052                    final boolean sigsOk;
15053                    if (bp.sourcePackage.equals(pkg.packageName)
15054                            && (bp.packageSetting instanceof PackageSetting)
15055                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15056                                    scanFlags))) {
15057                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15058                    } else {
15059                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15060                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15061                    }
15062                    if (!sigsOk) {
15063                        // If the owning package is the system itself, we log but allow
15064                        // install to proceed; we fail the install on all other permission
15065                        // redefinitions.
15066                        if (!bp.sourcePackage.equals("android")) {
15067                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15068                                    + pkg.packageName + " attempting to redeclare permission "
15069                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15070                            res.origPermission = perm.info.name;
15071                            res.origPackage = bp.sourcePackage;
15072                            return;
15073                        } else {
15074                            Slog.w(TAG, "Package " + pkg.packageName
15075                                    + " attempting to redeclare system permission "
15076                                    + perm.info.name + "; ignoring new declaration");
15077                            pkg.permissions.remove(i);
15078                        }
15079                    }
15080                }
15081            }
15082        }
15083
15084        if (systemApp) {
15085            if (onExternal) {
15086                // Abort update; system app can't be replaced with app on sdcard
15087                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15088                        "Cannot install updates to system apps on sdcard");
15089                return;
15090            } else if (ephemeral) {
15091                // Abort update; system app can't be replaced with an ephemeral app
15092                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15093                        "Cannot update a system app with an ephemeral app");
15094                return;
15095            }
15096        }
15097
15098        if (args.move != null) {
15099            // We did an in-place move, so dex is ready to roll
15100            scanFlags |= SCAN_NO_DEX;
15101            scanFlags |= SCAN_MOVE;
15102
15103            synchronized (mPackages) {
15104                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15105                if (ps == null) {
15106                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15107                            "Missing settings for moved package " + pkgName);
15108                }
15109
15110                // We moved the entire application as-is, so bring over the
15111                // previously derived ABI information.
15112                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15113                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15114            }
15115
15116        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15117            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15118            scanFlags |= SCAN_NO_DEX;
15119
15120            try {
15121                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15122                    args.abiOverride : pkg.cpuAbiOverride);
15123                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15124                        true /* extract libs */);
15125            } catch (PackageManagerException pme) {
15126                Slog.e(TAG, "Error deriving application ABI", pme);
15127                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15128                return;
15129            }
15130
15131            // Shared libraries for the package need to be updated.
15132            synchronized (mPackages) {
15133                try {
15134                    updateSharedLibrariesLPw(pkg, null);
15135                } catch (PackageManagerException e) {
15136                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15137                }
15138            }
15139            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15140            // Do not run PackageDexOptimizer through the local performDexOpt
15141            // method because `pkg` is not in `mPackages` yet.
15142            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15143                    null /* instructionSets */, false /* checkProfiles */,
15144                    getCompilerFilterForReason(REASON_INSTALL));
15145            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15146            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
15147                String msg = "Extracting package failed for " + pkgName;
15148                res.setError(INSTALL_FAILED_DEXOPT, msg);
15149                return;
15150            }
15151
15152            // Notify BackgroundDexOptService that the package has been changed.
15153            // If this is an update of a package which used to fail to compile,
15154            // BDOS will remove it from its blacklist.
15155            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15156        }
15157
15158        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15159            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15160            return;
15161        }
15162
15163        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15164
15165        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15166                "installPackageLI")) {
15167            if (replace) {
15168                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15169                        installerPackageName, res);
15170            } else {
15171                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15172                        args.user, installerPackageName, volumeUuid, res);
15173            }
15174        }
15175        synchronized (mPackages) {
15176            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15177            if (ps != null) {
15178                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15179            }
15180
15181            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15182            for (int i = 0; i < childCount; i++) {
15183                PackageParser.Package childPkg = pkg.childPackages.get(i);
15184                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15185                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15186                if (childPs != null) {
15187                    childRes.newUsers = childPs.queryInstalledUsers(
15188                            sUserManager.getUserIds(), true);
15189                }
15190            }
15191        }
15192    }
15193
15194    private void startIntentFilterVerifications(int userId, boolean replacing,
15195            PackageParser.Package pkg) {
15196        if (mIntentFilterVerifierComponent == null) {
15197            Slog.w(TAG, "No IntentFilter verification will not be done as "
15198                    + "there is no IntentFilterVerifier available!");
15199            return;
15200        }
15201
15202        final int verifierUid = getPackageUid(
15203                mIntentFilterVerifierComponent.getPackageName(),
15204                MATCH_DEBUG_TRIAGED_MISSING,
15205                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15206
15207        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15208        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15209        mHandler.sendMessage(msg);
15210
15211        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15212        for (int i = 0; i < childCount; i++) {
15213            PackageParser.Package childPkg = pkg.childPackages.get(i);
15214            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15215            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15216            mHandler.sendMessage(msg);
15217        }
15218    }
15219
15220    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15221            PackageParser.Package pkg) {
15222        int size = pkg.activities.size();
15223        if (size == 0) {
15224            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15225                    "No activity, so no need to verify any IntentFilter!");
15226            return;
15227        }
15228
15229        final boolean hasDomainURLs = hasDomainURLs(pkg);
15230        if (!hasDomainURLs) {
15231            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15232                    "No domain URLs, so no need to verify any IntentFilter!");
15233            return;
15234        }
15235
15236        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15237                + " if any IntentFilter from the " + size
15238                + " Activities needs verification ...");
15239
15240        int count = 0;
15241        final String packageName = pkg.packageName;
15242
15243        synchronized (mPackages) {
15244            // If this is a new install and we see that we've already run verification for this
15245            // package, we have nothing to do: it means the state was restored from backup.
15246            if (!replacing) {
15247                IntentFilterVerificationInfo ivi =
15248                        mSettings.getIntentFilterVerificationLPr(packageName);
15249                if (ivi != null) {
15250                    if (DEBUG_DOMAIN_VERIFICATION) {
15251                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15252                                + ivi.getStatusString());
15253                    }
15254                    return;
15255                }
15256            }
15257
15258            // If any filters need to be verified, then all need to be.
15259            boolean needToVerify = false;
15260            for (PackageParser.Activity a : pkg.activities) {
15261                for (ActivityIntentInfo filter : a.intents) {
15262                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15263                        if (DEBUG_DOMAIN_VERIFICATION) {
15264                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15265                        }
15266                        needToVerify = true;
15267                        break;
15268                    }
15269                }
15270            }
15271
15272            if (needToVerify) {
15273                final int verificationId = mIntentFilterVerificationToken++;
15274                for (PackageParser.Activity a : pkg.activities) {
15275                    for (ActivityIntentInfo filter : a.intents) {
15276                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15277                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15278                                    "Verification needed for IntentFilter:" + filter.toString());
15279                            mIntentFilterVerifier.addOneIntentFilterVerification(
15280                                    verifierUid, userId, verificationId, filter, packageName);
15281                            count++;
15282                        }
15283                    }
15284                }
15285            }
15286        }
15287
15288        if (count > 0) {
15289            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15290                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15291                    +  " for userId:" + userId);
15292            mIntentFilterVerifier.startVerifications(userId);
15293        } else {
15294            if (DEBUG_DOMAIN_VERIFICATION) {
15295                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15296            }
15297        }
15298    }
15299
15300    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15301        final ComponentName cn  = filter.activity.getComponentName();
15302        final String packageName = cn.getPackageName();
15303
15304        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15305                packageName);
15306        if (ivi == null) {
15307            return true;
15308        }
15309        int status = ivi.getStatus();
15310        switch (status) {
15311            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15312            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15313                return true;
15314
15315            default:
15316                // Nothing to do
15317                return false;
15318        }
15319    }
15320
15321    private static boolean isMultiArch(ApplicationInfo info) {
15322        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15323    }
15324
15325    private static boolean isExternal(PackageParser.Package pkg) {
15326        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15327    }
15328
15329    private static boolean isExternal(PackageSetting ps) {
15330        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15331    }
15332
15333    private static boolean isEphemeral(PackageParser.Package pkg) {
15334        return pkg.applicationInfo.isEphemeralApp();
15335    }
15336
15337    private static boolean isEphemeral(PackageSetting ps) {
15338        return ps.pkg != null && isEphemeral(ps.pkg);
15339    }
15340
15341    private static boolean isSystemApp(PackageParser.Package pkg) {
15342        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15343    }
15344
15345    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15346        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15347    }
15348
15349    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15350        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15351    }
15352
15353    private static boolean isSystemApp(PackageSetting ps) {
15354        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15355    }
15356
15357    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15358        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15359    }
15360
15361    private int packageFlagsToInstallFlags(PackageSetting ps) {
15362        int installFlags = 0;
15363        if (isEphemeral(ps)) {
15364            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15365        }
15366        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15367            // This existing package was an external ASEC install when we have
15368            // the external flag without a UUID
15369            installFlags |= PackageManager.INSTALL_EXTERNAL;
15370        }
15371        if (ps.isForwardLocked()) {
15372            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15373        }
15374        return installFlags;
15375    }
15376
15377    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15378        if (isExternal(pkg)) {
15379            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15380                return StorageManager.UUID_PRIMARY_PHYSICAL;
15381            } else {
15382                return pkg.volumeUuid;
15383            }
15384        } else {
15385            return StorageManager.UUID_PRIVATE_INTERNAL;
15386        }
15387    }
15388
15389    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15390        if (isExternal(pkg)) {
15391            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15392                return mSettings.getExternalVersion();
15393            } else {
15394                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15395            }
15396        } else {
15397            return mSettings.getInternalVersion();
15398        }
15399    }
15400
15401    private void deleteTempPackageFiles() {
15402        final FilenameFilter filter = new FilenameFilter() {
15403            public boolean accept(File dir, String name) {
15404                return name.startsWith("vmdl") && name.endsWith(".tmp");
15405            }
15406        };
15407        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15408            file.delete();
15409        }
15410    }
15411
15412    @Override
15413    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15414            int flags) {
15415        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15416                flags);
15417    }
15418
15419    @Override
15420    public void deletePackage(final String packageName,
15421            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15422        mContext.enforceCallingOrSelfPermission(
15423                android.Manifest.permission.DELETE_PACKAGES, null);
15424        Preconditions.checkNotNull(packageName);
15425        Preconditions.checkNotNull(observer);
15426        final int uid = Binder.getCallingUid();
15427        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15428        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15429        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15430            mContext.enforceCallingOrSelfPermission(
15431                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15432                    "deletePackage for user " + userId);
15433        }
15434
15435        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15436            try {
15437                observer.onPackageDeleted(packageName,
15438                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15439            } catch (RemoteException re) {
15440            }
15441            return;
15442        }
15443
15444        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15445            try {
15446                observer.onPackageDeleted(packageName,
15447                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15448            } catch (RemoteException re) {
15449            }
15450            return;
15451        }
15452
15453        if (DEBUG_REMOVE) {
15454            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15455                    + " deleteAllUsers: " + deleteAllUsers );
15456        }
15457        // Queue up an async operation since the package deletion may take a little while.
15458        mHandler.post(new Runnable() {
15459            public void run() {
15460                mHandler.removeCallbacks(this);
15461                int returnCode;
15462                if (!deleteAllUsers) {
15463                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15464                } else {
15465                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15466                    // If nobody is blocking uninstall, proceed with delete for all users
15467                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15468                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15469                    } else {
15470                        // Otherwise uninstall individually for users with blockUninstalls=false
15471                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15472                        for (int userId : users) {
15473                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15474                                returnCode = deletePackageX(packageName, userId, userFlags);
15475                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15476                                    Slog.w(TAG, "Package delete failed for user " + userId
15477                                            + ", returnCode " + returnCode);
15478                                }
15479                            }
15480                        }
15481                        // The app has only been marked uninstalled for certain users.
15482                        // We still need to report that delete was blocked
15483                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15484                    }
15485                }
15486                try {
15487                    observer.onPackageDeleted(packageName, returnCode, null);
15488                } catch (RemoteException e) {
15489                    Log.i(TAG, "Observer no longer exists.");
15490                } //end catch
15491            } //end run
15492        });
15493    }
15494
15495    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15496        int[] result = EMPTY_INT_ARRAY;
15497        for (int userId : userIds) {
15498            if (getBlockUninstallForUser(packageName, userId)) {
15499                result = ArrayUtils.appendInt(result, userId);
15500            }
15501        }
15502        return result;
15503    }
15504
15505    @Override
15506    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15507        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15508    }
15509
15510    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15511        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15512                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15513        try {
15514            if (dpm != null) {
15515                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15516                        /* callingUserOnly =*/ false);
15517                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15518                        : deviceOwnerComponentName.getPackageName();
15519                // Does the package contains the device owner?
15520                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15521                // this check is probably not needed, since DO should be registered as a device
15522                // admin on some user too. (Original bug for this: b/17657954)
15523                if (packageName.equals(deviceOwnerPackageName)) {
15524                    return true;
15525                }
15526                // Does it contain a device admin for any user?
15527                int[] users;
15528                if (userId == UserHandle.USER_ALL) {
15529                    users = sUserManager.getUserIds();
15530                } else {
15531                    users = new int[]{userId};
15532                }
15533                for (int i = 0; i < users.length; ++i) {
15534                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15535                        return true;
15536                    }
15537                }
15538            }
15539        } catch (RemoteException e) {
15540        }
15541        return false;
15542    }
15543
15544    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15545        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15546    }
15547
15548    /**
15549     *  This method is an internal method that could be get invoked either
15550     *  to delete an installed package or to clean up a failed installation.
15551     *  After deleting an installed package, a broadcast is sent to notify any
15552     *  listeners that the package has been removed. For cleaning up a failed
15553     *  installation, the broadcast is not necessary since the package's
15554     *  installation wouldn't have sent the initial broadcast either
15555     *  The key steps in deleting a package are
15556     *  deleting the package information in internal structures like mPackages,
15557     *  deleting the packages base directories through installd
15558     *  updating mSettings to reflect current status
15559     *  persisting settings for later use
15560     *  sending a broadcast if necessary
15561     */
15562    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15563        final PackageRemovedInfo info = new PackageRemovedInfo();
15564        final boolean res;
15565
15566        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15567                ? UserHandle.ALL : new UserHandle(userId);
15568
15569        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15570            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15571            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15572        }
15573
15574        PackageSetting uninstalledPs = null;
15575
15576        // for the uninstall-updates case and restricted profiles, remember the per-
15577        // user handle installed state
15578        int[] allUsers;
15579        synchronized (mPackages) {
15580            uninstalledPs = mSettings.mPackages.get(packageName);
15581            if (uninstalledPs == null) {
15582                Slog.w(TAG, "Not removing non-existent package " + packageName);
15583                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15584            }
15585            allUsers = sUserManager.getUserIds();
15586            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15587        }
15588
15589        synchronized (mInstallLock) {
15590            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15591            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15592                    "deletePackageX")) {
15593                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15594                        deleteFlags | REMOVE_CHATTY, info, true, null);
15595            }
15596            synchronized (mPackages) {
15597                if (res) {
15598                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15599                }
15600            }
15601        }
15602
15603        if (res) {
15604            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15605            info.sendPackageRemovedBroadcasts(killApp);
15606            info.sendSystemPackageUpdatedBroadcasts();
15607            info.sendSystemPackageAppearedBroadcasts();
15608        }
15609        // Force a gc here.
15610        Runtime.getRuntime().gc();
15611        // Delete the resources here after sending the broadcast to let
15612        // other processes clean up before deleting resources.
15613        if (info.args != null) {
15614            synchronized (mInstallLock) {
15615                info.args.doPostDeleteLI(true);
15616            }
15617        }
15618
15619        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15620    }
15621
15622    class PackageRemovedInfo {
15623        String removedPackage;
15624        int uid = -1;
15625        int removedAppId = -1;
15626        int[] origUsers;
15627        int[] removedUsers = null;
15628        boolean isRemovedPackageSystemUpdate = false;
15629        boolean isUpdate;
15630        boolean dataRemoved;
15631        boolean removedForAllUsers;
15632        // Clean up resources deleted packages.
15633        InstallArgs args = null;
15634        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15635        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15636
15637        void sendPackageRemovedBroadcasts(boolean killApp) {
15638            sendPackageRemovedBroadcastInternal(killApp);
15639            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15640            for (int i = 0; i < childCount; i++) {
15641                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15642                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15643            }
15644        }
15645
15646        void sendSystemPackageUpdatedBroadcasts() {
15647            if (isRemovedPackageSystemUpdate) {
15648                sendSystemPackageUpdatedBroadcastsInternal();
15649                final int childCount = (removedChildPackages != null)
15650                        ? removedChildPackages.size() : 0;
15651                for (int i = 0; i < childCount; i++) {
15652                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15653                    if (childInfo.isRemovedPackageSystemUpdate) {
15654                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15655                    }
15656                }
15657            }
15658        }
15659
15660        void sendSystemPackageAppearedBroadcasts() {
15661            final int packageCount = (appearedChildPackages != null)
15662                    ? appearedChildPackages.size() : 0;
15663            for (int i = 0; i < packageCount; i++) {
15664                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15665                for (int userId : installedInfo.newUsers) {
15666                    sendPackageAddedForUser(installedInfo.name, true,
15667                            UserHandle.getAppId(installedInfo.uid), userId);
15668                }
15669            }
15670        }
15671
15672        private void sendSystemPackageUpdatedBroadcastsInternal() {
15673            Bundle extras = new Bundle(2);
15674            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15675            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15676            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15677                    extras, 0, null, null, null);
15678            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15679                    extras, 0, null, null, null);
15680            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15681                    null, 0, removedPackage, null, null);
15682        }
15683
15684        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15685            Bundle extras = new Bundle(2);
15686            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15687            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15688            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15689            if (isUpdate || isRemovedPackageSystemUpdate) {
15690                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15691            }
15692            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15693            if (removedPackage != null) {
15694                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15695                        extras, 0, null, null, removedUsers);
15696                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15697                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15698                            removedPackage, extras, 0, null, null, removedUsers);
15699                }
15700            }
15701            if (removedAppId >= 0) {
15702                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15703                        removedUsers);
15704            }
15705        }
15706    }
15707
15708    /*
15709     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15710     * flag is not set, the data directory is removed as well.
15711     * make sure this flag is set for partially installed apps. If not its meaningless to
15712     * delete a partially installed application.
15713     */
15714    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15715            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15716        String packageName = ps.name;
15717        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15718        // Retrieve object to delete permissions for shared user later on
15719        final PackageParser.Package deletedPkg;
15720        final PackageSetting deletedPs;
15721        // reader
15722        synchronized (mPackages) {
15723            deletedPkg = mPackages.get(packageName);
15724            deletedPs = mSettings.mPackages.get(packageName);
15725            if (outInfo != null) {
15726                outInfo.removedPackage = packageName;
15727                outInfo.removedUsers = deletedPs != null
15728                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15729                        : null;
15730            }
15731        }
15732
15733        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15734
15735        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15736            final PackageParser.Package resolvedPkg;
15737            if (deletedPkg != null) {
15738                resolvedPkg = deletedPkg;
15739            } else {
15740                // We don't have a parsed package when it lives on an ejected
15741                // adopted storage device, so fake something together
15742                resolvedPkg = new PackageParser.Package(ps.name);
15743                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15744            }
15745            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15746                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15747            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15748            if (outInfo != null) {
15749                outInfo.dataRemoved = true;
15750            }
15751            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15752        }
15753
15754        // writer
15755        synchronized (mPackages) {
15756            if (deletedPs != null) {
15757                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15758                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15759                    clearDefaultBrowserIfNeeded(packageName);
15760                    if (outInfo != null) {
15761                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15762                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15763                    }
15764                    updatePermissionsLPw(deletedPs.name, null, 0);
15765                    if (deletedPs.sharedUser != null) {
15766                        // Remove permissions associated with package. Since runtime
15767                        // permissions are per user we have to kill the removed package
15768                        // or packages running under the shared user of the removed
15769                        // package if revoking the permissions requested only by the removed
15770                        // package is successful and this causes a change in gids.
15771                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15772                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15773                                    userId);
15774                            if (userIdToKill == UserHandle.USER_ALL
15775                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15776                                // If gids changed for this user, kill all affected packages.
15777                                mHandler.post(new Runnable() {
15778                                    @Override
15779                                    public void run() {
15780                                        // This has to happen with no lock held.
15781                                        killApplication(deletedPs.name, deletedPs.appId,
15782                                                KILL_APP_REASON_GIDS_CHANGED);
15783                                    }
15784                                });
15785                                break;
15786                            }
15787                        }
15788                    }
15789                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15790                }
15791                // make sure to preserve per-user disabled state if this removal was just
15792                // a downgrade of a system app to the factory package
15793                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15794                    if (DEBUG_REMOVE) {
15795                        Slog.d(TAG, "Propagating install state across downgrade");
15796                    }
15797                    for (int userId : allUserHandles) {
15798                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15799                        if (DEBUG_REMOVE) {
15800                            Slog.d(TAG, "    user " + userId + " => " + installed);
15801                        }
15802                        ps.setInstalled(installed, userId);
15803                    }
15804                }
15805            }
15806            // can downgrade to reader
15807            if (writeSettings) {
15808                // Save settings now
15809                mSettings.writeLPr();
15810            }
15811        }
15812        if (outInfo != null) {
15813            // A user ID was deleted here. Go through all users and remove it
15814            // from KeyStore.
15815            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15816        }
15817    }
15818
15819    static boolean locationIsPrivileged(File path) {
15820        try {
15821            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15822                    .getCanonicalPath();
15823            return path.getCanonicalPath().startsWith(privilegedAppDir);
15824        } catch (IOException e) {
15825            Slog.e(TAG, "Unable to access code path " + path);
15826        }
15827        return false;
15828    }
15829
15830    /*
15831     * Tries to delete system package.
15832     */
15833    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15834            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15835            boolean writeSettings) {
15836        if (deletedPs.parentPackageName != null) {
15837            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15838            return false;
15839        }
15840
15841        final boolean applyUserRestrictions
15842                = (allUserHandles != null) && (outInfo.origUsers != null);
15843        final PackageSetting disabledPs;
15844        // Confirm if the system package has been updated
15845        // An updated system app can be deleted. This will also have to restore
15846        // the system pkg from system partition
15847        // reader
15848        synchronized (mPackages) {
15849            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15850        }
15851
15852        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15853                + " disabledPs=" + disabledPs);
15854
15855        if (disabledPs == null) {
15856            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15857            return false;
15858        } else if (DEBUG_REMOVE) {
15859            Slog.d(TAG, "Deleting system pkg from data partition");
15860        }
15861
15862        if (DEBUG_REMOVE) {
15863            if (applyUserRestrictions) {
15864                Slog.d(TAG, "Remembering install states:");
15865                for (int userId : allUserHandles) {
15866                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15867                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15868                }
15869            }
15870        }
15871
15872        // Delete the updated package
15873        outInfo.isRemovedPackageSystemUpdate = true;
15874        if (outInfo.removedChildPackages != null) {
15875            final int childCount = (deletedPs.childPackageNames != null)
15876                    ? deletedPs.childPackageNames.size() : 0;
15877            for (int i = 0; i < childCount; i++) {
15878                String childPackageName = deletedPs.childPackageNames.get(i);
15879                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15880                        .contains(childPackageName)) {
15881                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15882                            childPackageName);
15883                    if (childInfo != null) {
15884                        childInfo.isRemovedPackageSystemUpdate = true;
15885                    }
15886                }
15887            }
15888        }
15889
15890        if (disabledPs.versionCode < deletedPs.versionCode) {
15891            // Delete data for downgrades
15892            flags &= ~PackageManager.DELETE_KEEP_DATA;
15893        } else {
15894            // Preserve data by setting flag
15895            flags |= PackageManager.DELETE_KEEP_DATA;
15896        }
15897
15898        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15899                outInfo, writeSettings, disabledPs.pkg);
15900        if (!ret) {
15901            return false;
15902        }
15903
15904        // writer
15905        synchronized (mPackages) {
15906            // Reinstate the old system package
15907            enableSystemPackageLPw(disabledPs.pkg);
15908            // Remove any native libraries from the upgraded package.
15909            removeNativeBinariesLI(deletedPs);
15910        }
15911
15912        // Install the system package
15913        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15914        int parseFlags = mDefParseFlags
15915                | PackageParser.PARSE_MUST_BE_APK
15916                | PackageParser.PARSE_IS_SYSTEM
15917                | PackageParser.PARSE_IS_SYSTEM_DIR;
15918        if (locationIsPrivileged(disabledPs.codePath)) {
15919            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15920        }
15921
15922        final PackageParser.Package newPkg;
15923        try {
15924            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15925        } catch (PackageManagerException e) {
15926            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15927                    + e.getMessage());
15928            return false;
15929        }
15930
15931        prepareAppDataAfterInstallLIF(newPkg);
15932
15933        // writer
15934        synchronized (mPackages) {
15935            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15936
15937            // Propagate the permissions state as we do not want to drop on the floor
15938            // runtime permissions. The update permissions method below will take
15939            // care of removing obsolete permissions and grant install permissions.
15940            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15941            updatePermissionsLPw(newPkg.packageName, newPkg,
15942                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15943
15944            if (applyUserRestrictions) {
15945                if (DEBUG_REMOVE) {
15946                    Slog.d(TAG, "Propagating install state across reinstall");
15947                }
15948                for (int userId : allUserHandles) {
15949                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15950                    if (DEBUG_REMOVE) {
15951                        Slog.d(TAG, "    user " + userId + " => " + installed);
15952                    }
15953                    ps.setInstalled(installed, userId);
15954
15955                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15956                }
15957                // Regardless of writeSettings we need to ensure that this restriction
15958                // state propagation is persisted
15959                mSettings.writeAllUsersPackageRestrictionsLPr();
15960            }
15961            // can downgrade to reader here
15962            if (writeSettings) {
15963                mSettings.writeLPr();
15964            }
15965        }
15966        return true;
15967    }
15968
15969    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15970            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15971            PackageRemovedInfo outInfo, boolean writeSettings,
15972            PackageParser.Package replacingPackage) {
15973        synchronized (mPackages) {
15974            if (outInfo != null) {
15975                outInfo.uid = ps.appId;
15976            }
15977
15978            if (outInfo != null && outInfo.removedChildPackages != null) {
15979                final int childCount = (ps.childPackageNames != null)
15980                        ? ps.childPackageNames.size() : 0;
15981                for (int i = 0; i < childCount; i++) {
15982                    String childPackageName = ps.childPackageNames.get(i);
15983                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15984                    if (childPs == null) {
15985                        return false;
15986                    }
15987                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15988                            childPackageName);
15989                    if (childInfo != null) {
15990                        childInfo.uid = childPs.appId;
15991                    }
15992                }
15993            }
15994        }
15995
15996        // Delete package data from internal structures and also remove data if flag is set
15997        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15998
15999        // Delete the child packages data
16000        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16001        for (int i = 0; i < childCount; i++) {
16002            PackageSetting childPs;
16003            synchronized (mPackages) {
16004                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16005            }
16006            if (childPs != null) {
16007                PackageRemovedInfo childOutInfo = (outInfo != null
16008                        && outInfo.removedChildPackages != null)
16009                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16010                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16011                        && (replacingPackage != null
16012                        && !replacingPackage.hasChildPackage(childPs.name))
16013                        ? flags & ~DELETE_KEEP_DATA : flags;
16014                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16015                        deleteFlags, writeSettings);
16016            }
16017        }
16018
16019        // Delete application code and resources only for parent packages
16020        if (ps.parentPackageName == null) {
16021            if (deleteCodeAndResources && (outInfo != null)) {
16022                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16023                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16024                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16025            }
16026        }
16027
16028        return true;
16029    }
16030
16031    @Override
16032    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16033            int userId) {
16034        mContext.enforceCallingOrSelfPermission(
16035                android.Manifest.permission.DELETE_PACKAGES, null);
16036        synchronized (mPackages) {
16037            PackageSetting ps = mSettings.mPackages.get(packageName);
16038            if (ps == null) {
16039                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16040                return false;
16041            }
16042            if (!ps.getInstalled(userId)) {
16043                // Can't block uninstall for an app that is not installed or enabled.
16044                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16045                return false;
16046            }
16047            ps.setBlockUninstall(blockUninstall, userId);
16048            mSettings.writePackageRestrictionsLPr(userId);
16049        }
16050        return true;
16051    }
16052
16053    @Override
16054    public boolean getBlockUninstallForUser(String packageName, int userId) {
16055        synchronized (mPackages) {
16056            PackageSetting ps = mSettings.mPackages.get(packageName);
16057            if (ps == null) {
16058                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16059                return false;
16060            }
16061            return ps.getBlockUninstall(userId);
16062        }
16063    }
16064
16065    @Override
16066    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16067        int callingUid = Binder.getCallingUid();
16068        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16069            throw new SecurityException(
16070                    "setRequiredForSystemUser can only be run by the system or root");
16071        }
16072        synchronized (mPackages) {
16073            PackageSetting ps = mSettings.mPackages.get(packageName);
16074            if (ps == null) {
16075                Log.w(TAG, "Package doesn't exist: " + packageName);
16076                return false;
16077            }
16078            if (systemUserApp) {
16079                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16080            } else {
16081                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16082            }
16083            mSettings.writeLPr();
16084        }
16085        return true;
16086    }
16087
16088    /*
16089     * This method handles package deletion in general
16090     */
16091    private boolean deletePackageLIF(String packageName, UserHandle user,
16092            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16093            PackageRemovedInfo outInfo, boolean writeSettings,
16094            PackageParser.Package replacingPackage) {
16095        if (packageName == null) {
16096            Slog.w(TAG, "Attempt to delete null packageName.");
16097            return false;
16098        }
16099
16100        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16101
16102        PackageSetting ps;
16103
16104        synchronized (mPackages) {
16105            ps = mSettings.mPackages.get(packageName);
16106            if (ps == null) {
16107                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16108                return false;
16109            }
16110
16111            if (ps.parentPackageName != null && (!isSystemApp(ps)
16112                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16113                if (DEBUG_REMOVE) {
16114                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16115                            + ((user == null) ? UserHandle.USER_ALL : user));
16116                }
16117                final int removedUserId = (user != null) ? user.getIdentifier()
16118                        : UserHandle.USER_ALL;
16119                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16120                    return false;
16121                }
16122                markPackageUninstalledForUserLPw(ps, user);
16123                scheduleWritePackageRestrictionsLocked(user);
16124                return true;
16125            }
16126        }
16127
16128        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16129                && user.getIdentifier() != UserHandle.USER_ALL)) {
16130            // The caller is asking that the package only be deleted for a single
16131            // user.  To do this, we just mark its uninstalled state and delete
16132            // its data. If this is a system app, we only allow this to happen if
16133            // they have set the special DELETE_SYSTEM_APP which requests different
16134            // semantics than normal for uninstalling system apps.
16135            markPackageUninstalledForUserLPw(ps, user);
16136
16137            if (!isSystemApp(ps)) {
16138                // Do not uninstall the APK if an app should be cached
16139                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16140                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16141                    // Other user still have this package installed, so all
16142                    // we need to do is clear this user's data and save that
16143                    // it is uninstalled.
16144                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16145                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16146                        return false;
16147                    }
16148                    scheduleWritePackageRestrictionsLocked(user);
16149                    return true;
16150                } else {
16151                    // We need to set it back to 'installed' so the uninstall
16152                    // broadcasts will be sent correctly.
16153                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16154                    ps.setInstalled(true, user.getIdentifier());
16155                }
16156            } else {
16157                // This is a system app, so we assume that the
16158                // other users still have this package installed, so all
16159                // we need to do is clear this user's data and save that
16160                // it is uninstalled.
16161                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16162                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16163                    return false;
16164                }
16165                scheduleWritePackageRestrictionsLocked(user);
16166                return true;
16167            }
16168        }
16169
16170        // If we are deleting a composite package for all users, keep track
16171        // of result for each child.
16172        if (ps.childPackageNames != null && outInfo != null) {
16173            synchronized (mPackages) {
16174                final int childCount = ps.childPackageNames.size();
16175                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16176                for (int i = 0; i < childCount; i++) {
16177                    String childPackageName = ps.childPackageNames.get(i);
16178                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16179                    childInfo.removedPackage = childPackageName;
16180                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16181                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16182                    if (childPs != null) {
16183                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16184                    }
16185                }
16186            }
16187        }
16188
16189        boolean ret = false;
16190        if (isSystemApp(ps)) {
16191            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16192            // When an updated system application is deleted we delete the existing resources
16193            // as well and fall back to existing code in system partition
16194            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16195        } else {
16196            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16197            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16198                    outInfo, writeSettings, replacingPackage);
16199        }
16200
16201        // Take a note whether we deleted the package for all users
16202        if (outInfo != null) {
16203            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16204            if (outInfo.removedChildPackages != null) {
16205                synchronized (mPackages) {
16206                    final int childCount = outInfo.removedChildPackages.size();
16207                    for (int i = 0; i < childCount; i++) {
16208                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16209                        if (childInfo != null) {
16210                            childInfo.removedForAllUsers = mPackages.get(
16211                                    childInfo.removedPackage) == null;
16212                        }
16213                    }
16214                }
16215            }
16216            // If we uninstalled an update to a system app there may be some
16217            // child packages that appeared as they are declared in the system
16218            // app but were not declared in the update.
16219            if (isSystemApp(ps)) {
16220                synchronized (mPackages) {
16221                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16222                    final int childCount = (updatedPs.childPackageNames != null)
16223                            ? updatedPs.childPackageNames.size() : 0;
16224                    for (int i = 0; i < childCount; i++) {
16225                        String childPackageName = updatedPs.childPackageNames.get(i);
16226                        if (outInfo.removedChildPackages == null
16227                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16228                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16229                            if (childPs == null) {
16230                                continue;
16231                            }
16232                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16233                            installRes.name = childPackageName;
16234                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16235                            installRes.pkg = mPackages.get(childPackageName);
16236                            installRes.uid = childPs.pkg.applicationInfo.uid;
16237                            if (outInfo.appearedChildPackages == null) {
16238                                outInfo.appearedChildPackages = new ArrayMap<>();
16239                            }
16240                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16241                        }
16242                    }
16243                }
16244            }
16245        }
16246
16247        return ret;
16248    }
16249
16250    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16251        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16252                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16253        for (int nextUserId : userIds) {
16254            if (DEBUG_REMOVE) {
16255                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16256            }
16257            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16258                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16259                    false /*hidden*/, false /*suspended*/, null, null, null,
16260                    false /*blockUninstall*/,
16261                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16262        }
16263    }
16264
16265    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16266            PackageRemovedInfo outInfo) {
16267        final PackageParser.Package pkg;
16268        synchronized (mPackages) {
16269            pkg = mPackages.get(ps.name);
16270        }
16271
16272        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16273                : new int[] {userId};
16274        for (int nextUserId : userIds) {
16275            if (DEBUG_REMOVE) {
16276                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16277                        + nextUserId);
16278            }
16279
16280            destroyAppDataLIF(pkg, userId,
16281                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16282            destroyAppProfilesLIF(pkg, userId);
16283            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16284            schedulePackageCleaning(ps.name, nextUserId, false);
16285            synchronized (mPackages) {
16286                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16287                    scheduleWritePackageRestrictionsLocked(nextUserId);
16288                }
16289                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16290            }
16291        }
16292
16293        if (outInfo != null) {
16294            outInfo.removedPackage = ps.name;
16295            outInfo.removedAppId = ps.appId;
16296            outInfo.removedUsers = userIds;
16297        }
16298
16299        return true;
16300    }
16301
16302    private final class ClearStorageConnection implements ServiceConnection {
16303        IMediaContainerService mContainerService;
16304
16305        @Override
16306        public void onServiceConnected(ComponentName name, IBinder service) {
16307            synchronized (this) {
16308                mContainerService = IMediaContainerService.Stub.asInterface(service);
16309                notifyAll();
16310            }
16311        }
16312
16313        @Override
16314        public void onServiceDisconnected(ComponentName name) {
16315        }
16316    }
16317
16318    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16319        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16320
16321        final boolean mounted;
16322        if (Environment.isExternalStorageEmulated()) {
16323            mounted = true;
16324        } else {
16325            final String status = Environment.getExternalStorageState();
16326
16327            mounted = status.equals(Environment.MEDIA_MOUNTED)
16328                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16329        }
16330
16331        if (!mounted) {
16332            return;
16333        }
16334
16335        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16336        int[] users;
16337        if (userId == UserHandle.USER_ALL) {
16338            users = sUserManager.getUserIds();
16339        } else {
16340            users = new int[] { userId };
16341        }
16342        final ClearStorageConnection conn = new ClearStorageConnection();
16343        if (mContext.bindServiceAsUser(
16344                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16345            try {
16346                for (int curUser : users) {
16347                    long timeout = SystemClock.uptimeMillis() + 5000;
16348                    synchronized (conn) {
16349                        long now;
16350                        while (conn.mContainerService == null &&
16351                                (now = SystemClock.uptimeMillis()) < timeout) {
16352                            try {
16353                                conn.wait(timeout - now);
16354                            } catch (InterruptedException e) {
16355                            }
16356                        }
16357                    }
16358                    if (conn.mContainerService == null) {
16359                        return;
16360                    }
16361
16362                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16363                    clearDirectory(conn.mContainerService,
16364                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16365                    if (allData) {
16366                        clearDirectory(conn.mContainerService,
16367                                userEnv.buildExternalStorageAppDataDirs(packageName));
16368                        clearDirectory(conn.mContainerService,
16369                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16370                    }
16371                }
16372            } finally {
16373                mContext.unbindService(conn);
16374            }
16375        }
16376    }
16377
16378    @Override
16379    public void clearApplicationProfileData(String packageName) {
16380        enforceSystemOrRoot("Only the system can clear all profile data");
16381
16382        final PackageParser.Package pkg;
16383        synchronized (mPackages) {
16384            pkg = mPackages.get(packageName);
16385        }
16386
16387        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16388            synchronized (mInstallLock) {
16389                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16390                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16391                        true /* removeBaseMarker */);
16392            }
16393        }
16394    }
16395
16396    @Override
16397    public void clearApplicationUserData(final String packageName,
16398            final IPackageDataObserver observer, final int userId) {
16399        mContext.enforceCallingOrSelfPermission(
16400                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16401
16402        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16403                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16404
16405        if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
16406            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16407        }
16408        // Queue up an async operation since the package deletion may take a little while.
16409        mHandler.post(new Runnable() {
16410            public void run() {
16411                mHandler.removeCallbacks(this);
16412                final boolean succeeded;
16413                try (PackageFreezer freezer = freezePackage(packageName,
16414                        "clearApplicationUserData")) {
16415                    synchronized (mInstallLock) {
16416                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16417                    }
16418                    clearExternalStorageDataSync(packageName, userId, true);
16419                }
16420                if (succeeded) {
16421                    // invoke DeviceStorageMonitor's update method to clear any notifications
16422                    DeviceStorageMonitorInternal dsm = LocalServices
16423                            .getService(DeviceStorageMonitorInternal.class);
16424                    if (dsm != null) {
16425                        dsm.checkMemory();
16426                    }
16427                }
16428                if(observer != null) {
16429                    try {
16430                        observer.onRemoveCompleted(packageName, succeeded);
16431                    } catch (RemoteException e) {
16432                        Log.i(TAG, "Observer no longer exists.");
16433                    }
16434                } //end if observer
16435            } //end run
16436        });
16437    }
16438
16439    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16440        if (packageName == null) {
16441            Slog.w(TAG, "Attempt to delete null packageName.");
16442            return false;
16443        }
16444
16445        // Try finding details about the requested package
16446        PackageParser.Package pkg;
16447        synchronized (mPackages) {
16448            pkg = mPackages.get(packageName);
16449            if (pkg == null) {
16450                final PackageSetting ps = mSettings.mPackages.get(packageName);
16451                if (ps != null) {
16452                    pkg = ps.pkg;
16453                }
16454            }
16455
16456            if (pkg == null) {
16457                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16458                return false;
16459            }
16460
16461            PackageSetting ps = (PackageSetting) pkg.mExtras;
16462            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16463        }
16464
16465        clearAppDataLIF(pkg, userId,
16466                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16467
16468        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16469        removeKeystoreDataIfNeeded(userId, appId);
16470
16471        UserManagerInternal umInternal = getUserManagerInternal();
16472        final int flags;
16473        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16474            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16475        } else if (umInternal.isUserRunning(userId)) {
16476            flags = StorageManager.FLAG_STORAGE_DE;
16477        } else {
16478            flags = 0;
16479        }
16480        prepareAppDataContentsLIF(pkg, userId, flags);
16481
16482        return true;
16483    }
16484
16485    /**
16486     * Reverts user permission state changes (permissions and flags) in
16487     * all packages for a given user.
16488     *
16489     * @param userId The device user for which to do a reset.
16490     */
16491    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16492        final int packageCount = mPackages.size();
16493        for (int i = 0; i < packageCount; i++) {
16494            PackageParser.Package pkg = mPackages.valueAt(i);
16495            PackageSetting ps = (PackageSetting) pkg.mExtras;
16496            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16497        }
16498    }
16499
16500    private void resetNetworkPolicies(int userId) {
16501        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16502    }
16503
16504    /**
16505     * Reverts user permission state changes (permissions and flags).
16506     *
16507     * @param ps The package for which to reset.
16508     * @param userId The device user for which to do a reset.
16509     */
16510    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16511            final PackageSetting ps, final int userId) {
16512        if (ps.pkg == null) {
16513            return;
16514        }
16515
16516        // These are flags that can change base on user actions.
16517        final int userSettableMask = FLAG_PERMISSION_USER_SET
16518                | FLAG_PERMISSION_USER_FIXED
16519                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16520                | FLAG_PERMISSION_REVIEW_REQUIRED;
16521
16522        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16523                | FLAG_PERMISSION_POLICY_FIXED;
16524
16525        boolean writeInstallPermissions = false;
16526        boolean writeRuntimePermissions = false;
16527
16528        final int permissionCount = ps.pkg.requestedPermissions.size();
16529        for (int i = 0; i < permissionCount; i++) {
16530            String permission = ps.pkg.requestedPermissions.get(i);
16531
16532            BasePermission bp = mSettings.mPermissions.get(permission);
16533            if (bp == null) {
16534                continue;
16535            }
16536
16537            // If shared user we just reset the state to which only this app contributed.
16538            if (ps.sharedUser != null) {
16539                boolean used = false;
16540                final int packageCount = ps.sharedUser.packages.size();
16541                for (int j = 0; j < packageCount; j++) {
16542                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16543                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16544                            && pkg.pkg.requestedPermissions.contains(permission)) {
16545                        used = true;
16546                        break;
16547                    }
16548                }
16549                if (used) {
16550                    continue;
16551                }
16552            }
16553
16554            PermissionsState permissionsState = ps.getPermissionsState();
16555
16556            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16557
16558            // Always clear the user settable flags.
16559            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16560                    bp.name) != null;
16561            // If permission review is enabled and this is a legacy app, mark the
16562            // permission as requiring a review as this is the initial state.
16563            int flags = 0;
16564            if (Build.PERMISSIONS_REVIEW_REQUIRED
16565                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16566                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16567            }
16568            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16569                if (hasInstallState) {
16570                    writeInstallPermissions = true;
16571                } else {
16572                    writeRuntimePermissions = true;
16573                }
16574            }
16575
16576            // Below is only runtime permission handling.
16577            if (!bp.isRuntime()) {
16578                continue;
16579            }
16580
16581            // Never clobber system or policy.
16582            if ((oldFlags & policyOrSystemFlags) != 0) {
16583                continue;
16584            }
16585
16586            // If this permission was granted by default, make sure it is.
16587            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16588                if (permissionsState.grantRuntimePermission(bp, userId)
16589                        != PERMISSION_OPERATION_FAILURE) {
16590                    writeRuntimePermissions = true;
16591                }
16592            // If permission review is enabled the permissions for a legacy apps
16593            // are represented as constantly granted runtime ones, so don't revoke.
16594            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16595                // Otherwise, reset the permission.
16596                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16597                switch (revokeResult) {
16598                    case PERMISSION_OPERATION_SUCCESS:
16599                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16600                        writeRuntimePermissions = true;
16601                        final int appId = ps.appId;
16602                        mHandler.post(new Runnable() {
16603                            @Override
16604                            public void run() {
16605                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16606                            }
16607                        });
16608                    } break;
16609                }
16610            }
16611        }
16612
16613        // Synchronously write as we are taking permissions away.
16614        if (writeRuntimePermissions) {
16615            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16616        }
16617
16618        // Synchronously write as we are taking permissions away.
16619        if (writeInstallPermissions) {
16620            mSettings.writeLPr();
16621        }
16622    }
16623
16624    /**
16625     * Remove entries from the keystore daemon. Will only remove it if the
16626     * {@code appId} is valid.
16627     */
16628    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16629        if (appId < 0) {
16630            return;
16631        }
16632
16633        final KeyStore keyStore = KeyStore.getInstance();
16634        if (keyStore != null) {
16635            if (userId == UserHandle.USER_ALL) {
16636                for (final int individual : sUserManager.getUserIds()) {
16637                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16638                }
16639            } else {
16640                keyStore.clearUid(UserHandle.getUid(userId, appId));
16641            }
16642        } else {
16643            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16644        }
16645    }
16646
16647    @Override
16648    public void deleteApplicationCacheFiles(final String packageName,
16649            final IPackageDataObserver observer) {
16650        final int userId = UserHandle.getCallingUserId();
16651        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16652    }
16653
16654    @Override
16655    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16656            final IPackageDataObserver observer) {
16657        mContext.enforceCallingOrSelfPermission(
16658                android.Manifest.permission.DELETE_CACHE_FILES, null);
16659        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16660                /* requireFullPermission= */ true, /* checkShell= */ false,
16661                "delete application cache files");
16662
16663        final PackageParser.Package pkg;
16664        synchronized (mPackages) {
16665            pkg = mPackages.get(packageName);
16666        }
16667
16668        // Queue up an async operation since the package deletion may take a little while.
16669        mHandler.post(new Runnable() {
16670            public void run() {
16671                synchronized (mInstallLock) {
16672                    final int flags = StorageManager.FLAG_STORAGE_DE
16673                            | StorageManager.FLAG_STORAGE_CE;
16674                    // We're only clearing cache files, so we don't care if the
16675                    // app is unfrozen and still able to run
16676                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16677                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16678                }
16679                clearExternalStorageDataSync(packageName, userId, false);
16680                if (observer != null) {
16681                    try {
16682                        observer.onRemoveCompleted(packageName, true);
16683                    } catch (RemoteException e) {
16684                        Log.i(TAG, "Observer no longer exists.");
16685                    }
16686                }
16687            }
16688        });
16689    }
16690
16691    @Override
16692    public void getPackageSizeInfo(final String packageName, int userHandle,
16693            final IPackageStatsObserver observer) {
16694        mContext.enforceCallingOrSelfPermission(
16695                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16696        if (packageName == null) {
16697            throw new IllegalArgumentException("Attempt to get size of null packageName");
16698        }
16699
16700        PackageStats stats = new PackageStats(packageName, userHandle);
16701
16702        /*
16703         * Queue up an async operation since the package measurement may take a
16704         * little while.
16705         */
16706        Message msg = mHandler.obtainMessage(INIT_COPY);
16707        msg.obj = new MeasureParams(stats, observer);
16708        mHandler.sendMessage(msg);
16709    }
16710
16711    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16712        final PackageSetting ps;
16713        synchronized (mPackages) {
16714            ps = mSettings.mPackages.get(packageName);
16715            if (ps == null) {
16716                Slog.w(TAG, "Failed to find settings for " + packageName);
16717                return false;
16718            }
16719        }
16720        try {
16721            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16722                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16723                    ps.getCeDataInode(userId), ps.codePathString, stats);
16724        } catch (InstallerException e) {
16725            Slog.w(TAG, String.valueOf(e));
16726            return false;
16727        }
16728
16729        // For now, ignore code size of packages on system partition
16730        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16731            stats.codeSize = 0;
16732        }
16733
16734        return true;
16735    }
16736
16737    private int getUidTargetSdkVersionLockedLPr(int uid) {
16738        Object obj = mSettings.getUserIdLPr(uid);
16739        if (obj instanceof SharedUserSetting) {
16740            final SharedUserSetting sus = (SharedUserSetting) obj;
16741            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16742            final Iterator<PackageSetting> it = sus.packages.iterator();
16743            while (it.hasNext()) {
16744                final PackageSetting ps = it.next();
16745                if (ps.pkg != null) {
16746                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16747                    if (v < vers) vers = v;
16748                }
16749            }
16750            return vers;
16751        } else if (obj instanceof PackageSetting) {
16752            final PackageSetting ps = (PackageSetting) obj;
16753            if (ps.pkg != null) {
16754                return ps.pkg.applicationInfo.targetSdkVersion;
16755            }
16756        }
16757        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16758    }
16759
16760    @Override
16761    public void addPreferredActivity(IntentFilter filter, int match,
16762            ComponentName[] set, ComponentName activity, int userId) {
16763        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16764                "Adding preferred");
16765    }
16766
16767    private void addPreferredActivityInternal(IntentFilter filter, int match,
16768            ComponentName[] set, ComponentName activity, boolean always, int userId,
16769            String opname) {
16770        // writer
16771        int callingUid = Binder.getCallingUid();
16772        enforceCrossUserPermission(callingUid, userId,
16773                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16774        if (filter.countActions() == 0) {
16775            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16776            return;
16777        }
16778        synchronized (mPackages) {
16779            if (mContext.checkCallingOrSelfPermission(
16780                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16781                    != PackageManager.PERMISSION_GRANTED) {
16782                if (getUidTargetSdkVersionLockedLPr(callingUid)
16783                        < Build.VERSION_CODES.FROYO) {
16784                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16785                            + callingUid);
16786                    return;
16787                }
16788                mContext.enforceCallingOrSelfPermission(
16789                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16790            }
16791
16792            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16793            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16794                    + userId + ":");
16795            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16796            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16797            scheduleWritePackageRestrictionsLocked(userId);
16798        }
16799    }
16800
16801    @Override
16802    public void replacePreferredActivity(IntentFilter filter, int match,
16803            ComponentName[] set, ComponentName activity, int userId) {
16804        if (filter.countActions() != 1) {
16805            throw new IllegalArgumentException(
16806                    "replacePreferredActivity expects filter to have only 1 action.");
16807        }
16808        if (filter.countDataAuthorities() != 0
16809                || filter.countDataPaths() != 0
16810                || filter.countDataSchemes() > 1
16811                || filter.countDataTypes() != 0) {
16812            throw new IllegalArgumentException(
16813                    "replacePreferredActivity expects filter to have no data authorities, " +
16814                    "paths, or types; and at most one scheme.");
16815        }
16816
16817        final int callingUid = Binder.getCallingUid();
16818        enforceCrossUserPermission(callingUid, userId,
16819                true /* requireFullPermission */, false /* checkShell */,
16820                "replace preferred activity");
16821        synchronized (mPackages) {
16822            if (mContext.checkCallingOrSelfPermission(
16823                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16824                    != PackageManager.PERMISSION_GRANTED) {
16825                if (getUidTargetSdkVersionLockedLPr(callingUid)
16826                        < Build.VERSION_CODES.FROYO) {
16827                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16828                            + Binder.getCallingUid());
16829                    return;
16830                }
16831                mContext.enforceCallingOrSelfPermission(
16832                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16833            }
16834
16835            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16836            if (pir != null) {
16837                // Get all of the existing entries that exactly match this filter.
16838                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16839                if (existing != null && existing.size() == 1) {
16840                    PreferredActivity cur = existing.get(0);
16841                    if (DEBUG_PREFERRED) {
16842                        Slog.i(TAG, "Checking replace of preferred:");
16843                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16844                        if (!cur.mPref.mAlways) {
16845                            Slog.i(TAG, "  -- CUR; not mAlways!");
16846                        } else {
16847                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16848                            Slog.i(TAG, "  -- CUR: mSet="
16849                                    + Arrays.toString(cur.mPref.mSetComponents));
16850                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16851                            Slog.i(TAG, "  -- NEW: mMatch="
16852                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16853                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16854                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16855                        }
16856                    }
16857                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16858                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16859                            && cur.mPref.sameSet(set)) {
16860                        // Setting the preferred activity to what it happens to be already
16861                        if (DEBUG_PREFERRED) {
16862                            Slog.i(TAG, "Replacing with same preferred activity "
16863                                    + cur.mPref.mShortComponent + " for user "
16864                                    + userId + ":");
16865                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16866                        }
16867                        return;
16868                    }
16869                }
16870
16871                if (existing != null) {
16872                    if (DEBUG_PREFERRED) {
16873                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16874                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16875                    }
16876                    for (int i = 0; i < existing.size(); i++) {
16877                        PreferredActivity pa = existing.get(i);
16878                        if (DEBUG_PREFERRED) {
16879                            Slog.i(TAG, "Removing existing preferred activity "
16880                                    + pa.mPref.mComponent + ":");
16881                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16882                        }
16883                        pir.removeFilter(pa);
16884                    }
16885                }
16886            }
16887            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16888                    "Replacing preferred");
16889        }
16890    }
16891
16892    @Override
16893    public void clearPackagePreferredActivities(String packageName) {
16894        final int uid = Binder.getCallingUid();
16895        // writer
16896        synchronized (mPackages) {
16897            PackageParser.Package pkg = mPackages.get(packageName);
16898            if (pkg == null || pkg.applicationInfo.uid != uid) {
16899                if (mContext.checkCallingOrSelfPermission(
16900                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16901                        != PackageManager.PERMISSION_GRANTED) {
16902                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16903                            < Build.VERSION_CODES.FROYO) {
16904                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16905                                + Binder.getCallingUid());
16906                        return;
16907                    }
16908                    mContext.enforceCallingOrSelfPermission(
16909                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16910                }
16911            }
16912
16913            int user = UserHandle.getCallingUserId();
16914            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16915                scheduleWritePackageRestrictionsLocked(user);
16916            }
16917        }
16918    }
16919
16920    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16921    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16922        ArrayList<PreferredActivity> removed = null;
16923        boolean changed = false;
16924        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16925            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16926            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16927            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16928                continue;
16929            }
16930            Iterator<PreferredActivity> it = pir.filterIterator();
16931            while (it.hasNext()) {
16932                PreferredActivity pa = it.next();
16933                // Mark entry for removal only if it matches the package name
16934                // and the entry is of type "always".
16935                if (packageName == null ||
16936                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16937                                && pa.mPref.mAlways)) {
16938                    if (removed == null) {
16939                        removed = new ArrayList<PreferredActivity>();
16940                    }
16941                    removed.add(pa);
16942                }
16943            }
16944            if (removed != null) {
16945                for (int j=0; j<removed.size(); j++) {
16946                    PreferredActivity pa = removed.get(j);
16947                    pir.removeFilter(pa);
16948                }
16949                changed = true;
16950            }
16951        }
16952        return changed;
16953    }
16954
16955    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16956    private void clearIntentFilterVerificationsLPw(int userId) {
16957        final int packageCount = mPackages.size();
16958        for (int i = 0; i < packageCount; i++) {
16959            PackageParser.Package pkg = mPackages.valueAt(i);
16960            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16961        }
16962    }
16963
16964    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16965    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16966        if (userId == UserHandle.USER_ALL) {
16967            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16968                    sUserManager.getUserIds())) {
16969                for (int oneUserId : sUserManager.getUserIds()) {
16970                    scheduleWritePackageRestrictionsLocked(oneUserId);
16971                }
16972            }
16973        } else {
16974            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16975                scheduleWritePackageRestrictionsLocked(userId);
16976            }
16977        }
16978    }
16979
16980    void clearDefaultBrowserIfNeeded(String packageName) {
16981        for (int oneUserId : sUserManager.getUserIds()) {
16982            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16983            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16984            if (packageName.equals(defaultBrowserPackageName)) {
16985                setDefaultBrowserPackageName(null, oneUserId);
16986            }
16987        }
16988    }
16989
16990    @Override
16991    public void resetApplicationPreferences(int userId) {
16992        mContext.enforceCallingOrSelfPermission(
16993                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16994        final long identity = Binder.clearCallingIdentity();
16995        // writer
16996        try {
16997            synchronized (mPackages) {
16998                clearPackagePreferredActivitiesLPw(null, userId);
16999                mSettings.applyDefaultPreferredAppsLPw(this, userId);
17000                // TODO: We have to reset the default SMS and Phone. This requires
17001                // significant refactoring to keep all default apps in the package
17002                // manager (cleaner but more work) or have the services provide
17003                // callbacks to the package manager to request a default app reset.
17004                applyFactoryDefaultBrowserLPw(userId);
17005                clearIntentFilterVerificationsLPw(userId);
17006                primeDomainVerificationsLPw(userId);
17007                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17008                scheduleWritePackageRestrictionsLocked(userId);
17009            }
17010            resetNetworkPolicies(userId);
17011        } finally {
17012            Binder.restoreCallingIdentity(identity);
17013        }
17014    }
17015
17016    @Override
17017    public int getPreferredActivities(List<IntentFilter> outFilters,
17018            List<ComponentName> outActivities, String packageName) {
17019
17020        int num = 0;
17021        final int userId = UserHandle.getCallingUserId();
17022        // reader
17023        synchronized (mPackages) {
17024            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17025            if (pir != null) {
17026                final Iterator<PreferredActivity> it = pir.filterIterator();
17027                while (it.hasNext()) {
17028                    final PreferredActivity pa = it.next();
17029                    if (packageName == null
17030                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17031                                    && pa.mPref.mAlways)) {
17032                        if (outFilters != null) {
17033                            outFilters.add(new IntentFilter(pa));
17034                        }
17035                        if (outActivities != null) {
17036                            outActivities.add(pa.mPref.mComponent);
17037                        }
17038                    }
17039                }
17040            }
17041        }
17042
17043        return num;
17044    }
17045
17046    @Override
17047    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17048            int userId) {
17049        int callingUid = Binder.getCallingUid();
17050        if (callingUid != Process.SYSTEM_UID) {
17051            throw new SecurityException(
17052                    "addPersistentPreferredActivity can only be run by the system");
17053        }
17054        if (filter.countActions() == 0) {
17055            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17056            return;
17057        }
17058        synchronized (mPackages) {
17059            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17060                    ":");
17061            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17062            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17063                    new PersistentPreferredActivity(filter, activity));
17064            scheduleWritePackageRestrictionsLocked(userId);
17065        }
17066    }
17067
17068    @Override
17069    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17070        int callingUid = Binder.getCallingUid();
17071        if (callingUid != Process.SYSTEM_UID) {
17072            throw new SecurityException(
17073                    "clearPackagePersistentPreferredActivities can only be run by the system");
17074        }
17075        ArrayList<PersistentPreferredActivity> removed = null;
17076        boolean changed = false;
17077        synchronized (mPackages) {
17078            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17079                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17080                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17081                        .valueAt(i);
17082                if (userId != thisUserId) {
17083                    continue;
17084                }
17085                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17086                while (it.hasNext()) {
17087                    PersistentPreferredActivity ppa = it.next();
17088                    // Mark entry for removal only if it matches the package name.
17089                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17090                        if (removed == null) {
17091                            removed = new ArrayList<PersistentPreferredActivity>();
17092                        }
17093                        removed.add(ppa);
17094                    }
17095                }
17096                if (removed != null) {
17097                    for (int j=0; j<removed.size(); j++) {
17098                        PersistentPreferredActivity ppa = removed.get(j);
17099                        ppir.removeFilter(ppa);
17100                    }
17101                    changed = true;
17102                }
17103            }
17104
17105            if (changed) {
17106                scheduleWritePackageRestrictionsLocked(userId);
17107            }
17108        }
17109    }
17110
17111    /**
17112     * Common machinery for picking apart a restored XML blob and passing
17113     * it to a caller-supplied functor to be applied to the running system.
17114     */
17115    private void restoreFromXml(XmlPullParser parser, int userId,
17116            String expectedStartTag, BlobXmlRestorer functor)
17117            throws IOException, XmlPullParserException {
17118        int type;
17119        while ((type = parser.next()) != XmlPullParser.START_TAG
17120                && type != XmlPullParser.END_DOCUMENT) {
17121        }
17122        if (type != XmlPullParser.START_TAG) {
17123            // oops didn't find a start tag?!
17124            if (DEBUG_BACKUP) {
17125                Slog.e(TAG, "Didn't find start tag during restore");
17126            }
17127            return;
17128        }
17129Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17130        // this is supposed to be TAG_PREFERRED_BACKUP
17131        if (!expectedStartTag.equals(parser.getName())) {
17132            if (DEBUG_BACKUP) {
17133                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17134            }
17135            return;
17136        }
17137
17138        // skip interfering stuff, then we're aligned with the backing implementation
17139        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17140Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17141        functor.apply(parser, userId);
17142    }
17143
17144    private interface BlobXmlRestorer {
17145        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17146    }
17147
17148    /**
17149     * Non-Binder method, support for the backup/restore mechanism: write the
17150     * full set of preferred activities in its canonical XML format.  Returns the
17151     * XML output as a byte array, or null if there is none.
17152     */
17153    @Override
17154    public byte[] getPreferredActivityBackup(int userId) {
17155        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17156            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17157        }
17158
17159        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17160        try {
17161            final XmlSerializer serializer = new FastXmlSerializer();
17162            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17163            serializer.startDocument(null, true);
17164            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17165
17166            synchronized (mPackages) {
17167                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17168            }
17169
17170            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17171            serializer.endDocument();
17172            serializer.flush();
17173        } catch (Exception e) {
17174            if (DEBUG_BACKUP) {
17175                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17176            }
17177            return null;
17178        }
17179
17180        return dataStream.toByteArray();
17181    }
17182
17183    @Override
17184    public void restorePreferredActivities(byte[] backup, int userId) {
17185        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17186            throw new SecurityException("Only the system may call restorePreferredActivities()");
17187        }
17188
17189        try {
17190            final XmlPullParser parser = Xml.newPullParser();
17191            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17192            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17193                    new BlobXmlRestorer() {
17194                        @Override
17195                        public void apply(XmlPullParser parser, int userId)
17196                                throws XmlPullParserException, IOException {
17197                            synchronized (mPackages) {
17198                                mSettings.readPreferredActivitiesLPw(parser, userId);
17199                            }
17200                        }
17201                    } );
17202        } catch (Exception e) {
17203            if (DEBUG_BACKUP) {
17204                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17205            }
17206        }
17207    }
17208
17209    /**
17210     * Non-Binder method, support for the backup/restore mechanism: write the
17211     * default browser (etc) settings in its canonical XML format.  Returns the default
17212     * browser XML representation as a byte array, or null if there is none.
17213     */
17214    @Override
17215    public byte[] getDefaultAppsBackup(int userId) {
17216        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17217            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17218        }
17219
17220        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17221        try {
17222            final XmlSerializer serializer = new FastXmlSerializer();
17223            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17224            serializer.startDocument(null, true);
17225            serializer.startTag(null, TAG_DEFAULT_APPS);
17226
17227            synchronized (mPackages) {
17228                mSettings.writeDefaultAppsLPr(serializer, userId);
17229            }
17230
17231            serializer.endTag(null, TAG_DEFAULT_APPS);
17232            serializer.endDocument();
17233            serializer.flush();
17234        } catch (Exception e) {
17235            if (DEBUG_BACKUP) {
17236                Slog.e(TAG, "Unable to write default apps for backup", e);
17237            }
17238            return null;
17239        }
17240
17241        return dataStream.toByteArray();
17242    }
17243
17244    @Override
17245    public void restoreDefaultApps(byte[] backup, int userId) {
17246        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17247            throw new SecurityException("Only the system may call restoreDefaultApps()");
17248        }
17249
17250        try {
17251            final XmlPullParser parser = Xml.newPullParser();
17252            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17253            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17254                    new BlobXmlRestorer() {
17255                        @Override
17256                        public void apply(XmlPullParser parser, int userId)
17257                                throws XmlPullParserException, IOException {
17258                            synchronized (mPackages) {
17259                                mSettings.readDefaultAppsLPw(parser, userId);
17260                            }
17261                        }
17262                    } );
17263        } catch (Exception e) {
17264            if (DEBUG_BACKUP) {
17265                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17266            }
17267        }
17268    }
17269
17270    @Override
17271    public byte[] getIntentFilterVerificationBackup(int userId) {
17272        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17273            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17274        }
17275
17276        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17277        try {
17278            final XmlSerializer serializer = new FastXmlSerializer();
17279            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17280            serializer.startDocument(null, true);
17281            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17282
17283            synchronized (mPackages) {
17284                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17285            }
17286
17287            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17288            serializer.endDocument();
17289            serializer.flush();
17290        } catch (Exception e) {
17291            if (DEBUG_BACKUP) {
17292                Slog.e(TAG, "Unable to write default apps for backup", e);
17293            }
17294            return null;
17295        }
17296
17297        return dataStream.toByteArray();
17298    }
17299
17300    @Override
17301    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17302        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17303            throw new SecurityException("Only the system may call restorePreferredActivities()");
17304        }
17305
17306        try {
17307            final XmlPullParser parser = Xml.newPullParser();
17308            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17309            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17310                    new BlobXmlRestorer() {
17311                        @Override
17312                        public void apply(XmlPullParser parser, int userId)
17313                                throws XmlPullParserException, IOException {
17314                            synchronized (mPackages) {
17315                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17316                                mSettings.writeLPr();
17317                            }
17318                        }
17319                    } );
17320        } catch (Exception e) {
17321            if (DEBUG_BACKUP) {
17322                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17323            }
17324        }
17325    }
17326
17327    @Override
17328    public byte[] getPermissionGrantBackup(int userId) {
17329        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17330            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17331        }
17332
17333        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17334        try {
17335            final XmlSerializer serializer = new FastXmlSerializer();
17336            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17337            serializer.startDocument(null, true);
17338            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17339
17340            synchronized (mPackages) {
17341                serializeRuntimePermissionGrantsLPr(serializer, userId);
17342            }
17343
17344            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17345            serializer.endDocument();
17346            serializer.flush();
17347        } catch (Exception e) {
17348            if (DEBUG_BACKUP) {
17349                Slog.e(TAG, "Unable to write default apps for backup", e);
17350            }
17351            return null;
17352        }
17353
17354        return dataStream.toByteArray();
17355    }
17356
17357    @Override
17358    public void restorePermissionGrants(byte[] backup, int userId) {
17359        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17360            throw new SecurityException("Only the system may call restorePermissionGrants()");
17361        }
17362
17363        try {
17364            final XmlPullParser parser = Xml.newPullParser();
17365            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17366            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17367                    new BlobXmlRestorer() {
17368                        @Override
17369                        public void apply(XmlPullParser parser, int userId)
17370                                throws XmlPullParserException, IOException {
17371                            synchronized (mPackages) {
17372                                processRestoredPermissionGrantsLPr(parser, userId);
17373                            }
17374                        }
17375                    } );
17376        } catch (Exception e) {
17377            if (DEBUG_BACKUP) {
17378                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17379            }
17380        }
17381    }
17382
17383    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17384            throws IOException {
17385        serializer.startTag(null, TAG_ALL_GRANTS);
17386
17387        final int N = mSettings.mPackages.size();
17388        for (int i = 0; i < N; i++) {
17389            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17390            boolean pkgGrantsKnown = false;
17391
17392            PermissionsState packagePerms = ps.getPermissionsState();
17393
17394            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17395                final int grantFlags = state.getFlags();
17396                // only look at grants that are not system/policy fixed
17397                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17398                    final boolean isGranted = state.isGranted();
17399                    // And only back up the user-twiddled state bits
17400                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17401                        final String packageName = mSettings.mPackages.keyAt(i);
17402                        if (!pkgGrantsKnown) {
17403                            serializer.startTag(null, TAG_GRANT);
17404                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17405                            pkgGrantsKnown = true;
17406                        }
17407
17408                        final boolean userSet =
17409                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17410                        final boolean userFixed =
17411                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17412                        final boolean revoke =
17413                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17414
17415                        serializer.startTag(null, TAG_PERMISSION);
17416                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17417                        if (isGranted) {
17418                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17419                        }
17420                        if (userSet) {
17421                            serializer.attribute(null, ATTR_USER_SET, "true");
17422                        }
17423                        if (userFixed) {
17424                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17425                        }
17426                        if (revoke) {
17427                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17428                        }
17429                        serializer.endTag(null, TAG_PERMISSION);
17430                    }
17431                }
17432            }
17433
17434            if (pkgGrantsKnown) {
17435                serializer.endTag(null, TAG_GRANT);
17436            }
17437        }
17438
17439        serializer.endTag(null, TAG_ALL_GRANTS);
17440    }
17441
17442    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17443            throws XmlPullParserException, IOException {
17444        String pkgName = null;
17445        int outerDepth = parser.getDepth();
17446        int type;
17447        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17448                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17449            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17450                continue;
17451            }
17452
17453            final String tagName = parser.getName();
17454            if (tagName.equals(TAG_GRANT)) {
17455                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17456                if (DEBUG_BACKUP) {
17457                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17458                }
17459            } else if (tagName.equals(TAG_PERMISSION)) {
17460
17461                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17462                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17463
17464                int newFlagSet = 0;
17465                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17466                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17467                }
17468                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17469                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17470                }
17471                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17472                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17473                }
17474                if (DEBUG_BACKUP) {
17475                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17476                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17477                }
17478                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17479                if (ps != null) {
17480                    // Already installed so we apply the grant immediately
17481                    if (DEBUG_BACKUP) {
17482                        Slog.v(TAG, "        + already installed; applying");
17483                    }
17484                    PermissionsState perms = ps.getPermissionsState();
17485                    BasePermission bp = mSettings.mPermissions.get(permName);
17486                    if (bp != null) {
17487                        if (isGranted) {
17488                            perms.grantRuntimePermission(bp, userId);
17489                        }
17490                        if (newFlagSet != 0) {
17491                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17492                        }
17493                    }
17494                } else {
17495                    // Need to wait for post-restore install to apply the grant
17496                    if (DEBUG_BACKUP) {
17497                        Slog.v(TAG, "        - not yet installed; saving for later");
17498                    }
17499                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17500                            isGranted, newFlagSet, userId);
17501                }
17502            } else {
17503                PackageManagerService.reportSettingsProblem(Log.WARN,
17504                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17505                XmlUtils.skipCurrentTag(parser);
17506            }
17507        }
17508
17509        scheduleWriteSettingsLocked();
17510        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17511    }
17512
17513    @Override
17514    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17515            int sourceUserId, int targetUserId, int flags) {
17516        mContext.enforceCallingOrSelfPermission(
17517                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17518        int callingUid = Binder.getCallingUid();
17519        enforceOwnerRights(ownerPackage, callingUid);
17520        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17521        if (intentFilter.countActions() == 0) {
17522            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17523            return;
17524        }
17525        synchronized (mPackages) {
17526            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17527                    ownerPackage, targetUserId, flags);
17528            CrossProfileIntentResolver resolver =
17529                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17530            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17531            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17532            if (existing != null) {
17533                int size = existing.size();
17534                for (int i = 0; i < size; i++) {
17535                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17536                        return;
17537                    }
17538                }
17539            }
17540            resolver.addFilter(newFilter);
17541            scheduleWritePackageRestrictionsLocked(sourceUserId);
17542        }
17543    }
17544
17545    @Override
17546    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17547        mContext.enforceCallingOrSelfPermission(
17548                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17549        int callingUid = Binder.getCallingUid();
17550        enforceOwnerRights(ownerPackage, callingUid);
17551        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17552        synchronized (mPackages) {
17553            CrossProfileIntentResolver resolver =
17554                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17555            ArraySet<CrossProfileIntentFilter> set =
17556                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17557            for (CrossProfileIntentFilter filter : set) {
17558                if (filter.getOwnerPackage().equals(ownerPackage)) {
17559                    resolver.removeFilter(filter);
17560                }
17561            }
17562            scheduleWritePackageRestrictionsLocked(sourceUserId);
17563        }
17564    }
17565
17566    // Enforcing that callingUid is owning pkg on userId
17567    private void enforceOwnerRights(String pkg, int callingUid) {
17568        // The system owns everything.
17569        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17570            return;
17571        }
17572        int callingUserId = UserHandle.getUserId(callingUid);
17573        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17574        if (pi == null) {
17575            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17576                    + callingUserId);
17577        }
17578        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17579            throw new SecurityException("Calling uid " + callingUid
17580                    + " does not own package " + pkg);
17581        }
17582    }
17583
17584    @Override
17585    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17586        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17587    }
17588
17589    private Intent getHomeIntent() {
17590        Intent intent = new Intent(Intent.ACTION_MAIN);
17591        intent.addCategory(Intent.CATEGORY_HOME);
17592        return intent;
17593    }
17594
17595    private IntentFilter getHomeFilter() {
17596        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17597        filter.addCategory(Intent.CATEGORY_HOME);
17598        filter.addCategory(Intent.CATEGORY_DEFAULT);
17599        return filter;
17600    }
17601
17602    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17603            int userId) {
17604        Intent intent  = getHomeIntent();
17605        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17606                PackageManager.GET_META_DATA, userId);
17607        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17608                true, false, false, userId);
17609
17610        allHomeCandidates.clear();
17611        if (list != null) {
17612            for (ResolveInfo ri : list) {
17613                allHomeCandidates.add(ri);
17614            }
17615        }
17616        return (preferred == null || preferred.activityInfo == null)
17617                ? null
17618                : new ComponentName(preferred.activityInfo.packageName,
17619                        preferred.activityInfo.name);
17620    }
17621
17622    @Override
17623    public void setHomeActivity(ComponentName comp, int userId) {
17624        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17625        getHomeActivitiesAsUser(homeActivities, userId);
17626
17627        boolean found = false;
17628
17629        final int size = homeActivities.size();
17630        final ComponentName[] set = new ComponentName[size];
17631        for (int i = 0; i < size; i++) {
17632            final ResolveInfo candidate = homeActivities.get(i);
17633            final ActivityInfo info = candidate.activityInfo;
17634            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17635            set[i] = activityName;
17636            if (!found && activityName.equals(comp)) {
17637                found = true;
17638            }
17639        }
17640        if (!found) {
17641            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17642                    + userId);
17643        }
17644        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17645                set, comp, userId);
17646    }
17647
17648    private @Nullable String getSetupWizardPackageName() {
17649        final Intent intent = new Intent(Intent.ACTION_MAIN);
17650        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17651
17652        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17653                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17654                        | MATCH_DISABLED_COMPONENTS,
17655                UserHandle.myUserId());
17656        if (matches.size() == 1) {
17657            return matches.get(0).getComponentInfo().packageName;
17658        } else {
17659            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17660                    + ": matches=" + matches);
17661            return null;
17662        }
17663    }
17664
17665    @Override
17666    public void setApplicationEnabledSetting(String appPackageName,
17667            int newState, int flags, int userId, String callingPackage) {
17668        if (!sUserManager.exists(userId)) return;
17669        if (callingPackage == null) {
17670            callingPackage = Integer.toString(Binder.getCallingUid());
17671        }
17672        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17673    }
17674
17675    @Override
17676    public void setComponentEnabledSetting(ComponentName componentName,
17677            int newState, int flags, int userId) {
17678        if (!sUserManager.exists(userId)) return;
17679        setEnabledSetting(componentName.getPackageName(),
17680                componentName.getClassName(), newState, flags, userId, null);
17681    }
17682
17683    private void setEnabledSetting(final String packageName, String className, int newState,
17684            final int flags, int userId, String callingPackage) {
17685        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17686              || newState == COMPONENT_ENABLED_STATE_ENABLED
17687              || newState == COMPONENT_ENABLED_STATE_DISABLED
17688              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17689              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17690            throw new IllegalArgumentException("Invalid new component state: "
17691                    + newState);
17692        }
17693        PackageSetting pkgSetting;
17694        final int uid = Binder.getCallingUid();
17695        final int permission;
17696        if (uid == Process.SYSTEM_UID) {
17697            permission = PackageManager.PERMISSION_GRANTED;
17698        } else {
17699            permission = mContext.checkCallingOrSelfPermission(
17700                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17701        }
17702        enforceCrossUserPermission(uid, userId,
17703                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17704        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17705        boolean sendNow = false;
17706        boolean isApp = (className == null);
17707        String componentName = isApp ? packageName : className;
17708        int packageUid = -1;
17709        ArrayList<String> components;
17710
17711        // writer
17712        synchronized (mPackages) {
17713            pkgSetting = mSettings.mPackages.get(packageName);
17714            if (pkgSetting == null) {
17715                if (className == null) {
17716                    throw new IllegalArgumentException("Unknown package: " + packageName);
17717                }
17718                throw new IllegalArgumentException(
17719                        "Unknown component: " + packageName + "/" + className);
17720            }
17721        }
17722
17723        // Limit who can change which apps
17724        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17725            // Don't allow apps that don't have permission to modify other apps
17726            if (!allowedByPermission) {
17727                throw new SecurityException(
17728                        "Permission Denial: attempt to change component state from pid="
17729                        + Binder.getCallingPid()
17730                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17731            }
17732            // Don't allow changing profile and device owners.
17733            if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17734                throw new SecurityException("Cannot disable a device owner or a profile owner");
17735            }
17736        }
17737
17738        synchronized (mPackages) {
17739            if (uid == Process.SHELL_UID) {
17740                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17741                int oldState = pkgSetting.getEnabled(userId);
17742                if (className == null
17743                    &&
17744                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17745                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17746                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17747                    &&
17748                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17749                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17750                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17751                    // ok
17752                } else {
17753                    throw new SecurityException(
17754                            "Shell cannot change component state for " + packageName + "/"
17755                            + className + " to " + newState);
17756                }
17757            }
17758            if (className == null) {
17759                // We're dealing with an application/package level state change
17760                if (pkgSetting.getEnabled(userId) == newState) {
17761                    // Nothing to do
17762                    return;
17763                }
17764                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17765                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17766                    // Don't care about who enables an app.
17767                    callingPackage = null;
17768                }
17769                pkgSetting.setEnabled(newState, userId, callingPackage);
17770                // pkgSetting.pkg.mSetEnabled = newState;
17771            } else {
17772                // We're dealing with a component level state change
17773                // First, verify that this is a valid class name.
17774                PackageParser.Package pkg = pkgSetting.pkg;
17775                if (pkg == null || !pkg.hasComponentClassName(className)) {
17776                    if (pkg != null &&
17777                            pkg.applicationInfo.targetSdkVersion >=
17778                                    Build.VERSION_CODES.JELLY_BEAN) {
17779                        throw new IllegalArgumentException("Component class " + className
17780                                + " does not exist in " + packageName);
17781                    } else {
17782                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17783                                + className + " does not exist in " + packageName);
17784                    }
17785                }
17786                switch (newState) {
17787                case COMPONENT_ENABLED_STATE_ENABLED:
17788                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17789                        return;
17790                    }
17791                    break;
17792                case COMPONENT_ENABLED_STATE_DISABLED:
17793                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17794                        return;
17795                    }
17796                    break;
17797                case COMPONENT_ENABLED_STATE_DEFAULT:
17798                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17799                        return;
17800                    }
17801                    break;
17802                default:
17803                    Slog.e(TAG, "Invalid new component state: " + newState);
17804                    return;
17805                }
17806            }
17807            scheduleWritePackageRestrictionsLocked(userId);
17808            components = mPendingBroadcasts.get(userId, packageName);
17809            final boolean newPackage = components == null;
17810            if (newPackage) {
17811                components = new ArrayList<String>();
17812            }
17813            if (!components.contains(componentName)) {
17814                components.add(componentName);
17815            }
17816            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17817                sendNow = true;
17818                // Purge entry from pending broadcast list if another one exists already
17819                // since we are sending one right away.
17820                mPendingBroadcasts.remove(userId, packageName);
17821            } else {
17822                if (newPackage) {
17823                    mPendingBroadcasts.put(userId, packageName, components);
17824                }
17825                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17826                    // Schedule a message
17827                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17828                }
17829            }
17830        }
17831
17832        long callingId = Binder.clearCallingIdentity();
17833        try {
17834            if (sendNow) {
17835                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17836                sendPackageChangedBroadcast(packageName,
17837                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17838            }
17839        } finally {
17840            Binder.restoreCallingIdentity(callingId);
17841        }
17842    }
17843
17844    @Override
17845    public void flushPackageRestrictionsAsUser(int userId) {
17846        if (!sUserManager.exists(userId)) {
17847            return;
17848        }
17849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17850                false /* checkShell */, "flushPackageRestrictions");
17851        synchronized (mPackages) {
17852            mSettings.writePackageRestrictionsLPr(userId);
17853            mDirtyUsers.remove(userId);
17854            if (mDirtyUsers.isEmpty()) {
17855                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17856            }
17857        }
17858    }
17859
17860    private void sendPackageChangedBroadcast(String packageName,
17861            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17862        if (DEBUG_INSTALL)
17863            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17864                    + componentNames);
17865        Bundle extras = new Bundle(4);
17866        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17867        String nameList[] = new String[componentNames.size()];
17868        componentNames.toArray(nameList);
17869        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17870        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17871        extras.putInt(Intent.EXTRA_UID, packageUid);
17872        // If this is not reporting a change of the overall package, then only send it
17873        // to registered receivers.  We don't want to launch a swath of apps for every
17874        // little component state change.
17875        final int flags = !componentNames.contains(packageName)
17876                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17877        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17878                new int[] {UserHandle.getUserId(packageUid)});
17879    }
17880
17881    @Override
17882    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17883        if (!sUserManager.exists(userId)) return;
17884        final int uid = Binder.getCallingUid();
17885        final int permission = mContext.checkCallingOrSelfPermission(
17886                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17887        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17888        enforceCrossUserPermission(uid, userId,
17889                true /* requireFullPermission */, true /* checkShell */, "stop package");
17890        // writer
17891        synchronized (mPackages) {
17892            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17893                    allowedByPermission, uid, userId)) {
17894                scheduleWritePackageRestrictionsLocked(userId);
17895            }
17896        }
17897    }
17898
17899    @Override
17900    public String getInstallerPackageName(String packageName) {
17901        // reader
17902        synchronized (mPackages) {
17903            return mSettings.getInstallerPackageNameLPr(packageName);
17904        }
17905    }
17906
17907    public boolean isOrphaned(String packageName) {
17908        // reader
17909        synchronized (mPackages) {
17910            return mSettings.isOrphaned(packageName);
17911        }
17912    }
17913
17914    @Override
17915    public int getApplicationEnabledSetting(String packageName, int userId) {
17916        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17917        int uid = Binder.getCallingUid();
17918        enforceCrossUserPermission(uid, userId,
17919                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17920        // reader
17921        synchronized (mPackages) {
17922            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17923        }
17924    }
17925
17926    @Override
17927    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17928        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17929        int uid = Binder.getCallingUid();
17930        enforceCrossUserPermission(uid, userId,
17931                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17932        // reader
17933        synchronized (mPackages) {
17934            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17935        }
17936    }
17937
17938    @Override
17939    public void enterSafeMode() {
17940        enforceSystemOrRoot("Only the system can request entering safe mode");
17941
17942        if (!mSystemReady) {
17943            mSafeMode = true;
17944        }
17945    }
17946
17947    @Override
17948    public void systemReady() {
17949        mSystemReady = true;
17950
17951        // Read the compatibilty setting when the system is ready.
17952        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17953                mContext.getContentResolver(),
17954                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17955        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17956        if (DEBUG_SETTINGS) {
17957            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17958        }
17959
17960        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17961
17962        synchronized (mPackages) {
17963            // Verify that all of the preferred activity components actually
17964            // exist.  It is possible for applications to be updated and at
17965            // that point remove a previously declared activity component that
17966            // had been set as a preferred activity.  We try to clean this up
17967            // the next time we encounter that preferred activity, but it is
17968            // possible for the user flow to never be able to return to that
17969            // situation so here we do a sanity check to make sure we haven't
17970            // left any junk around.
17971            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17972            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17973                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17974                removed.clear();
17975                for (PreferredActivity pa : pir.filterSet()) {
17976                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17977                        removed.add(pa);
17978                    }
17979                }
17980                if (removed.size() > 0) {
17981                    for (int r=0; r<removed.size(); r++) {
17982                        PreferredActivity pa = removed.get(r);
17983                        Slog.w(TAG, "Removing dangling preferred activity: "
17984                                + pa.mPref.mComponent);
17985                        pir.removeFilter(pa);
17986                    }
17987                    mSettings.writePackageRestrictionsLPr(
17988                            mSettings.mPreferredActivities.keyAt(i));
17989                }
17990            }
17991
17992            for (int userId : UserManagerService.getInstance().getUserIds()) {
17993                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17994                    grantPermissionsUserIds = ArrayUtils.appendInt(
17995                            grantPermissionsUserIds, userId);
17996                }
17997            }
17998        }
17999        sUserManager.systemReady();
18000
18001        // If we upgraded grant all default permissions before kicking off.
18002        for (int userId : grantPermissionsUserIds) {
18003            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18004        }
18005
18006        // Kick off any messages waiting for system ready
18007        if (mPostSystemReadyMessages != null) {
18008            for (Message msg : mPostSystemReadyMessages) {
18009                msg.sendToTarget();
18010            }
18011            mPostSystemReadyMessages = null;
18012        }
18013
18014        // Watch for external volumes that come and go over time
18015        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18016        storage.registerListener(mStorageListener);
18017
18018        mInstallerService.systemReady();
18019        mPackageDexOptimizer.systemReady();
18020
18021        MountServiceInternal mountServiceInternal = LocalServices.getService(
18022                MountServiceInternal.class);
18023        mountServiceInternal.addExternalStoragePolicy(
18024                new MountServiceInternal.ExternalStorageMountPolicy() {
18025            @Override
18026            public int getMountMode(int uid, String packageName) {
18027                if (Process.isIsolated(uid)) {
18028                    return Zygote.MOUNT_EXTERNAL_NONE;
18029                }
18030                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18031                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18032                }
18033                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18034                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18035                }
18036                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18037                    return Zygote.MOUNT_EXTERNAL_READ;
18038                }
18039                return Zygote.MOUNT_EXTERNAL_WRITE;
18040            }
18041
18042            @Override
18043            public boolean hasExternalStorage(int uid, String packageName) {
18044                return true;
18045            }
18046        });
18047
18048        // Now that we're mostly running, clean up stale users and apps
18049        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18050        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18051    }
18052
18053    @Override
18054    public boolean isSafeMode() {
18055        return mSafeMode;
18056    }
18057
18058    @Override
18059    public boolean hasSystemUidErrors() {
18060        return mHasSystemUidErrors;
18061    }
18062
18063    static String arrayToString(int[] array) {
18064        StringBuffer buf = new StringBuffer(128);
18065        buf.append('[');
18066        if (array != null) {
18067            for (int i=0; i<array.length; i++) {
18068                if (i > 0) buf.append(", ");
18069                buf.append(array[i]);
18070            }
18071        }
18072        buf.append(']');
18073        return buf.toString();
18074    }
18075
18076    static class DumpState {
18077        public static final int DUMP_LIBS = 1 << 0;
18078        public static final int DUMP_FEATURES = 1 << 1;
18079        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18080        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18081        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18082        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18083        public static final int DUMP_PERMISSIONS = 1 << 6;
18084        public static final int DUMP_PACKAGES = 1 << 7;
18085        public static final int DUMP_SHARED_USERS = 1 << 8;
18086        public static final int DUMP_MESSAGES = 1 << 9;
18087        public static final int DUMP_PROVIDERS = 1 << 10;
18088        public static final int DUMP_VERIFIERS = 1 << 11;
18089        public static final int DUMP_PREFERRED = 1 << 12;
18090        public static final int DUMP_PREFERRED_XML = 1 << 13;
18091        public static final int DUMP_KEYSETS = 1 << 14;
18092        public static final int DUMP_VERSION = 1 << 15;
18093        public static final int DUMP_INSTALLS = 1 << 16;
18094        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18095        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18096        public static final int DUMP_FROZEN = 1 << 19;
18097        public static final int DUMP_DEXOPT = 1 << 20;
18098
18099        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18100
18101        private int mTypes;
18102
18103        private int mOptions;
18104
18105        private boolean mTitlePrinted;
18106
18107        private SharedUserSetting mSharedUser;
18108
18109        public boolean isDumping(int type) {
18110            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18111                return true;
18112            }
18113
18114            return (mTypes & type) != 0;
18115        }
18116
18117        public void setDump(int type) {
18118            mTypes |= type;
18119        }
18120
18121        public boolean isOptionEnabled(int option) {
18122            return (mOptions & option) != 0;
18123        }
18124
18125        public void setOptionEnabled(int option) {
18126            mOptions |= option;
18127        }
18128
18129        public boolean onTitlePrinted() {
18130            final boolean printed = mTitlePrinted;
18131            mTitlePrinted = true;
18132            return printed;
18133        }
18134
18135        public boolean getTitlePrinted() {
18136            return mTitlePrinted;
18137        }
18138
18139        public void setTitlePrinted(boolean enabled) {
18140            mTitlePrinted = enabled;
18141        }
18142
18143        public SharedUserSetting getSharedUser() {
18144            return mSharedUser;
18145        }
18146
18147        public void setSharedUser(SharedUserSetting user) {
18148            mSharedUser = user;
18149        }
18150    }
18151
18152    @Override
18153    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18154            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18155        (new PackageManagerShellCommand(this)).exec(
18156                this, in, out, err, args, resultReceiver);
18157    }
18158
18159    @Override
18160    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18161        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18162                != PackageManager.PERMISSION_GRANTED) {
18163            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18164                    + Binder.getCallingPid()
18165                    + ", uid=" + Binder.getCallingUid()
18166                    + " without permission "
18167                    + android.Manifest.permission.DUMP);
18168            return;
18169        }
18170
18171        DumpState dumpState = new DumpState();
18172        boolean fullPreferred = false;
18173        boolean checkin = false;
18174
18175        String packageName = null;
18176        ArraySet<String> permissionNames = null;
18177
18178        int opti = 0;
18179        while (opti < args.length) {
18180            String opt = args[opti];
18181            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18182                break;
18183            }
18184            opti++;
18185
18186            if ("-a".equals(opt)) {
18187                // Right now we only know how to print all.
18188            } else if ("-h".equals(opt)) {
18189                pw.println("Package manager dump options:");
18190                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18191                pw.println("    --checkin: dump for a checkin");
18192                pw.println("    -f: print details of intent filters");
18193                pw.println("    -h: print this help");
18194                pw.println("  cmd may be one of:");
18195                pw.println("    l[ibraries]: list known shared libraries");
18196                pw.println("    f[eatures]: list device features");
18197                pw.println("    k[eysets]: print known keysets");
18198                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18199                pw.println("    perm[issions]: dump permissions");
18200                pw.println("    permission [name ...]: dump declaration and use of given permission");
18201                pw.println("    pref[erred]: print preferred package settings");
18202                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18203                pw.println("    prov[iders]: dump content providers");
18204                pw.println("    p[ackages]: dump installed packages");
18205                pw.println("    s[hared-users]: dump shared user IDs");
18206                pw.println("    m[essages]: print collected runtime messages");
18207                pw.println("    v[erifiers]: print package verifier info");
18208                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18209                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18210                pw.println("    version: print database version info");
18211                pw.println("    write: write current settings now");
18212                pw.println("    installs: details about install sessions");
18213                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18214                pw.println("    dexopt: dump dexopt state");
18215                pw.println("    <package.name>: info about given package");
18216                return;
18217            } else if ("--checkin".equals(opt)) {
18218                checkin = true;
18219            } else if ("-f".equals(opt)) {
18220                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18221            } else {
18222                pw.println("Unknown argument: " + opt + "; use -h for help");
18223            }
18224        }
18225
18226        // Is the caller requesting to dump a particular piece of data?
18227        if (opti < args.length) {
18228            String cmd = args[opti];
18229            opti++;
18230            // Is this a package name?
18231            if ("android".equals(cmd) || cmd.contains(".")) {
18232                packageName = cmd;
18233                // When dumping a single package, we always dump all of its
18234                // filter information since the amount of data will be reasonable.
18235                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18236            } else if ("check-permission".equals(cmd)) {
18237                if (opti >= args.length) {
18238                    pw.println("Error: check-permission missing permission argument");
18239                    return;
18240                }
18241                String perm = args[opti];
18242                opti++;
18243                if (opti >= args.length) {
18244                    pw.println("Error: check-permission missing package argument");
18245                    return;
18246                }
18247                String pkg = args[opti];
18248                opti++;
18249                int user = UserHandle.getUserId(Binder.getCallingUid());
18250                if (opti < args.length) {
18251                    try {
18252                        user = Integer.parseInt(args[opti]);
18253                    } catch (NumberFormatException e) {
18254                        pw.println("Error: check-permission user argument is not a number: "
18255                                + args[opti]);
18256                        return;
18257                    }
18258                }
18259                pw.println(checkPermission(perm, pkg, user));
18260                return;
18261            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18262                dumpState.setDump(DumpState.DUMP_LIBS);
18263            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18264                dumpState.setDump(DumpState.DUMP_FEATURES);
18265            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18266                if (opti >= args.length) {
18267                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18268                            | DumpState.DUMP_SERVICE_RESOLVERS
18269                            | DumpState.DUMP_RECEIVER_RESOLVERS
18270                            | DumpState.DUMP_CONTENT_RESOLVERS);
18271                } else {
18272                    while (opti < args.length) {
18273                        String name = args[opti];
18274                        if ("a".equals(name) || "activity".equals(name)) {
18275                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18276                        } else if ("s".equals(name) || "service".equals(name)) {
18277                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18278                        } else if ("r".equals(name) || "receiver".equals(name)) {
18279                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18280                        } else if ("c".equals(name) || "content".equals(name)) {
18281                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18282                        } else {
18283                            pw.println("Error: unknown resolver table type: " + name);
18284                            return;
18285                        }
18286                        opti++;
18287                    }
18288                }
18289            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18290                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18291            } else if ("permission".equals(cmd)) {
18292                if (opti >= args.length) {
18293                    pw.println("Error: permission requires permission name");
18294                    return;
18295                }
18296                permissionNames = new ArraySet<>();
18297                while (opti < args.length) {
18298                    permissionNames.add(args[opti]);
18299                    opti++;
18300                }
18301                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18302                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18303            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18304                dumpState.setDump(DumpState.DUMP_PREFERRED);
18305            } else if ("preferred-xml".equals(cmd)) {
18306                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18307                if (opti < args.length && "--full".equals(args[opti])) {
18308                    fullPreferred = true;
18309                    opti++;
18310                }
18311            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18312                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18313            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18314                dumpState.setDump(DumpState.DUMP_PACKAGES);
18315            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18316                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18317            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18318                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18319            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18320                dumpState.setDump(DumpState.DUMP_MESSAGES);
18321            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18322                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18323            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18324                    || "intent-filter-verifiers".equals(cmd)) {
18325                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18326            } else if ("version".equals(cmd)) {
18327                dumpState.setDump(DumpState.DUMP_VERSION);
18328            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18329                dumpState.setDump(DumpState.DUMP_KEYSETS);
18330            } else if ("installs".equals(cmd)) {
18331                dumpState.setDump(DumpState.DUMP_INSTALLS);
18332            } else if ("frozen".equals(cmd)) {
18333                dumpState.setDump(DumpState.DUMP_FROZEN);
18334            } else if ("dexopt".equals(cmd)) {
18335                dumpState.setDump(DumpState.DUMP_DEXOPT);
18336            } else if ("write".equals(cmd)) {
18337                synchronized (mPackages) {
18338                    mSettings.writeLPr();
18339                    pw.println("Settings written.");
18340                    return;
18341                }
18342            }
18343        }
18344
18345        if (checkin) {
18346            pw.println("vers,1");
18347        }
18348
18349        // reader
18350        synchronized (mPackages) {
18351            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18352                if (!checkin) {
18353                    if (dumpState.onTitlePrinted())
18354                        pw.println();
18355                    pw.println("Database versions:");
18356                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18357                }
18358            }
18359
18360            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18361                if (!checkin) {
18362                    if (dumpState.onTitlePrinted())
18363                        pw.println();
18364                    pw.println("Verifiers:");
18365                    pw.print("  Required: ");
18366                    pw.print(mRequiredVerifierPackage);
18367                    pw.print(" (uid=");
18368                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18369                            UserHandle.USER_SYSTEM));
18370                    pw.println(")");
18371                } else if (mRequiredVerifierPackage != null) {
18372                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18373                    pw.print(",");
18374                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18375                            UserHandle.USER_SYSTEM));
18376                }
18377            }
18378
18379            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18380                    packageName == null) {
18381                if (mIntentFilterVerifierComponent != null) {
18382                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18383                    if (!checkin) {
18384                        if (dumpState.onTitlePrinted())
18385                            pw.println();
18386                        pw.println("Intent Filter Verifier:");
18387                        pw.print("  Using: ");
18388                        pw.print(verifierPackageName);
18389                        pw.print(" (uid=");
18390                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18391                                UserHandle.USER_SYSTEM));
18392                        pw.println(")");
18393                    } else if (verifierPackageName != null) {
18394                        pw.print("ifv,"); pw.print(verifierPackageName);
18395                        pw.print(",");
18396                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18397                                UserHandle.USER_SYSTEM));
18398                    }
18399                } else {
18400                    pw.println();
18401                    pw.println("No Intent Filter Verifier available!");
18402                }
18403            }
18404
18405            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18406                boolean printedHeader = false;
18407                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18408                while (it.hasNext()) {
18409                    String name = it.next();
18410                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18411                    if (!checkin) {
18412                        if (!printedHeader) {
18413                            if (dumpState.onTitlePrinted())
18414                                pw.println();
18415                            pw.println("Libraries:");
18416                            printedHeader = true;
18417                        }
18418                        pw.print("  ");
18419                    } else {
18420                        pw.print("lib,");
18421                    }
18422                    pw.print(name);
18423                    if (!checkin) {
18424                        pw.print(" -> ");
18425                    }
18426                    if (ent.path != null) {
18427                        if (!checkin) {
18428                            pw.print("(jar) ");
18429                            pw.print(ent.path);
18430                        } else {
18431                            pw.print(",jar,");
18432                            pw.print(ent.path);
18433                        }
18434                    } else {
18435                        if (!checkin) {
18436                            pw.print("(apk) ");
18437                            pw.print(ent.apk);
18438                        } else {
18439                            pw.print(",apk,");
18440                            pw.print(ent.apk);
18441                        }
18442                    }
18443                    pw.println();
18444                }
18445            }
18446
18447            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18448                if (dumpState.onTitlePrinted())
18449                    pw.println();
18450                if (!checkin) {
18451                    pw.println("Features:");
18452                }
18453
18454                for (FeatureInfo feat : mAvailableFeatures.values()) {
18455                    if (checkin) {
18456                        pw.print("feat,");
18457                        pw.print(feat.name);
18458                        pw.print(",");
18459                        pw.println(feat.version);
18460                    } else {
18461                        pw.print("  ");
18462                        pw.print(feat.name);
18463                        if (feat.version > 0) {
18464                            pw.print(" version=");
18465                            pw.print(feat.version);
18466                        }
18467                        pw.println();
18468                    }
18469                }
18470            }
18471
18472            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18473                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18474                        : "Activity Resolver Table:", "  ", packageName,
18475                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18476                    dumpState.setTitlePrinted(true);
18477                }
18478            }
18479            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18480                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18481                        : "Receiver Resolver Table:", "  ", packageName,
18482                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18483                    dumpState.setTitlePrinted(true);
18484                }
18485            }
18486            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18487                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18488                        : "Service Resolver Table:", "  ", packageName,
18489                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18490                    dumpState.setTitlePrinted(true);
18491                }
18492            }
18493            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18494                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18495                        : "Provider Resolver Table:", "  ", packageName,
18496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18497                    dumpState.setTitlePrinted(true);
18498                }
18499            }
18500
18501            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18502                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18503                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18504                    int user = mSettings.mPreferredActivities.keyAt(i);
18505                    if (pir.dump(pw,
18506                            dumpState.getTitlePrinted()
18507                                ? "\nPreferred Activities User " + user + ":"
18508                                : "Preferred Activities User " + user + ":", "  ",
18509                            packageName, true, false)) {
18510                        dumpState.setTitlePrinted(true);
18511                    }
18512                }
18513            }
18514
18515            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18516                pw.flush();
18517                FileOutputStream fout = new FileOutputStream(fd);
18518                BufferedOutputStream str = new BufferedOutputStream(fout);
18519                XmlSerializer serializer = new FastXmlSerializer();
18520                try {
18521                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18522                    serializer.startDocument(null, true);
18523                    serializer.setFeature(
18524                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18525                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18526                    serializer.endDocument();
18527                    serializer.flush();
18528                } catch (IllegalArgumentException e) {
18529                    pw.println("Failed writing: " + e);
18530                } catch (IllegalStateException e) {
18531                    pw.println("Failed writing: " + e);
18532                } catch (IOException e) {
18533                    pw.println("Failed writing: " + e);
18534                }
18535            }
18536
18537            if (!checkin
18538                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18539                    && packageName == null) {
18540                pw.println();
18541                int count = mSettings.mPackages.size();
18542                if (count == 0) {
18543                    pw.println("No applications!");
18544                    pw.println();
18545                } else {
18546                    final String prefix = "  ";
18547                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18548                    if (allPackageSettings.size() == 0) {
18549                        pw.println("No domain preferred apps!");
18550                        pw.println();
18551                    } else {
18552                        pw.println("App verification status:");
18553                        pw.println();
18554                        count = 0;
18555                        for (PackageSetting ps : allPackageSettings) {
18556                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18557                            if (ivi == null || ivi.getPackageName() == null) continue;
18558                            pw.println(prefix + "Package: " + ivi.getPackageName());
18559                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18560                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18561                            pw.println();
18562                            count++;
18563                        }
18564                        if (count == 0) {
18565                            pw.println(prefix + "No app verification established.");
18566                            pw.println();
18567                        }
18568                        for (int userId : sUserManager.getUserIds()) {
18569                            pw.println("App linkages for user " + userId + ":");
18570                            pw.println();
18571                            count = 0;
18572                            for (PackageSetting ps : allPackageSettings) {
18573                                final long status = ps.getDomainVerificationStatusForUser(userId);
18574                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18575                                    continue;
18576                                }
18577                                pw.println(prefix + "Package: " + ps.name);
18578                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18579                                String statusStr = IntentFilterVerificationInfo.
18580                                        getStatusStringFromValue(status);
18581                                pw.println(prefix + "Status:  " + statusStr);
18582                                pw.println();
18583                                count++;
18584                            }
18585                            if (count == 0) {
18586                                pw.println(prefix + "No configured app linkages.");
18587                                pw.println();
18588                            }
18589                        }
18590                    }
18591                }
18592            }
18593
18594            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18595                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18596                if (packageName == null && permissionNames == null) {
18597                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18598                        if (iperm == 0) {
18599                            if (dumpState.onTitlePrinted())
18600                                pw.println();
18601                            pw.println("AppOp Permissions:");
18602                        }
18603                        pw.print("  AppOp Permission ");
18604                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18605                        pw.println(":");
18606                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18607                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18608                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18609                        }
18610                    }
18611                }
18612            }
18613
18614            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18615                boolean printedSomething = false;
18616                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18617                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18618                        continue;
18619                    }
18620                    if (!printedSomething) {
18621                        if (dumpState.onTitlePrinted())
18622                            pw.println();
18623                        pw.println("Registered ContentProviders:");
18624                        printedSomething = true;
18625                    }
18626                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18627                    pw.print("    "); pw.println(p.toString());
18628                }
18629                printedSomething = false;
18630                for (Map.Entry<String, PackageParser.Provider> entry :
18631                        mProvidersByAuthority.entrySet()) {
18632                    PackageParser.Provider p = entry.getValue();
18633                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18634                        continue;
18635                    }
18636                    if (!printedSomething) {
18637                        if (dumpState.onTitlePrinted())
18638                            pw.println();
18639                        pw.println("ContentProvider Authorities:");
18640                        printedSomething = true;
18641                    }
18642                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18643                    pw.print("    "); pw.println(p.toString());
18644                    if (p.info != null && p.info.applicationInfo != null) {
18645                        final String appInfo = p.info.applicationInfo.toString();
18646                        pw.print("      applicationInfo="); pw.println(appInfo);
18647                    }
18648                }
18649            }
18650
18651            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18652                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18653            }
18654
18655            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18656                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18657            }
18658
18659            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18660                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18661            }
18662
18663            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18664                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18665            }
18666
18667            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18668                // XXX should handle packageName != null by dumping only install data that
18669                // the given package is involved with.
18670                if (dumpState.onTitlePrinted()) pw.println();
18671                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18672            }
18673
18674            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18675                // XXX should handle packageName != null by dumping only install data that
18676                // the given package is involved with.
18677                if (dumpState.onTitlePrinted()) pw.println();
18678
18679                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18680                ipw.println();
18681                ipw.println("Frozen packages:");
18682                ipw.increaseIndent();
18683                if (mFrozenPackages.size() == 0) {
18684                    ipw.println("(none)");
18685                } else {
18686                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18687                        ipw.println(mFrozenPackages.valueAt(i));
18688                    }
18689                }
18690                ipw.decreaseIndent();
18691            }
18692
18693            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18694                if (dumpState.onTitlePrinted()) pw.println();
18695                dumpDexoptStateLPr(pw, packageName);
18696            }
18697
18698            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18699                if (dumpState.onTitlePrinted()) pw.println();
18700                mSettings.dumpReadMessagesLPr(pw, dumpState);
18701
18702                pw.println();
18703                pw.println("Package warning messages:");
18704                BufferedReader in = null;
18705                String line = null;
18706                try {
18707                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18708                    while ((line = in.readLine()) != null) {
18709                        if (line.contains("ignored: updated version")) continue;
18710                        pw.println(line);
18711                    }
18712                } catch (IOException ignored) {
18713                } finally {
18714                    IoUtils.closeQuietly(in);
18715                }
18716            }
18717
18718            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18719                BufferedReader in = null;
18720                String line = null;
18721                try {
18722                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18723                    while ((line = in.readLine()) != null) {
18724                        if (line.contains("ignored: updated version")) continue;
18725                        pw.print("msg,");
18726                        pw.println(line);
18727                    }
18728                } catch (IOException ignored) {
18729                } finally {
18730                    IoUtils.closeQuietly(in);
18731                }
18732            }
18733        }
18734    }
18735
18736    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18737        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18738        ipw.println();
18739        ipw.println("Dexopt state:");
18740        ipw.increaseIndent();
18741        Collection<PackageParser.Package> packages = null;
18742        if (packageName != null) {
18743            PackageParser.Package targetPackage = mPackages.get(packageName);
18744            if (targetPackage != null) {
18745                packages = Collections.singletonList(targetPackage);
18746            } else {
18747                ipw.println("Unable to find package: " + packageName);
18748                return;
18749            }
18750        } else {
18751            packages = mPackages.values();
18752        }
18753
18754        for (PackageParser.Package pkg : packages) {
18755            ipw.println("[" + pkg.packageName + "]");
18756            ipw.increaseIndent();
18757            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18758            ipw.decreaseIndent();
18759        }
18760    }
18761
18762    private String dumpDomainString(String packageName) {
18763        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18764                .getList();
18765        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18766
18767        ArraySet<String> result = new ArraySet<>();
18768        if (iviList.size() > 0) {
18769            for (IntentFilterVerificationInfo ivi : iviList) {
18770                for (String host : ivi.getDomains()) {
18771                    result.add(host);
18772                }
18773            }
18774        }
18775        if (filters != null && filters.size() > 0) {
18776            for (IntentFilter filter : filters) {
18777                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18778                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18779                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18780                    result.addAll(filter.getHostsList());
18781                }
18782            }
18783        }
18784
18785        StringBuilder sb = new StringBuilder(result.size() * 16);
18786        for (String domain : result) {
18787            if (sb.length() > 0) sb.append(" ");
18788            sb.append(domain);
18789        }
18790        return sb.toString();
18791    }
18792
18793    // ------- apps on sdcard specific code -------
18794    static final boolean DEBUG_SD_INSTALL = false;
18795
18796    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18797
18798    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18799
18800    private boolean mMediaMounted = false;
18801
18802    static String getEncryptKey() {
18803        try {
18804            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18805                    SD_ENCRYPTION_KEYSTORE_NAME);
18806            if (sdEncKey == null) {
18807                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18808                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18809                if (sdEncKey == null) {
18810                    Slog.e(TAG, "Failed to create encryption keys");
18811                    return null;
18812                }
18813            }
18814            return sdEncKey;
18815        } catch (NoSuchAlgorithmException nsae) {
18816            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18817            return null;
18818        } catch (IOException ioe) {
18819            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18820            return null;
18821        }
18822    }
18823
18824    /*
18825     * Update media status on PackageManager.
18826     */
18827    @Override
18828    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18829        int callingUid = Binder.getCallingUid();
18830        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18831            throw new SecurityException("Media status can only be updated by the system");
18832        }
18833        // reader; this apparently protects mMediaMounted, but should probably
18834        // be a different lock in that case.
18835        synchronized (mPackages) {
18836            Log.i(TAG, "Updating external media status from "
18837                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18838                    + (mediaStatus ? "mounted" : "unmounted"));
18839            if (DEBUG_SD_INSTALL)
18840                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18841                        + ", mMediaMounted=" + mMediaMounted);
18842            if (mediaStatus == mMediaMounted) {
18843                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18844                        : 0, -1);
18845                mHandler.sendMessage(msg);
18846                return;
18847            }
18848            mMediaMounted = mediaStatus;
18849        }
18850        // Queue up an async operation since the package installation may take a
18851        // little while.
18852        mHandler.post(new Runnable() {
18853            public void run() {
18854                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18855            }
18856        });
18857    }
18858
18859    /**
18860     * Called by MountService when the initial ASECs to scan are available.
18861     * Should block until all the ASEC containers are finished being scanned.
18862     */
18863    public void scanAvailableAsecs() {
18864        updateExternalMediaStatusInner(true, false, false);
18865    }
18866
18867    /*
18868     * Collect information of applications on external media, map them against
18869     * existing containers and update information based on current mount status.
18870     * Please note that we always have to report status if reportStatus has been
18871     * set to true especially when unloading packages.
18872     */
18873    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18874            boolean externalStorage) {
18875        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18876        int[] uidArr = EmptyArray.INT;
18877
18878        final String[] list = PackageHelper.getSecureContainerList();
18879        if (ArrayUtils.isEmpty(list)) {
18880            Log.i(TAG, "No secure containers found");
18881        } else {
18882            // Process list of secure containers and categorize them
18883            // as active or stale based on their package internal state.
18884
18885            // reader
18886            synchronized (mPackages) {
18887                for (String cid : list) {
18888                    // Leave stages untouched for now; installer service owns them
18889                    if (PackageInstallerService.isStageName(cid)) continue;
18890
18891                    if (DEBUG_SD_INSTALL)
18892                        Log.i(TAG, "Processing container " + cid);
18893                    String pkgName = getAsecPackageName(cid);
18894                    if (pkgName == null) {
18895                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18896                        continue;
18897                    }
18898                    if (DEBUG_SD_INSTALL)
18899                        Log.i(TAG, "Looking for pkg : " + pkgName);
18900
18901                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18902                    if (ps == null) {
18903                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18904                        continue;
18905                    }
18906
18907                    /*
18908                     * Skip packages that are not external if we're unmounting
18909                     * external storage.
18910                     */
18911                    if (externalStorage && !isMounted && !isExternal(ps)) {
18912                        continue;
18913                    }
18914
18915                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18916                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18917                    // The package status is changed only if the code path
18918                    // matches between settings and the container id.
18919                    if (ps.codePathString != null
18920                            && ps.codePathString.startsWith(args.getCodePath())) {
18921                        if (DEBUG_SD_INSTALL) {
18922                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18923                                    + " at code path: " + ps.codePathString);
18924                        }
18925
18926                        // We do have a valid package installed on sdcard
18927                        processCids.put(args, ps.codePathString);
18928                        final int uid = ps.appId;
18929                        if (uid != -1) {
18930                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18931                        }
18932                    } else {
18933                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18934                                + ps.codePathString);
18935                    }
18936                }
18937            }
18938
18939            Arrays.sort(uidArr);
18940        }
18941
18942        // Process packages with valid entries.
18943        if (isMounted) {
18944            if (DEBUG_SD_INSTALL)
18945                Log.i(TAG, "Loading packages");
18946            loadMediaPackages(processCids, uidArr, externalStorage);
18947            startCleaningPackages();
18948            mInstallerService.onSecureContainersAvailable();
18949        } else {
18950            if (DEBUG_SD_INSTALL)
18951                Log.i(TAG, "Unloading packages");
18952            unloadMediaPackages(processCids, uidArr, reportStatus);
18953        }
18954    }
18955
18956    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18957            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18958        final int size = infos.size();
18959        final String[] packageNames = new String[size];
18960        final int[] packageUids = new int[size];
18961        for (int i = 0; i < size; i++) {
18962            final ApplicationInfo info = infos.get(i);
18963            packageNames[i] = info.packageName;
18964            packageUids[i] = info.uid;
18965        }
18966        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18967                finishedReceiver);
18968    }
18969
18970    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18971            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18972        sendResourcesChangedBroadcast(mediaStatus, replacing,
18973                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18974    }
18975
18976    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18977            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18978        int size = pkgList.length;
18979        if (size > 0) {
18980            // Send broadcasts here
18981            Bundle extras = new Bundle();
18982            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18983            if (uidArr != null) {
18984                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18985            }
18986            if (replacing) {
18987                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18988            }
18989            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18990                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18991            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18992        }
18993    }
18994
18995   /*
18996     * Look at potentially valid container ids from processCids If package
18997     * information doesn't match the one on record or package scanning fails,
18998     * the cid is added to list of removeCids. We currently don't delete stale
18999     * containers.
19000     */
19001    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19002            boolean externalStorage) {
19003        ArrayList<String> pkgList = new ArrayList<String>();
19004        Set<AsecInstallArgs> keys = processCids.keySet();
19005
19006        for (AsecInstallArgs args : keys) {
19007            String codePath = processCids.get(args);
19008            if (DEBUG_SD_INSTALL)
19009                Log.i(TAG, "Loading container : " + args.cid);
19010            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19011            try {
19012                // Make sure there are no container errors first.
19013                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19014                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19015                            + " when installing from sdcard");
19016                    continue;
19017                }
19018                // Check code path here.
19019                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19020                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19021                            + " does not match one in settings " + codePath);
19022                    continue;
19023                }
19024                // Parse package
19025                int parseFlags = mDefParseFlags;
19026                if (args.isExternalAsec()) {
19027                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19028                }
19029                if (args.isFwdLocked()) {
19030                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19031                }
19032
19033                synchronized (mInstallLock) {
19034                    PackageParser.Package pkg = null;
19035                    try {
19036                        // Sadly we don't know the package name yet to freeze it
19037                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19038                                SCAN_IGNORE_FROZEN, 0, null);
19039                    } catch (PackageManagerException e) {
19040                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19041                    }
19042                    // Scan the package
19043                    if (pkg != null) {
19044                        /*
19045                         * TODO why is the lock being held? doPostInstall is
19046                         * called in other places without the lock. This needs
19047                         * to be straightened out.
19048                         */
19049                        // writer
19050                        synchronized (mPackages) {
19051                            retCode = PackageManager.INSTALL_SUCCEEDED;
19052                            pkgList.add(pkg.packageName);
19053                            // Post process args
19054                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19055                                    pkg.applicationInfo.uid);
19056                        }
19057                    } else {
19058                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19059                    }
19060                }
19061
19062            } finally {
19063                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19064                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19065                }
19066            }
19067        }
19068        // writer
19069        synchronized (mPackages) {
19070            // If the platform SDK has changed since the last time we booted,
19071            // we need to re-grant app permission to catch any new ones that
19072            // appear. This is really a hack, and means that apps can in some
19073            // cases get permissions that the user didn't initially explicitly
19074            // allow... it would be nice to have some better way to handle
19075            // this situation.
19076            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19077                    : mSettings.getInternalVersion();
19078            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19079                    : StorageManager.UUID_PRIVATE_INTERNAL;
19080
19081            int updateFlags = UPDATE_PERMISSIONS_ALL;
19082            if (ver.sdkVersion != mSdkVersion) {
19083                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19084                        + mSdkVersion + "; regranting permissions for external");
19085                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19086            }
19087            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19088
19089            // Yay, everything is now upgraded
19090            ver.forceCurrent();
19091
19092            // can downgrade to reader
19093            // Persist settings
19094            mSettings.writeLPr();
19095        }
19096        // Send a broadcast to let everyone know we are done processing
19097        if (pkgList.size() > 0) {
19098            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19099        }
19100    }
19101
19102   /*
19103     * Utility method to unload a list of specified containers
19104     */
19105    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19106        // Just unmount all valid containers.
19107        for (AsecInstallArgs arg : cidArgs) {
19108            synchronized (mInstallLock) {
19109                arg.doPostDeleteLI(false);
19110           }
19111       }
19112   }
19113
19114    /*
19115     * Unload packages mounted on external media. This involves deleting package
19116     * data from internal structures, sending broadcasts about disabled packages,
19117     * gc'ing to free up references, unmounting all secure containers
19118     * corresponding to packages on external media, and posting a
19119     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19120     * that we always have to post this message if status has been requested no
19121     * matter what.
19122     */
19123    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19124            final boolean reportStatus) {
19125        if (DEBUG_SD_INSTALL)
19126            Log.i(TAG, "unloading media packages");
19127        ArrayList<String> pkgList = new ArrayList<String>();
19128        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19129        final Set<AsecInstallArgs> keys = processCids.keySet();
19130        for (AsecInstallArgs args : keys) {
19131            String pkgName = args.getPackageName();
19132            if (DEBUG_SD_INSTALL)
19133                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19134            // Delete package internally
19135            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19136            synchronized (mInstallLock) {
19137                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19138                final boolean res;
19139                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19140                        "unloadMediaPackages")) {
19141                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19142                            null);
19143                }
19144                if (res) {
19145                    pkgList.add(pkgName);
19146                } else {
19147                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19148                    failedList.add(args);
19149                }
19150            }
19151        }
19152
19153        // reader
19154        synchronized (mPackages) {
19155            // We didn't update the settings after removing each package;
19156            // write them now for all packages.
19157            mSettings.writeLPr();
19158        }
19159
19160        // We have to absolutely send UPDATED_MEDIA_STATUS only
19161        // after confirming that all the receivers processed the ordered
19162        // broadcast when packages get disabled, force a gc to clean things up.
19163        // and unload all the containers.
19164        if (pkgList.size() > 0) {
19165            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19166                    new IIntentReceiver.Stub() {
19167                public void performReceive(Intent intent, int resultCode, String data,
19168                        Bundle extras, boolean ordered, boolean sticky,
19169                        int sendingUser) throws RemoteException {
19170                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19171                            reportStatus ? 1 : 0, 1, keys);
19172                    mHandler.sendMessage(msg);
19173                }
19174            });
19175        } else {
19176            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19177                    keys);
19178            mHandler.sendMessage(msg);
19179        }
19180    }
19181
19182    private void loadPrivatePackages(final VolumeInfo vol) {
19183        mHandler.post(new Runnable() {
19184            @Override
19185            public void run() {
19186                loadPrivatePackagesInner(vol);
19187            }
19188        });
19189    }
19190
19191    private void loadPrivatePackagesInner(VolumeInfo vol) {
19192        final String volumeUuid = vol.fsUuid;
19193        if (TextUtils.isEmpty(volumeUuid)) {
19194            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19195            return;
19196        }
19197
19198        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19199        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19200        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19201
19202        final VersionInfo ver;
19203        final List<PackageSetting> packages;
19204        synchronized (mPackages) {
19205            ver = mSettings.findOrCreateVersion(volumeUuid);
19206            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19207        }
19208
19209        for (PackageSetting ps : packages) {
19210            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19211            synchronized (mInstallLock) {
19212                final PackageParser.Package pkg;
19213                try {
19214                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19215                    loaded.add(pkg.applicationInfo);
19216
19217                } catch (PackageManagerException e) {
19218                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19219                }
19220
19221                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19222                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19223                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19224                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19225                }
19226            }
19227        }
19228
19229        // Reconcile app data for all started/unlocked users
19230        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19231        final UserManager um = mContext.getSystemService(UserManager.class);
19232        UserManagerInternal umInternal = getUserManagerInternal();
19233        for (UserInfo user : um.getUsers()) {
19234            final int flags;
19235            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19236                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19237            } else if (umInternal.isUserRunning(user.id)) {
19238                flags = StorageManager.FLAG_STORAGE_DE;
19239            } else {
19240                continue;
19241            }
19242
19243            try {
19244                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19245                synchronized (mInstallLock) {
19246                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19247                }
19248            } catch (IllegalStateException e) {
19249                // Device was probably ejected, and we'll process that event momentarily
19250                Slog.w(TAG, "Failed to prepare storage: " + e);
19251            }
19252        }
19253
19254        synchronized (mPackages) {
19255            int updateFlags = UPDATE_PERMISSIONS_ALL;
19256            if (ver.sdkVersion != mSdkVersion) {
19257                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19258                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19259                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19260            }
19261            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19262
19263            // Yay, everything is now upgraded
19264            ver.forceCurrent();
19265
19266            mSettings.writeLPr();
19267        }
19268
19269        for (PackageFreezer freezer : freezers) {
19270            freezer.close();
19271        }
19272
19273        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19274        sendResourcesChangedBroadcast(true, false, loaded, null);
19275    }
19276
19277    private void unloadPrivatePackages(final VolumeInfo vol) {
19278        mHandler.post(new Runnable() {
19279            @Override
19280            public void run() {
19281                unloadPrivatePackagesInner(vol);
19282            }
19283        });
19284    }
19285
19286    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19287        final String volumeUuid = vol.fsUuid;
19288        if (TextUtils.isEmpty(volumeUuid)) {
19289            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19290            return;
19291        }
19292
19293        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19294        synchronized (mInstallLock) {
19295        synchronized (mPackages) {
19296            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19297            for (PackageSetting ps : packages) {
19298                if (ps.pkg == null) continue;
19299
19300                final ApplicationInfo info = ps.pkg.applicationInfo;
19301                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19302                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19303
19304                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19305                        "unloadPrivatePackagesInner")) {
19306                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19307                            false, null)) {
19308                        unloaded.add(info);
19309                    } else {
19310                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19311                    }
19312                }
19313
19314                // Try very hard to release any references to this package
19315                // so we don't risk the system server being killed due to
19316                // open FDs
19317                AttributeCache.instance().removePackage(ps.name);
19318            }
19319
19320            mSettings.writeLPr();
19321        }
19322        }
19323
19324        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19325        sendResourcesChangedBroadcast(false, false, unloaded, null);
19326
19327        // Try very hard to release any references to this path so we don't risk
19328        // the system server being killed due to open FDs
19329        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19330
19331        for (int i = 0; i < 3; i++) {
19332            System.gc();
19333            System.runFinalization();
19334        }
19335    }
19336
19337    /**
19338     * Prepare storage areas for given user on all mounted devices.
19339     */
19340    void prepareUserData(int userId, int userSerial, int flags) {
19341        synchronized (mInstallLock) {
19342            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19343            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19344                final String volumeUuid = vol.getFsUuid();
19345                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19346            }
19347        }
19348    }
19349
19350    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19351            boolean allowRecover) {
19352        // Prepare storage and verify that serial numbers are consistent; if
19353        // there's a mismatch we need to destroy to avoid leaking data
19354        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19355        try {
19356            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19357
19358            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19359                UserManagerService.enforceSerialNumber(
19360                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19361            }
19362            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19363                UserManagerService.enforceSerialNumber(
19364                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19365            }
19366
19367            synchronized (mInstallLock) {
19368                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19369            }
19370        } catch (Exception e) {
19371            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19372                    + " because we failed to prepare: " + e);
19373            destroyUserDataLI(volumeUuid, userId,
19374                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19375
19376            if (allowRecover) {
19377                // Try one last time; if we fail again we're really in trouble
19378                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19379            }
19380        }
19381    }
19382
19383    /**
19384     * Destroy storage areas for given user on all mounted devices.
19385     */
19386    void destroyUserData(int userId, int flags) {
19387        synchronized (mInstallLock) {
19388            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19389            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19390                final String volumeUuid = vol.getFsUuid();
19391                destroyUserDataLI(volumeUuid, userId, flags);
19392            }
19393        }
19394    }
19395
19396    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19397        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19398        try {
19399            // Clean up app data, profile data, and media data
19400            mInstaller.destroyUserData(volumeUuid, userId, flags);
19401
19402            // Clean up system data
19403            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19404                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19405                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19406                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19407                }
19408                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19409                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19410                }
19411            }
19412
19413            // Data with special labels is now gone, so finish the job
19414            storage.destroyUserStorage(volumeUuid, userId, flags);
19415
19416        } catch (Exception e) {
19417            logCriticalInfo(Log.WARN,
19418                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19419        }
19420    }
19421
19422    /**
19423     * Examine all users present on given mounted volume, and destroy data
19424     * belonging to users that are no longer valid, or whose user ID has been
19425     * recycled.
19426     */
19427    private void reconcileUsers(String volumeUuid) {
19428        final List<File> files = new ArrayList<>();
19429        Collections.addAll(files, FileUtils
19430                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19431        Collections.addAll(files, FileUtils
19432                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19433        for (File file : files) {
19434            if (!file.isDirectory()) continue;
19435
19436            final int userId;
19437            final UserInfo info;
19438            try {
19439                userId = Integer.parseInt(file.getName());
19440                info = sUserManager.getUserInfo(userId);
19441            } catch (NumberFormatException e) {
19442                Slog.w(TAG, "Invalid user directory " + file);
19443                continue;
19444            }
19445
19446            boolean destroyUser = false;
19447            if (info == null) {
19448                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19449                        + " because no matching user was found");
19450                destroyUser = true;
19451            } else if (!mOnlyCore) {
19452                try {
19453                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19454                } catch (IOException e) {
19455                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19456                            + " because we failed to enforce serial number: " + e);
19457                    destroyUser = true;
19458                }
19459            }
19460
19461            if (destroyUser) {
19462                synchronized (mInstallLock) {
19463                    destroyUserDataLI(volumeUuid, userId,
19464                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19465                }
19466            }
19467        }
19468    }
19469
19470    private void assertPackageKnown(String volumeUuid, String packageName)
19471            throws PackageManagerException {
19472        synchronized (mPackages) {
19473            final PackageSetting ps = mSettings.mPackages.get(packageName);
19474            if (ps == null) {
19475                throw new PackageManagerException("Package " + packageName + " is unknown");
19476            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19477                throw new PackageManagerException(
19478                        "Package " + packageName + " found on unknown volume " + volumeUuid
19479                                + "; expected volume " + ps.volumeUuid);
19480            }
19481        }
19482    }
19483
19484    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19485            throws PackageManagerException {
19486        synchronized (mPackages) {
19487            final PackageSetting ps = mSettings.mPackages.get(packageName);
19488            if (ps == null) {
19489                throw new PackageManagerException("Package " + packageName + " is unknown");
19490            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19491                throw new PackageManagerException(
19492                        "Package " + packageName + " found on unknown volume " + volumeUuid
19493                                + "; expected volume " + ps.volumeUuid);
19494            } else if (!ps.getInstalled(userId)) {
19495                throw new PackageManagerException(
19496                        "Package " + packageName + " not installed for user " + userId);
19497            }
19498        }
19499    }
19500
19501    /**
19502     * Examine all apps present on given mounted volume, and destroy apps that
19503     * aren't expected, either due to uninstallation or reinstallation on
19504     * another volume.
19505     */
19506    private void reconcileApps(String volumeUuid) {
19507        final File[] files = FileUtils
19508                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19509        for (File file : files) {
19510            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19511                    && !PackageInstallerService.isStageName(file.getName());
19512            if (!isPackage) {
19513                // Ignore entries which are not packages
19514                continue;
19515            }
19516
19517            try {
19518                final PackageLite pkg = PackageParser.parsePackageLite(file,
19519                        PackageParser.PARSE_MUST_BE_APK);
19520                assertPackageKnown(volumeUuid, pkg.packageName);
19521
19522            } catch (PackageParserException | PackageManagerException e) {
19523                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19524                synchronized (mInstallLock) {
19525                    removeCodePathLI(file);
19526                }
19527            }
19528        }
19529    }
19530
19531    /**
19532     * Reconcile all app data for the given user.
19533     * <p>
19534     * Verifies that directories exist and that ownership and labeling is
19535     * correct for all installed apps on all mounted volumes.
19536     */
19537    void reconcileAppsData(int userId, int flags) {
19538        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19539        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19540            final String volumeUuid = vol.getFsUuid();
19541            synchronized (mInstallLock) {
19542                reconcileAppsDataLI(volumeUuid, userId, flags);
19543            }
19544        }
19545    }
19546
19547    /**
19548     * Reconcile all app data on given mounted volume.
19549     * <p>
19550     * Destroys app data that isn't expected, either due to uninstallation or
19551     * reinstallation on another volume.
19552     * <p>
19553     * Verifies that directories exist and that ownership and labeling is
19554     * correct for all installed apps.
19555     */
19556    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19557        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19558                + Integer.toHexString(flags));
19559
19560        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19561        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19562
19563        boolean restoreconNeeded = false;
19564
19565        // First look for stale data that doesn't belong, and check if things
19566        // have changed since we did our last restorecon
19567        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19568            if (StorageManager.isFileEncryptedNativeOrEmulated()
19569                    && !StorageManager.isUserKeyUnlocked(userId)) {
19570                throw new RuntimeException(
19571                        "Yikes, someone asked us to reconcile CE storage while " + userId
19572                                + " was still locked; this would have caused massive data loss!");
19573            }
19574
19575            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19576
19577            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19578            for (File file : files) {
19579                final String packageName = file.getName();
19580                try {
19581                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19582                } catch (PackageManagerException e) {
19583                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19584                    try {
19585                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19586                                StorageManager.FLAG_STORAGE_CE, 0);
19587                    } catch (InstallerException e2) {
19588                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19589                    }
19590                }
19591            }
19592        }
19593        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19594            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19595
19596            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19597            for (File file : files) {
19598                final String packageName = file.getName();
19599                try {
19600                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19601                } catch (PackageManagerException e) {
19602                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19603                    try {
19604                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19605                                StorageManager.FLAG_STORAGE_DE, 0);
19606                    } catch (InstallerException e2) {
19607                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19608                    }
19609                }
19610            }
19611        }
19612
19613        // Ensure that data directories are ready to roll for all packages
19614        // installed for this volume and user
19615        final List<PackageSetting> packages;
19616        synchronized (mPackages) {
19617            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19618        }
19619        int preparedCount = 0;
19620        for (PackageSetting ps : packages) {
19621            final String packageName = ps.name;
19622            if (ps.pkg == null) {
19623                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19624                // TODO: might be due to legacy ASEC apps; we should circle back
19625                // and reconcile again once they're scanned
19626                continue;
19627            }
19628
19629            if (ps.getInstalled(userId)) {
19630                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19631
19632                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19633                    // We may have just shuffled around app data directories, so
19634                    // prepare them one more time
19635                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19636                }
19637
19638                preparedCount++;
19639            }
19640        }
19641
19642        if (restoreconNeeded) {
19643            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19644                SELinuxMMAC.setRestoreconDone(ceDir);
19645            }
19646            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19647                SELinuxMMAC.setRestoreconDone(deDir);
19648            }
19649        }
19650
19651        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19652                + " packages; restoreconNeeded was " + restoreconNeeded);
19653    }
19654
19655    /**
19656     * Prepare app data for the given app just after it was installed or
19657     * upgraded. This method carefully only touches users that it's installed
19658     * for, and it forces a restorecon to handle any seinfo changes.
19659     * <p>
19660     * Verifies that directories exist and that ownership and labeling is
19661     * correct for all installed apps. If there is an ownership mismatch, it
19662     * will try recovering system apps by wiping data; third-party app data is
19663     * left intact.
19664     * <p>
19665     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19666     */
19667    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19668        final PackageSetting ps;
19669        synchronized (mPackages) {
19670            ps = mSettings.mPackages.get(pkg.packageName);
19671            mSettings.writeKernelMappingLPr(ps);
19672        }
19673
19674        final UserManager um = mContext.getSystemService(UserManager.class);
19675        UserManagerInternal umInternal = getUserManagerInternal();
19676        for (UserInfo user : um.getUsers()) {
19677            final int flags;
19678            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19679                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19680            } else if (umInternal.isUserRunning(user.id)) {
19681                flags = StorageManager.FLAG_STORAGE_DE;
19682            } else {
19683                continue;
19684            }
19685
19686            if (ps.getInstalled(user.id)) {
19687                // Whenever an app changes, force a restorecon of its data
19688                // TODO: when user data is locked, mark that we're still dirty
19689                prepareAppDataLIF(pkg, user.id, flags, true);
19690            }
19691        }
19692    }
19693
19694    /**
19695     * Prepare app data for the given app.
19696     * <p>
19697     * Verifies that directories exist and that ownership and labeling is
19698     * correct for all installed apps. If there is an ownership mismatch, this
19699     * will try recovering system apps by wiping data; third-party app data is
19700     * left intact.
19701     */
19702    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19703            boolean restoreconNeeded) {
19704        if (pkg == null) {
19705            Slog.wtf(TAG, "Package was null!", new Throwable());
19706            return;
19707        }
19708        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19709        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19710        for (int i = 0; i < childCount; i++) {
19711            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19712        }
19713    }
19714
19715    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19716            boolean restoreconNeeded) {
19717        if (DEBUG_APP_DATA) {
19718            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19719                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19720        }
19721
19722        final String volumeUuid = pkg.volumeUuid;
19723        final String packageName = pkg.packageName;
19724        final ApplicationInfo app = pkg.applicationInfo;
19725        final int appId = UserHandle.getAppId(app.uid);
19726
19727        Preconditions.checkNotNull(app.seinfo);
19728
19729        try {
19730            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19731                    appId, app.seinfo, app.targetSdkVersion);
19732        } catch (InstallerException e) {
19733            if (app.isSystemApp()) {
19734                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19735                        + ", but trying to recover: " + e);
19736                destroyAppDataLeafLIF(pkg, userId, flags);
19737                try {
19738                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19739                            appId, app.seinfo, app.targetSdkVersion);
19740                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19741                } catch (InstallerException e2) {
19742                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19743                }
19744            } else {
19745                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19746            }
19747        }
19748
19749        if (restoreconNeeded) {
19750            try {
19751                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19752                        app.seinfo);
19753            } catch (InstallerException e) {
19754                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19755            }
19756        }
19757
19758        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19759            try {
19760                // CE storage is unlocked right now, so read out the inode and
19761                // remember for use later when it's locked
19762                // TODO: mark this structure as dirty so we persist it!
19763                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19764                        StorageManager.FLAG_STORAGE_CE);
19765                synchronized (mPackages) {
19766                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19767                    if (ps != null) {
19768                        ps.setCeDataInode(ceDataInode, userId);
19769                    }
19770                }
19771            } catch (InstallerException e) {
19772                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19773            }
19774        }
19775
19776        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19777    }
19778
19779    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19780        if (pkg == null) {
19781            Slog.wtf(TAG, "Package was null!", new Throwable());
19782            return;
19783        }
19784        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19785        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19786        for (int i = 0; i < childCount; i++) {
19787            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19788        }
19789    }
19790
19791    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19792        final String volumeUuid = pkg.volumeUuid;
19793        final String packageName = pkg.packageName;
19794        final ApplicationInfo app = pkg.applicationInfo;
19795
19796        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19797            // Create a native library symlink only if we have native libraries
19798            // and if the native libraries are 32 bit libraries. We do not provide
19799            // this symlink for 64 bit libraries.
19800            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19801                final String nativeLibPath = app.nativeLibraryDir;
19802                try {
19803                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19804                            nativeLibPath, userId);
19805                } catch (InstallerException e) {
19806                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19807                }
19808            }
19809        }
19810    }
19811
19812    /**
19813     * For system apps on non-FBE devices, this method migrates any existing
19814     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19815     * requested by the app.
19816     */
19817    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19818        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19819                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19820            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19821                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19822            try {
19823                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19824                        storageTarget);
19825            } catch (InstallerException e) {
19826                logCriticalInfo(Log.WARN,
19827                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19828            }
19829            return true;
19830        } else {
19831            return false;
19832        }
19833    }
19834
19835    public PackageFreezer freezePackage(String packageName, String killReason) {
19836        return new PackageFreezer(packageName, killReason);
19837    }
19838
19839    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19840            String killReason) {
19841        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19842            return new PackageFreezer();
19843        } else {
19844            return freezePackage(packageName, killReason);
19845        }
19846    }
19847
19848    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19849            String killReason) {
19850        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19851            return new PackageFreezer();
19852        } else {
19853            return freezePackage(packageName, killReason);
19854        }
19855    }
19856
19857    /**
19858     * Class that freezes and kills the given package upon creation, and
19859     * unfreezes it upon closing. This is typically used when doing surgery on
19860     * app code/data to prevent the app from running while you're working.
19861     */
19862    private class PackageFreezer implements AutoCloseable {
19863        private final String mPackageName;
19864        private final PackageFreezer[] mChildren;
19865
19866        private final boolean mWeFroze;
19867
19868        private final AtomicBoolean mClosed = new AtomicBoolean();
19869        private final CloseGuard mCloseGuard = CloseGuard.get();
19870
19871        /**
19872         * Create and return a stub freezer that doesn't actually do anything,
19873         * typically used when someone requested
19874         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19875         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19876         */
19877        public PackageFreezer() {
19878            mPackageName = null;
19879            mChildren = null;
19880            mWeFroze = false;
19881            mCloseGuard.open("close");
19882        }
19883
19884        public PackageFreezer(String packageName, String killReason) {
19885            synchronized (mPackages) {
19886                mPackageName = packageName;
19887                mWeFroze = mFrozenPackages.add(mPackageName);
19888
19889                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19890                if (ps != null) {
19891                    killApplication(ps.name, ps.appId, killReason);
19892                }
19893
19894                final PackageParser.Package p = mPackages.get(packageName);
19895                if (p != null && p.childPackages != null) {
19896                    final int N = p.childPackages.size();
19897                    mChildren = new PackageFreezer[N];
19898                    for (int i = 0; i < N; i++) {
19899                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19900                                killReason);
19901                    }
19902                } else {
19903                    mChildren = null;
19904                }
19905            }
19906            mCloseGuard.open("close");
19907        }
19908
19909        @Override
19910        protected void finalize() throws Throwable {
19911            try {
19912                mCloseGuard.warnIfOpen();
19913                close();
19914            } finally {
19915                super.finalize();
19916            }
19917        }
19918
19919        @Override
19920        public void close() {
19921            mCloseGuard.close();
19922            if (mClosed.compareAndSet(false, true)) {
19923                synchronized (mPackages) {
19924                    if (mWeFroze) {
19925                        mFrozenPackages.remove(mPackageName);
19926                    }
19927
19928                    if (mChildren != null) {
19929                        for (PackageFreezer freezer : mChildren) {
19930                            freezer.close();
19931                        }
19932                    }
19933                }
19934            }
19935        }
19936    }
19937
19938    /**
19939     * Verify that given package is currently frozen.
19940     */
19941    private void checkPackageFrozen(String packageName) {
19942        synchronized (mPackages) {
19943            if (!mFrozenPackages.contains(packageName)) {
19944                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19945            }
19946        }
19947    }
19948
19949    @Override
19950    public int movePackage(final String packageName, final String volumeUuid) {
19951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19952
19953        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19954        final int moveId = mNextMoveId.getAndIncrement();
19955        mHandler.post(new Runnable() {
19956            @Override
19957            public void run() {
19958                try {
19959                    movePackageInternal(packageName, volumeUuid, moveId, user);
19960                } catch (PackageManagerException e) {
19961                    Slog.w(TAG, "Failed to move " + packageName, e);
19962                    mMoveCallbacks.notifyStatusChanged(moveId,
19963                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19964                }
19965            }
19966        });
19967        return moveId;
19968    }
19969
19970    private void movePackageInternal(final String packageName, final String volumeUuid,
19971            final int moveId, UserHandle user) throws PackageManagerException {
19972        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19973        final PackageManager pm = mContext.getPackageManager();
19974
19975        final boolean currentAsec;
19976        final String currentVolumeUuid;
19977        final File codeFile;
19978        final String installerPackageName;
19979        final String packageAbiOverride;
19980        final int appId;
19981        final String seinfo;
19982        final String label;
19983        final int targetSdkVersion;
19984        final PackageFreezer freezer;
19985        final int[] installedUserIds;
19986
19987        // reader
19988        synchronized (mPackages) {
19989            final PackageParser.Package pkg = mPackages.get(packageName);
19990            final PackageSetting ps = mSettings.mPackages.get(packageName);
19991            if (pkg == null || ps == null) {
19992                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19993            }
19994
19995            if (pkg.applicationInfo.isSystemApp()) {
19996                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19997                        "Cannot move system application");
19998            }
19999
20000            if (pkg.applicationInfo.isExternalAsec()) {
20001                currentAsec = true;
20002                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20003            } else if (pkg.applicationInfo.isForwardLocked()) {
20004                currentAsec = true;
20005                currentVolumeUuid = "forward_locked";
20006            } else {
20007                currentAsec = false;
20008                currentVolumeUuid = ps.volumeUuid;
20009
20010                final File probe = new File(pkg.codePath);
20011                final File probeOat = new File(probe, "oat");
20012                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20013                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20014                            "Move only supported for modern cluster style installs");
20015                }
20016            }
20017
20018            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20019                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20020                        "Package already moved to " + volumeUuid);
20021            }
20022            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20023                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20024                        "Device admin cannot be moved");
20025            }
20026
20027            if (mFrozenPackages.contains(packageName)) {
20028                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20029                        "Failed to move already frozen package");
20030            }
20031
20032            codeFile = new File(pkg.codePath);
20033            installerPackageName = ps.installerPackageName;
20034            packageAbiOverride = ps.cpuAbiOverrideString;
20035            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20036            seinfo = pkg.applicationInfo.seinfo;
20037            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20038            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20039            freezer = new PackageFreezer(packageName, "movePackageInternal");
20040            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20041        }
20042
20043        final Bundle extras = new Bundle();
20044        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20045        extras.putString(Intent.EXTRA_TITLE, label);
20046        mMoveCallbacks.notifyCreated(moveId, extras);
20047
20048        int installFlags;
20049        final boolean moveCompleteApp;
20050        final File measurePath;
20051
20052        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20053            installFlags = INSTALL_INTERNAL;
20054            moveCompleteApp = !currentAsec;
20055            measurePath = Environment.getDataAppDirectory(volumeUuid);
20056        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20057            installFlags = INSTALL_EXTERNAL;
20058            moveCompleteApp = false;
20059            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20060        } else {
20061            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20062            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20063                    || !volume.isMountedWritable()) {
20064                freezer.close();
20065                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20066                        "Move location not mounted private volume");
20067            }
20068
20069            Preconditions.checkState(!currentAsec);
20070
20071            installFlags = INSTALL_INTERNAL;
20072            moveCompleteApp = true;
20073            measurePath = Environment.getDataAppDirectory(volumeUuid);
20074        }
20075
20076        final PackageStats stats = new PackageStats(null, -1);
20077        synchronized (mInstaller) {
20078            for (int userId : installedUserIds) {
20079                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20080                    freezer.close();
20081                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20082                            "Failed to measure package size");
20083                }
20084            }
20085        }
20086
20087        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20088                + stats.dataSize);
20089
20090        final long startFreeBytes = measurePath.getFreeSpace();
20091        final long sizeBytes;
20092        if (moveCompleteApp) {
20093            sizeBytes = stats.codeSize + stats.dataSize;
20094        } else {
20095            sizeBytes = stats.codeSize;
20096        }
20097
20098        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20099            freezer.close();
20100            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20101                    "Not enough free space to move");
20102        }
20103
20104        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20105
20106        final CountDownLatch installedLatch = new CountDownLatch(1);
20107        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20108            @Override
20109            public void onUserActionRequired(Intent intent) throws RemoteException {
20110                throw new IllegalStateException();
20111            }
20112
20113            @Override
20114            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20115                    Bundle extras) throws RemoteException {
20116                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20117                        + PackageManager.installStatusToString(returnCode, msg));
20118
20119                installedLatch.countDown();
20120                freezer.close();
20121
20122                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20123                switch (status) {
20124                    case PackageInstaller.STATUS_SUCCESS:
20125                        mMoveCallbacks.notifyStatusChanged(moveId,
20126                                PackageManager.MOVE_SUCCEEDED);
20127                        break;
20128                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20129                        mMoveCallbacks.notifyStatusChanged(moveId,
20130                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20131                        break;
20132                    default:
20133                        mMoveCallbacks.notifyStatusChanged(moveId,
20134                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20135                        break;
20136                }
20137            }
20138        };
20139
20140        final MoveInfo move;
20141        if (moveCompleteApp) {
20142            // Kick off a thread to report progress estimates
20143            new Thread() {
20144                @Override
20145                public void run() {
20146                    while (true) {
20147                        try {
20148                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20149                                break;
20150                            }
20151                        } catch (InterruptedException ignored) {
20152                        }
20153
20154                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20155                        final int progress = 10 + (int) MathUtils.constrain(
20156                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20157                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20158                    }
20159                }
20160            }.start();
20161
20162            final String dataAppName = codeFile.getName();
20163            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20164                    dataAppName, appId, seinfo, targetSdkVersion);
20165        } else {
20166            move = null;
20167        }
20168
20169        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20170
20171        final Message msg = mHandler.obtainMessage(INIT_COPY);
20172        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20173        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20174                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20175                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20176        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20177        msg.obj = params;
20178
20179        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20180                System.identityHashCode(msg.obj));
20181        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20182                System.identityHashCode(msg.obj));
20183
20184        mHandler.sendMessage(msg);
20185    }
20186
20187    @Override
20188    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20189        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20190
20191        final int realMoveId = mNextMoveId.getAndIncrement();
20192        final Bundle extras = new Bundle();
20193        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20194        mMoveCallbacks.notifyCreated(realMoveId, extras);
20195
20196        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20197            @Override
20198            public void onCreated(int moveId, Bundle extras) {
20199                // Ignored
20200            }
20201
20202            @Override
20203            public void onStatusChanged(int moveId, int status, long estMillis) {
20204                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20205            }
20206        };
20207
20208        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20209        storage.setPrimaryStorageUuid(volumeUuid, callback);
20210        return realMoveId;
20211    }
20212
20213    @Override
20214    public int getMoveStatus(int moveId) {
20215        mContext.enforceCallingOrSelfPermission(
20216                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20217        return mMoveCallbacks.mLastStatus.get(moveId);
20218    }
20219
20220    @Override
20221    public void registerMoveCallback(IPackageMoveObserver callback) {
20222        mContext.enforceCallingOrSelfPermission(
20223                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20224        mMoveCallbacks.register(callback);
20225    }
20226
20227    @Override
20228    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20229        mContext.enforceCallingOrSelfPermission(
20230                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20231        mMoveCallbacks.unregister(callback);
20232    }
20233
20234    @Override
20235    public boolean setInstallLocation(int loc) {
20236        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20237                null);
20238        if (getInstallLocation() == loc) {
20239            return true;
20240        }
20241        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20242                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20243            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20244                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20245            return true;
20246        }
20247        return false;
20248   }
20249
20250    @Override
20251    public int getInstallLocation() {
20252        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20253                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20254                PackageHelper.APP_INSTALL_AUTO);
20255    }
20256
20257    /** Called by UserManagerService */
20258    void cleanUpUser(UserManagerService userManager, int userHandle) {
20259        synchronized (mPackages) {
20260            mDirtyUsers.remove(userHandle);
20261            mUserNeedsBadging.delete(userHandle);
20262            mSettings.removeUserLPw(userHandle);
20263            mPendingBroadcasts.remove(userHandle);
20264            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20265            removeUnusedPackagesLPw(userManager, userHandle);
20266        }
20267    }
20268
20269    /**
20270     * We're removing userHandle and would like to remove any downloaded packages
20271     * that are no longer in use by any other user.
20272     * @param userHandle the user being removed
20273     */
20274    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20275        final boolean DEBUG_CLEAN_APKS = false;
20276        int [] users = userManager.getUserIds();
20277        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20278        while (psit.hasNext()) {
20279            PackageSetting ps = psit.next();
20280            if (ps.pkg == null) {
20281                continue;
20282            }
20283            final String packageName = ps.pkg.packageName;
20284            // Skip over if system app
20285            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20286                continue;
20287            }
20288            if (DEBUG_CLEAN_APKS) {
20289                Slog.i(TAG, "Checking package " + packageName);
20290            }
20291            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20292            if (keep) {
20293                if (DEBUG_CLEAN_APKS) {
20294                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20295                }
20296            } else {
20297                for (int i = 0; i < users.length; i++) {
20298                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20299                        keep = true;
20300                        if (DEBUG_CLEAN_APKS) {
20301                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20302                                    + users[i]);
20303                        }
20304                        break;
20305                    }
20306                }
20307            }
20308            if (!keep) {
20309                if (DEBUG_CLEAN_APKS) {
20310                    Slog.i(TAG, "  Removing package " + packageName);
20311                }
20312                mHandler.post(new Runnable() {
20313                    public void run() {
20314                        deletePackageX(packageName, userHandle, 0);
20315                    } //end run
20316                });
20317            }
20318        }
20319    }
20320
20321    /** Called by UserManagerService */
20322    void createNewUser(int userId) {
20323        synchronized (mInstallLock) {
20324            mSettings.createNewUserLI(this, mInstaller, userId);
20325        }
20326        synchronized (mPackages) {
20327            scheduleWritePackageRestrictionsLocked(userId);
20328            scheduleWritePackageListLocked(userId);
20329            applyFactoryDefaultBrowserLPw(userId);
20330            primeDomainVerificationsLPw(userId);
20331        }
20332    }
20333
20334    void onBeforeUserStartUninitialized(final int userId) {
20335        synchronized (mPackages) {
20336            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20337                return;
20338            }
20339        }
20340        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20341        // If permission review for legacy apps is required, we represent
20342        // dagerous permissions for such apps as always granted runtime
20343        // permissions to keep per user flag state whether review is needed.
20344        // Hence, if a new user is added we have to propagate dangerous
20345        // permission grants for these legacy apps.
20346        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20347            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20348                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20349        }
20350    }
20351
20352    @Override
20353    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20354        mContext.enforceCallingOrSelfPermission(
20355                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20356                "Only package verification agents can read the verifier device identity");
20357
20358        synchronized (mPackages) {
20359            return mSettings.getVerifierDeviceIdentityLPw();
20360        }
20361    }
20362
20363    @Override
20364    public void setPermissionEnforced(String permission, boolean enforced) {
20365        // TODO: Now that we no longer change GID for storage, this should to away.
20366        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20367                "setPermissionEnforced");
20368        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20369            synchronized (mPackages) {
20370                if (mSettings.mReadExternalStorageEnforced == null
20371                        || mSettings.mReadExternalStorageEnforced != enforced) {
20372                    mSettings.mReadExternalStorageEnforced = enforced;
20373                    mSettings.writeLPr();
20374                }
20375            }
20376            // kill any non-foreground processes so we restart them and
20377            // grant/revoke the GID.
20378            final IActivityManager am = ActivityManagerNative.getDefault();
20379            if (am != null) {
20380                final long token = Binder.clearCallingIdentity();
20381                try {
20382                    am.killProcessesBelowForeground("setPermissionEnforcement");
20383                } catch (RemoteException e) {
20384                } finally {
20385                    Binder.restoreCallingIdentity(token);
20386                }
20387            }
20388        } else {
20389            throw new IllegalArgumentException("No selective enforcement for " + permission);
20390        }
20391    }
20392
20393    @Override
20394    @Deprecated
20395    public boolean isPermissionEnforced(String permission) {
20396        return true;
20397    }
20398
20399    @Override
20400    public boolean isStorageLow() {
20401        final long token = Binder.clearCallingIdentity();
20402        try {
20403            final DeviceStorageMonitorInternal
20404                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20405            if (dsm != null) {
20406                return dsm.isMemoryLow();
20407            } else {
20408                return false;
20409            }
20410        } finally {
20411            Binder.restoreCallingIdentity(token);
20412        }
20413    }
20414
20415    @Override
20416    public IPackageInstaller getPackageInstaller() {
20417        return mInstallerService;
20418    }
20419
20420    private boolean userNeedsBadging(int userId) {
20421        int index = mUserNeedsBadging.indexOfKey(userId);
20422        if (index < 0) {
20423            final UserInfo userInfo;
20424            final long token = Binder.clearCallingIdentity();
20425            try {
20426                userInfo = sUserManager.getUserInfo(userId);
20427            } finally {
20428                Binder.restoreCallingIdentity(token);
20429            }
20430            final boolean b;
20431            if (userInfo != null && userInfo.isManagedProfile()) {
20432                b = true;
20433            } else {
20434                b = false;
20435            }
20436            mUserNeedsBadging.put(userId, b);
20437            return b;
20438        }
20439        return mUserNeedsBadging.valueAt(index);
20440    }
20441
20442    @Override
20443    public KeySet getKeySetByAlias(String packageName, String alias) {
20444        if (packageName == null || alias == null) {
20445            return null;
20446        }
20447        synchronized(mPackages) {
20448            final PackageParser.Package pkg = mPackages.get(packageName);
20449            if (pkg == null) {
20450                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20451                throw new IllegalArgumentException("Unknown package: " + packageName);
20452            }
20453            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20454            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20455        }
20456    }
20457
20458    @Override
20459    public KeySet getSigningKeySet(String packageName) {
20460        if (packageName == null) {
20461            return null;
20462        }
20463        synchronized(mPackages) {
20464            final PackageParser.Package pkg = mPackages.get(packageName);
20465            if (pkg == null) {
20466                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20467                throw new IllegalArgumentException("Unknown package: " + packageName);
20468            }
20469            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20470                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20471                throw new SecurityException("May not access signing KeySet of other apps.");
20472            }
20473            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20474            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20475        }
20476    }
20477
20478    @Override
20479    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20480        if (packageName == null || ks == null) {
20481            return false;
20482        }
20483        synchronized(mPackages) {
20484            final PackageParser.Package pkg = mPackages.get(packageName);
20485            if (pkg == null) {
20486                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20487                throw new IllegalArgumentException("Unknown package: " + packageName);
20488            }
20489            IBinder ksh = ks.getToken();
20490            if (ksh instanceof KeySetHandle) {
20491                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20492                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20493            }
20494            return false;
20495        }
20496    }
20497
20498    @Override
20499    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20500        if (packageName == null || ks == null) {
20501            return false;
20502        }
20503        synchronized(mPackages) {
20504            final PackageParser.Package pkg = mPackages.get(packageName);
20505            if (pkg == null) {
20506                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20507                throw new IllegalArgumentException("Unknown package: " + packageName);
20508            }
20509            IBinder ksh = ks.getToken();
20510            if (ksh instanceof KeySetHandle) {
20511                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20512                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20513            }
20514            return false;
20515        }
20516    }
20517
20518    private void deletePackageIfUnusedLPr(final String packageName) {
20519        PackageSetting ps = mSettings.mPackages.get(packageName);
20520        if (ps == null) {
20521            return;
20522        }
20523        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20524            // TODO Implement atomic delete if package is unused
20525            // It is currently possible that the package will be deleted even if it is installed
20526            // after this method returns.
20527            mHandler.post(new Runnable() {
20528                public void run() {
20529                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20530                }
20531            });
20532        }
20533    }
20534
20535    /**
20536     * Check and throw if the given before/after packages would be considered a
20537     * downgrade.
20538     */
20539    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20540            throws PackageManagerException {
20541        if (after.versionCode < before.mVersionCode) {
20542            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20543                    "Update version code " + after.versionCode + " is older than current "
20544                    + before.mVersionCode);
20545        } else if (after.versionCode == before.mVersionCode) {
20546            if (after.baseRevisionCode < before.baseRevisionCode) {
20547                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20548                        "Update base revision code " + after.baseRevisionCode
20549                        + " is older than current " + before.baseRevisionCode);
20550            }
20551
20552            if (!ArrayUtils.isEmpty(after.splitNames)) {
20553                for (int i = 0; i < after.splitNames.length; i++) {
20554                    final String splitName = after.splitNames[i];
20555                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20556                    if (j != -1) {
20557                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20558                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20559                                    "Update split " + splitName + " revision code "
20560                                    + after.splitRevisionCodes[i] + " is older than current "
20561                                    + before.splitRevisionCodes[j]);
20562                        }
20563                    }
20564                }
20565            }
20566        }
20567    }
20568
20569    private static class MoveCallbacks extends Handler {
20570        private static final int MSG_CREATED = 1;
20571        private static final int MSG_STATUS_CHANGED = 2;
20572
20573        private final RemoteCallbackList<IPackageMoveObserver>
20574                mCallbacks = new RemoteCallbackList<>();
20575
20576        private final SparseIntArray mLastStatus = new SparseIntArray();
20577
20578        public MoveCallbacks(Looper looper) {
20579            super(looper);
20580        }
20581
20582        public void register(IPackageMoveObserver callback) {
20583            mCallbacks.register(callback);
20584        }
20585
20586        public void unregister(IPackageMoveObserver callback) {
20587            mCallbacks.unregister(callback);
20588        }
20589
20590        @Override
20591        public void handleMessage(Message msg) {
20592            final SomeArgs args = (SomeArgs) msg.obj;
20593            final int n = mCallbacks.beginBroadcast();
20594            for (int i = 0; i < n; i++) {
20595                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20596                try {
20597                    invokeCallback(callback, msg.what, args);
20598                } catch (RemoteException ignored) {
20599                }
20600            }
20601            mCallbacks.finishBroadcast();
20602            args.recycle();
20603        }
20604
20605        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20606                throws RemoteException {
20607            switch (what) {
20608                case MSG_CREATED: {
20609                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20610                    break;
20611                }
20612                case MSG_STATUS_CHANGED: {
20613                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20614                    break;
20615                }
20616            }
20617        }
20618
20619        private void notifyCreated(int moveId, Bundle extras) {
20620            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20621
20622            final SomeArgs args = SomeArgs.obtain();
20623            args.argi1 = moveId;
20624            args.arg2 = extras;
20625            obtainMessage(MSG_CREATED, args).sendToTarget();
20626        }
20627
20628        private void notifyStatusChanged(int moveId, int status) {
20629            notifyStatusChanged(moveId, status, -1);
20630        }
20631
20632        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20633            Slog.v(TAG, "Move " + moveId + " status " + status);
20634
20635            final SomeArgs args = SomeArgs.obtain();
20636            args.argi1 = moveId;
20637            args.argi2 = status;
20638            args.arg3 = estMillis;
20639            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20640
20641            synchronized (mLastStatus) {
20642                mLastStatus.put(moveId, status);
20643            }
20644        }
20645    }
20646
20647    private final static class OnPermissionChangeListeners extends Handler {
20648        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20649
20650        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20651                new RemoteCallbackList<>();
20652
20653        public OnPermissionChangeListeners(Looper looper) {
20654            super(looper);
20655        }
20656
20657        @Override
20658        public void handleMessage(Message msg) {
20659            switch (msg.what) {
20660                case MSG_ON_PERMISSIONS_CHANGED: {
20661                    final int uid = msg.arg1;
20662                    handleOnPermissionsChanged(uid);
20663                } break;
20664            }
20665        }
20666
20667        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20668            mPermissionListeners.register(listener);
20669
20670        }
20671
20672        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20673            mPermissionListeners.unregister(listener);
20674        }
20675
20676        public void onPermissionsChanged(int uid) {
20677            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20678                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20679            }
20680        }
20681
20682        private void handleOnPermissionsChanged(int uid) {
20683            final int count = mPermissionListeners.beginBroadcast();
20684            try {
20685                for (int i = 0; i < count; i++) {
20686                    IOnPermissionsChangeListener callback = mPermissionListeners
20687                            .getBroadcastItem(i);
20688                    try {
20689                        callback.onPermissionsChanged(uid);
20690                    } catch (RemoteException e) {
20691                        Log.e(TAG, "Permission listener is dead", e);
20692                    }
20693                }
20694            } finally {
20695                mPermissionListeners.finishBroadcast();
20696            }
20697        }
20698    }
20699
20700    private class PackageManagerInternalImpl extends PackageManagerInternal {
20701        @Override
20702        public void setLocationPackagesProvider(PackagesProvider provider) {
20703            synchronized (mPackages) {
20704                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20705            }
20706        }
20707
20708        @Override
20709        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20710            synchronized (mPackages) {
20711                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20712            }
20713        }
20714
20715        @Override
20716        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20717            synchronized (mPackages) {
20718                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20719            }
20720        }
20721
20722        @Override
20723        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20724            synchronized (mPackages) {
20725                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20726            }
20727        }
20728
20729        @Override
20730        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20731            synchronized (mPackages) {
20732                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20733            }
20734        }
20735
20736        @Override
20737        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20738            synchronized (mPackages) {
20739                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20740            }
20741        }
20742
20743        @Override
20744        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20745            synchronized (mPackages) {
20746                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20747                        packageName, userId);
20748            }
20749        }
20750
20751        @Override
20752        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20753            synchronized (mPackages) {
20754                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20755                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20756                        packageName, userId);
20757            }
20758        }
20759
20760        @Override
20761        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20762            synchronized (mPackages) {
20763                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20764                        packageName, userId);
20765            }
20766        }
20767
20768        @Override
20769        public void setKeepUninstalledPackages(final List<String> packageList) {
20770            Preconditions.checkNotNull(packageList);
20771            List<String> removedFromList = null;
20772            synchronized (mPackages) {
20773                if (mKeepUninstalledPackages != null) {
20774                    final int packagesCount = mKeepUninstalledPackages.size();
20775                    for (int i = 0; i < packagesCount; i++) {
20776                        String oldPackage = mKeepUninstalledPackages.get(i);
20777                        if (packageList != null && packageList.contains(oldPackage)) {
20778                            continue;
20779                        }
20780                        if (removedFromList == null) {
20781                            removedFromList = new ArrayList<>();
20782                        }
20783                        removedFromList.add(oldPackage);
20784                    }
20785                }
20786                mKeepUninstalledPackages = new ArrayList<>(packageList);
20787                if (removedFromList != null) {
20788                    final int removedCount = removedFromList.size();
20789                    for (int i = 0; i < removedCount; i++) {
20790                        deletePackageIfUnusedLPr(removedFromList.get(i));
20791                    }
20792                }
20793            }
20794        }
20795
20796        @Override
20797        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20798            synchronized (mPackages) {
20799                // If we do not support permission review, done.
20800                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20801                    return false;
20802                }
20803
20804                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20805                if (packageSetting == null) {
20806                    return false;
20807                }
20808
20809                // Permission review applies only to apps not supporting the new permission model.
20810                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20811                    return false;
20812                }
20813
20814                // Legacy apps have the permission and get user consent on launch.
20815                PermissionsState permissionsState = packageSetting.getPermissionsState();
20816                return permissionsState.isPermissionReviewRequired(userId);
20817            }
20818        }
20819
20820        @Override
20821        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20822            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20823        }
20824
20825        @Override
20826        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20827                int userId) {
20828            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20829        }
20830
20831        @Override
20832        public void setDeviceAndProfileOwnerPackages(
20833                int deviceOwnerUserId, String deviceOwnerPackage,
20834                SparseArray<String> profileOwnerPackages) {
20835            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20836                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20837        }
20838
20839        @Override
20840        public boolean canPackageBeWiped(int userId, String packageName) {
20841            return mProtectedPackages.canPackageBeWiped(userId,
20842                    packageName);
20843        }
20844    }
20845
20846    @Override
20847    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20848        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20849        synchronized (mPackages) {
20850            final long identity = Binder.clearCallingIdentity();
20851            try {
20852                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20853                        packageNames, userId);
20854            } finally {
20855                Binder.restoreCallingIdentity(identity);
20856            }
20857        }
20858    }
20859
20860    private static void enforceSystemOrPhoneCaller(String tag) {
20861        int callingUid = Binder.getCallingUid();
20862        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20863            throw new SecurityException(
20864                    "Cannot call " + tag + " from UID " + callingUid);
20865        }
20866    }
20867
20868    boolean isHistoricalPackageUsageAvailable() {
20869        return mPackageUsage.isHistoricalPackageUsageAvailable();
20870    }
20871
20872    /**
20873     * Return a <b>copy</b> of the collection of packages known to the package manager.
20874     * @return A copy of the values of mPackages.
20875     */
20876    Collection<PackageParser.Package> getPackages() {
20877        synchronized (mPackages) {
20878            return new ArrayList<>(mPackages.values());
20879        }
20880    }
20881
20882    /**
20883     * Logs process start information (including base APK hash) to the security log.
20884     * @hide
20885     */
20886    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20887            String apkFile, int pid) {
20888        if (!SecurityLog.isLoggingEnabled()) {
20889            return;
20890        }
20891        Bundle data = new Bundle();
20892        data.putLong("startTimestamp", System.currentTimeMillis());
20893        data.putString("processName", processName);
20894        data.putInt("uid", uid);
20895        data.putString("seinfo", seinfo);
20896        data.putString("apkFile", apkFile);
20897        data.putInt("pid", pid);
20898        Message msg = mProcessLoggingHandler.obtainMessage(
20899                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20900        msg.setData(data);
20901        mProcessLoggingHandler.sendMessage(msg);
20902    }
20903}
20904