PackageManagerService.java revision 1186eb3fad0b61f9a6dbf027e933fd778cbad4b2
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.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67import static android.content.pm.PackageManager.MATCH_ALL;
68import static android.content.pm.PackageManager.MATCH_ANY_USER;
69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106
107import android.Manifest;
108import android.annotation.IntDef;
109import android.annotation.NonNull;
110import android.annotation.Nullable;
111import android.app.ActivityManager;
112import android.app.AppOpsManager;
113import android.app.IActivityManager;
114import android.app.ResourcesManager;
115import android.app.admin.IDevicePolicyManager;
116import android.app.admin.SecurityLog;
117import android.app.backup.IBackupManager;
118import android.content.BroadcastReceiver;
119import android.content.ComponentName;
120import android.content.ContentResolver;
121import android.content.Context;
122import android.content.IIntentReceiver;
123import android.content.Intent;
124import android.content.IntentFilter;
125import android.content.IntentSender;
126import android.content.IntentSender.SendIntentException;
127import android.content.ServiceConnection;
128import android.content.pm.ActivityInfo;
129import android.content.pm.ApplicationInfo;
130import android.content.pm.AppsQueryHelper;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.ChangedPackages;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppRequest;
146import android.content.pm.InstantAppResolveInfo;
147import android.content.pm.InstrumentationInfo;
148import android.content.pm.IntentFilterVerificationInfo;
149import android.content.pm.KeySet;
150import android.content.pm.PackageCleanItem;
151import android.content.pm.PackageInfo;
152import android.content.pm.PackageInfoLite;
153import android.content.pm.PackageInstaller;
154import android.content.pm.PackageManager;
155import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
156import android.content.pm.PackageManagerInternal;
157import android.content.pm.PackageParser;
158import android.content.pm.PackageParser.ActivityIntentInfo;
159import android.content.pm.PackageParser.PackageLite;
160import android.content.pm.PackageParser.PackageParserException;
161import android.content.pm.PackageStats;
162import android.content.pm.PackageUserState;
163import android.content.pm.ParceledListSlice;
164import android.content.pm.PermissionGroupInfo;
165import android.content.pm.PermissionInfo;
166import android.content.pm.ProviderInfo;
167import android.content.pm.ResolveInfo;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.database.ContentObserver;
177import android.graphics.Bitmap;
178import android.hardware.display.DisplayManager;
179import android.net.Uri;
180import android.os.Binder;
181import android.os.Build;
182import android.os.Bundle;
183import android.os.Debug;
184import android.os.Environment;
185import android.os.Environment.UserEnvironment;
186import android.os.FileUtils;
187import android.os.Handler;
188import android.os.IBinder;
189import android.os.Looper;
190import android.os.Message;
191import android.os.Parcel;
192import android.os.ParcelFileDescriptor;
193import android.os.PatternMatcher;
194import android.os.Process;
195import android.os.RemoteCallbackList;
196import android.os.RemoteException;
197import android.os.ResultReceiver;
198import android.os.SELinux;
199import android.os.ServiceManager;
200import android.os.ShellCallback;
201import android.os.SystemClock;
202import android.os.SystemProperties;
203import android.os.Trace;
204import android.os.UserHandle;
205import android.os.UserManager;
206import android.os.UserManagerInternal;
207import android.os.storage.IStorageManager;
208import android.os.storage.StorageEventListener;
209import android.os.storage.StorageManager;
210import android.os.storage.StorageManagerInternal;
211import android.os.storage.VolumeInfo;
212import android.os.storage.VolumeRecord;
213import android.provider.Settings.Global;
214import android.provider.Settings.Secure;
215import android.security.KeyStore;
216import android.security.SystemKeyStore;
217import android.service.pm.PackageServiceDumpProto;
218import android.system.ErrnoException;
219import android.system.Os;
220import android.text.TextUtils;
221import android.text.format.DateUtils;
222import android.util.ArrayMap;
223import android.util.ArraySet;
224import android.util.Base64;
225import android.util.BootTimingsTraceLog;
226import android.util.DisplayMetrics;
227import android.util.EventLog;
228import android.util.ExceptionUtils;
229import android.util.Log;
230import android.util.LogPrinter;
231import android.util.MathUtils;
232import android.util.PackageUtils;
233import android.util.Pair;
234import android.util.PrintStreamPrinter;
235import android.util.Slog;
236import android.util.SparseArray;
237import android.util.SparseBooleanArray;
238import android.util.SparseIntArray;
239import android.util.Xml;
240import android.util.jar.StrictJarFile;
241import android.util.proto.ProtoOutputStream;
242import android.view.Display;
243
244import com.android.internal.R;
245import com.android.internal.annotations.GuardedBy;
246import com.android.internal.app.IMediaContainerService;
247import com.android.internal.app.ResolverActivity;
248import com.android.internal.content.NativeLibraryHelper;
249import com.android.internal.content.PackageHelper;
250import com.android.internal.logging.MetricsLogger;
251import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
252import com.android.internal.os.IParcelFileDescriptorFactory;
253import com.android.internal.os.RoSystemProperties;
254import com.android.internal.os.SomeArgs;
255import com.android.internal.os.Zygote;
256import com.android.internal.telephony.CarrierAppUtils;
257import com.android.internal.util.ArrayUtils;
258import com.android.internal.util.ConcurrentUtils;
259import com.android.internal.util.DumpUtils;
260import com.android.internal.util.FastPrintWriter;
261import com.android.internal.util.FastXmlSerializer;
262import com.android.internal.util.IndentingPrintWriter;
263import com.android.internal.util.Preconditions;
264import com.android.internal.util.XmlUtils;
265import com.android.server.AttributeCache;
266import com.android.server.DeviceIdleController;
267import com.android.server.EventLogTags;
268import com.android.server.FgThread;
269import com.android.server.IntentResolver;
270import com.android.server.LocalServices;
271import com.android.server.LockGuard;
272import com.android.server.ServiceThread;
273import com.android.server.SystemConfig;
274import com.android.server.SystemServerInitThreadPool;
275import com.android.server.Watchdog;
276import com.android.server.net.NetworkPolicyManagerInternal;
277import com.android.server.pm.Installer.InstallerException;
278import com.android.server.pm.PermissionsState.PermissionState;
279import com.android.server.pm.Settings.DatabaseVersion;
280import com.android.server.pm.Settings.VersionInfo;
281import com.android.server.pm.dex.DexManager;
282import com.android.server.storage.DeviceStorageMonitorInternal;
283
284import dalvik.system.CloseGuard;
285import dalvik.system.DexFile;
286import dalvik.system.VMRuntime;
287
288import libcore.io.IoUtils;
289import libcore.util.EmptyArray;
290
291import org.xmlpull.v1.XmlPullParser;
292import org.xmlpull.v1.XmlPullParserException;
293import org.xmlpull.v1.XmlSerializer;
294
295import java.io.BufferedOutputStream;
296import java.io.BufferedReader;
297import java.io.ByteArrayInputStream;
298import java.io.ByteArrayOutputStream;
299import java.io.File;
300import java.io.FileDescriptor;
301import java.io.FileInputStream;
302import java.io.FileOutputStream;
303import java.io.FileReader;
304import java.io.FilenameFilter;
305import java.io.IOException;
306import java.io.PrintWriter;
307import java.lang.annotation.Retention;
308import java.lang.annotation.RetentionPolicy;
309import java.nio.charset.StandardCharsets;
310import java.security.DigestInputStream;
311import java.security.MessageDigest;
312import java.security.NoSuchAlgorithmException;
313import java.security.PublicKey;
314import java.security.SecureRandom;
315import java.security.cert.Certificate;
316import java.security.cert.CertificateEncodingException;
317import java.security.cert.CertificateException;
318import java.text.SimpleDateFormat;
319import java.util.ArrayList;
320import java.util.Arrays;
321import java.util.Collection;
322import java.util.Collections;
323import java.util.Comparator;
324import java.util.Date;
325import java.util.HashMap;
326import java.util.HashSet;
327import java.util.Iterator;
328import java.util.List;
329import java.util.Map;
330import java.util.Objects;
331import java.util.Set;
332import java.util.concurrent.CountDownLatch;
333import java.util.concurrent.Future;
334import java.util.concurrent.TimeUnit;
335import java.util.concurrent.atomic.AtomicBoolean;
336import java.util.concurrent.atomic.AtomicInteger;
337
338/**
339 * Keep track of all those APKs everywhere.
340 * <p>
341 * Internally there are two important locks:
342 * <ul>
343 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
344 * and other related state. It is a fine-grained lock that should only be held
345 * momentarily, as it's one of the most contended locks in the system.
346 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
347 * operations typically involve heavy lifting of application data on disk. Since
348 * {@code installd} is single-threaded, and it's operations can often be slow,
349 * this lock should never be acquired while already holding {@link #mPackages}.
350 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
351 * holding {@link #mInstallLock}.
352 * </ul>
353 * Many internal methods rely on the caller to hold the appropriate locks, and
354 * this contract is expressed through method name suffixes:
355 * <ul>
356 * <li>fooLI(): the caller must hold {@link #mInstallLock}
357 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
358 * being modified must be frozen
359 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
360 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
361 * </ul>
362 * <p>
363 * Because this class is very central to the platform's security; please run all
364 * CTS and unit tests whenever making modifications:
365 *
366 * <pre>
367 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
368 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
369 * </pre>
370 */
371public class PackageManagerService extends IPackageManager.Stub
372        implements PackageSender {
373    static final String TAG = "PackageManager";
374    static final boolean DEBUG_SETTINGS = false;
375    static final boolean DEBUG_PREFERRED = false;
376    static final boolean DEBUG_UPGRADE = false;
377    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
378    private static final boolean DEBUG_BACKUP = false;
379    private static final boolean DEBUG_INSTALL = false;
380    private static final boolean DEBUG_REMOVE = false;
381    private static final boolean DEBUG_BROADCASTS = false;
382    private static final boolean DEBUG_SHOW_INFO = false;
383    private static final boolean DEBUG_PACKAGE_INFO = false;
384    private static final boolean DEBUG_INTENT_MATCHING = false;
385    private static final boolean DEBUG_PACKAGE_SCANNING = false;
386    private static final boolean DEBUG_VERIFY = false;
387    private static final boolean DEBUG_FILTERS = false;
388    private static final boolean DEBUG_PERMISSIONS = false;
389    private static final boolean DEBUG_SHARED_LIBRARIES = false;
390
391    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
392    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
393    // user, but by default initialize to this.
394    public static final boolean DEBUG_DEXOPT = false;
395
396    private static final boolean DEBUG_ABI_SELECTION = false;
397    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
398    private static final boolean DEBUG_TRIAGED_MISSING = false;
399    private static final boolean DEBUG_APP_DATA = false;
400
401    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
402    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
403
404    private static final boolean HIDE_EPHEMERAL_APIS = false;
405
406    private static final boolean ENABLE_FREE_CACHE_V2 =
407            SystemProperties.getBoolean("fw.free_cache_v2", true);
408
409    private static final int RADIO_UID = Process.PHONE_UID;
410    private static final int LOG_UID = Process.LOG_UID;
411    private static final int NFC_UID = Process.NFC_UID;
412    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
413    private static final int SHELL_UID = Process.SHELL_UID;
414
415    // Cap the size of permission trees that 3rd party apps can define
416    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
417
418    // Suffix used during package installation when copying/moving
419    // package apks to install directory.
420    private static final String INSTALL_PACKAGE_SUFFIX = "-";
421
422    static final int SCAN_NO_DEX = 1<<1;
423    static final int SCAN_FORCE_DEX = 1<<2;
424    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
425    static final int SCAN_NEW_INSTALL = 1<<4;
426    static final int SCAN_UPDATE_TIME = 1<<5;
427    static final int SCAN_BOOTING = 1<<6;
428    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
429    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
430    static final int SCAN_REPLACING = 1<<9;
431    static final int SCAN_REQUIRE_KNOWN = 1<<10;
432    static final int SCAN_MOVE = 1<<11;
433    static final int SCAN_INITIAL = 1<<12;
434    static final int SCAN_CHECK_ONLY = 1<<13;
435    static final int SCAN_DONT_KILL_APP = 1<<14;
436    static final int SCAN_IGNORE_FROZEN = 1<<15;
437    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
438    static final int SCAN_AS_INSTANT_APP = 1<<17;
439    static final int SCAN_AS_FULL_APP = 1<<18;
440    /** Should not be with the scan flags */
441    static final int FLAGS_REMOVE_CHATTY = 1<<31;
442
443    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
444
445    private static final int[] EMPTY_INT_ARRAY = new int[0];
446
447    private static final int TYPE_UNKNOWN = 0;
448    private static final int TYPE_ACTIVITY = 1;
449    private static final int TYPE_RECEIVER = 2;
450    private static final int TYPE_SERVICE = 3;
451    private static final int TYPE_PROVIDER = 4;
452    @IntDef(prefix = { "TYPE_" }, value = {
453            TYPE_UNKNOWN,
454            TYPE_ACTIVITY,
455            TYPE_RECEIVER,
456            TYPE_SERVICE,
457            TYPE_PROVIDER,
458    })
459    @Retention(RetentionPolicy.SOURCE)
460    public @interface ComponentType {}
461
462    /**
463     * Timeout (in milliseconds) after which the watchdog should declare that
464     * our handler thread is wedged.  The usual default for such things is one
465     * minute but we sometimes do very lengthy I/O operations on this thread,
466     * such as installing multi-gigabyte applications, so ours needs to be longer.
467     */
468    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
469
470    /**
471     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
472     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
473     * settings entry if available, otherwise we use the hardcoded default.  If it's been
474     * more than this long since the last fstrim, we force one during the boot sequence.
475     *
476     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
477     * one gets run at the next available charging+idle time.  This final mandatory
478     * no-fstrim check kicks in only of the other scheduling criteria is never met.
479     */
480    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
481
482    /**
483     * Whether verification is enabled by default.
484     */
485    private static final boolean DEFAULT_VERIFY_ENABLE = true;
486
487    /**
488     * The default maximum time to wait for the verification agent to return in
489     * milliseconds.
490     */
491    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
492
493    /**
494     * The default response for package verification timeout.
495     *
496     * This can be either PackageManager.VERIFICATION_ALLOW or
497     * PackageManager.VERIFICATION_REJECT.
498     */
499    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
500
501    static final String PLATFORM_PACKAGE_NAME = "android";
502
503    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
504
505    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
506            DEFAULT_CONTAINER_PACKAGE,
507            "com.android.defcontainer.DefaultContainerService");
508
509    private static final String KILL_APP_REASON_GIDS_CHANGED =
510            "permission grant or revoke changed gids";
511
512    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
513            "permissions revoked";
514
515    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
516
517    private static final String PACKAGE_SCHEME = "package";
518
519    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
520
521    /** Permission grant: not grant the permission. */
522    private static final int GRANT_DENIED = 1;
523
524    /** Permission grant: grant the permission as an install permission. */
525    private static final int GRANT_INSTALL = 2;
526
527    /** Permission grant: grant the permission as a runtime one. */
528    private static final int GRANT_RUNTIME = 3;
529
530    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
531    private static final int GRANT_UPGRADE = 4;
532
533    /** Canonical intent used to identify what counts as a "web browser" app */
534    private static final Intent sBrowserIntent;
535    static {
536        sBrowserIntent = new Intent();
537        sBrowserIntent.setAction(Intent.ACTION_VIEW);
538        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
539        sBrowserIntent.setData(Uri.parse("http:"));
540    }
541
542    /**
543     * The set of all protected actions [i.e. those actions for which a high priority
544     * intent filter is disallowed].
545     */
546    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
547    static {
548        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
549        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
550        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
551        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
552    }
553
554    // Compilation reasons.
555    public static final int REASON_FIRST_BOOT = 0;
556    public static final int REASON_BOOT = 1;
557    public static final int REASON_INSTALL = 2;
558    public static final int REASON_BACKGROUND_DEXOPT = 3;
559    public static final int REASON_AB_OTA = 4;
560
561    public static final int REASON_LAST = REASON_AB_OTA;
562
563    /** All dangerous permission names in the same order as the events in MetricsEvent */
564    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
565            Manifest.permission.READ_CALENDAR,
566            Manifest.permission.WRITE_CALENDAR,
567            Manifest.permission.CAMERA,
568            Manifest.permission.READ_CONTACTS,
569            Manifest.permission.WRITE_CONTACTS,
570            Manifest.permission.GET_ACCOUNTS,
571            Manifest.permission.ACCESS_FINE_LOCATION,
572            Manifest.permission.ACCESS_COARSE_LOCATION,
573            Manifest.permission.RECORD_AUDIO,
574            Manifest.permission.READ_PHONE_STATE,
575            Manifest.permission.CALL_PHONE,
576            Manifest.permission.READ_CALL_LOG,
577            Manifest.permission.WRITE_CALL_LOG,
578            Manifest.permission.ADD_VOICEMAIL,
579            Manifest.permission.USE_SIP,
580            Manifest.permission.PROCESS_OUTGOING_CALLS,
581            Manifest.permission.READ_CELL_BROADCASTS,
582            Manifest.permission.BODY_SENSORS,
583            Manifest.permission.SEND_SMS,
584            Manifest.permission.RECEIVE_SMS,
585            Manifest.permission.READ_SMS,
586            Manifest.permission.RECEIVE_WAP_PUSH,
587            Manifest.permission.RECEIVE_MMS,
588            Manifest.permission.READ_EXTERNAL_STORAGE,
589            Manifest.permission.WRITE_EXTERNAL_STORAGE,
590            Manifest.permission.READ_PHONE_NUMBERS,
591            Manifest.permission.ANSWER_PHONE_CALLS);
592
593
594    /**
595     * Version number for the package parser cache. Increment this whenever the format or
596     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
597     */
598    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
599
600    /**
601     * Whether the package parser cache is enabled.
602     */
603    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
604
605    final ServiceThread mHandlerThread;
606
607    final PackageHandler mHandler;
608
609    private final ProcessLoggingHandler mProcessLoggingHandler;
610
611    /**
612     * Messages for {@link #mHandler} that need to wait for system ready before
613     * being dispatched.
614     */
615    private ArrayList<Message> mPostSystemReadyMessages;
616
617    final int mSdkVersion = Build.VERSION.SDK_INT;
618
619    final Context mContext;
620    final boolean mFactoryTest;
621    final boolean mOnlyCore;
622    final DisplayMetrics mMetrics;
623    final int mDefParseFlags;
624    final String[] mSeparateProcesses;
625    final boolean mIsUpgrade;
626    final boolean mIsPreNUpgrade;
627    final boolean mIsPreNMR1Upgrade;
628
629    // Have we told the Activity Manager to whitelist the default container service by uid yet?
630    @GuardedBy("mPackages")
631    boolean mDefaultContainerWhitelisted = false;
632
633    @GuardedBy("mPackages")
634    private boolean mDexOptDialogShown;
635
636    /** The location for ASEC container files on internal storage. */
637    final String mAsecInternalPath;
638
639    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
640    // LOCK HELD.  Can be called with mInstallLock held.
641    @GuardedBy("mInstallLock")
642    final Installer mInstaller;
643
644    /** Directory where installed third-party apps stored */
645    final File mAppInstallDir;
646
647    /**
648     * Directory to which applications installed internally have their
649     * 32 bit native libraries copied.
650     */
651    private File mAppLib32InstallDir;
652
653    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
654    // apps.
655    final File mDrmAppPrivateInstallDir;
656
657    // ----------------------------------------------------------------
658
659    // Lock for state used when installing and doing other long running
660    // operations.  Methods that must be called with this lock held have
661    // the suffix "LI".
662    final Object mInstallLock = new Object();
663
664    // ----------------------------------------------------------------
665
666    // Keys are String (package name), values are Package.  This also serves
667    // as the lock for the global state.  Methods that must be called with
668    // this lock held have the prefix "LP".
669    @GuardedBy("mPackages")
670    final ArrayMap<String, PackageParser.Package> mPackages =
671            new ArrayMap<String, PackageParser.Package>();
672
673    final ArrayMap<String, Set<String>> mKnownCodebase =
674            new ArrayMap<String, Set<String>>();
675
676    // Keys are isolated uids and values are the uid of the application
677    // that created the isolated proccess.
678    @GuardedBy("mPackages")
679    final SparseIntArray mIsolatedOwners = new SparseIntArray();
680
681    /**
682     * Tracks new system packages [received in an OTA] that we expect to
683     * find updated user-installed versions. Keys are package name, values
684     * are package location.
685     */
686    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
687    /**
688     * Tracks high priority intent filters for protected actions. During boot, certain
689     * filter actions are protected and should never be allowed to have a high priority
690     * intent filter for them. However, there is one, and only one exception -- the
691     * setup wizard. It must be able to define a high priority intent filter for these
692     * actions to ensure there are no escapes from the wizard. We need to delay processing
693     * of these during boot as we need to look at all of the system packages in order
694     * to know which component is the setup wizard.
695     */
696    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
697    /**
698     * Whether or not processing protected filters should be deferred.
699     */
700    private boolean mDeferProtectedFilters = true;
701
702    /**
703     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
704     */
705    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
706    /**
707     * Whether or not system app permissions should be promoted from install to runtime.
708     */
709    boolean mPromoteSystemApps;
710
711    @GuardedBy("mPackages")
712    final Settings mSettings;
713
714    /**
715     * Set of package names that are currently "frozen", which means active
716     * surgery is being done on the code/data for that package. The platform
717     * will refuse to launch frozen packages to avoid race conditions.
718     *
719     * @see PackageFreezer
720     */
721    @GuardedBy("mPackages")
722    final ArraySet<String> mFrozenPackages = new ArraySet<>();
723
724    final ProtectedPackages mProtectedPackages;
725
726    boolean mFirstBoot;
727
728    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
729
730    // System configuration read by SystemConfig.
731    final int[] mGlobalGids;
732    final SparseArray<ArraySet<String>> mSystemPermissions;
733    @GuardedBy("mAvailableFeatures")
734    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
735
736    // If mac_permissions.xml was found for seinfo labeling.
737    boolean mFoundPolicyFile;
738
739    private final InstantAppRegistry mInstantAppRegistry;
740
741    @GuardedBy("mPackages")
742    int mChangedPackagesSequenceNumber;
743    /**
744     * List of changed [installed, removed or updated] packages.
745     * mapping from user id -> sequence number -> package name
746     */
747    @GuardedBy("mPackages")
748    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
749    /**
750     * The sequence number of the last change to a package.
751     * mapping from user id -> package name -> sequence number
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
755
756    class PackageParserCallback implements PackageParser.Callback {
757        @Override public final boolean hasFeature(String feature) {
758            return PackageManagerService.this.hasSystemFeature(feature, 0);
759        }
760
761        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
762                Collection<PackageParser.Package> allPackages, String targetPackageName) {
763            List<PackageParser.Package> overlayPackages = null;
764            for (PackageParser.Package p : allPackages) {
765                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
766                    if (overlayPackages == null) {
767                        overlayPackages = new ArrayList<PackageParser.Package>();
768                    }
769                    overlayPackages.add(p);
770                }
771            }
772            if (overlayPackages != null) {
773                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
774                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
775                        return p1.mOverlayPriority - p2.mOverlayPriority;
776                    }
777                };
778                Collections.sort(overlayPackages, cmp);
779            }
780            return overlayPackages;
781        }
782
783        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
784                String targetPackageName, String targetPath) {
785            if ("android".equals(targetPackageName)) {
786                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                // native AssetManager.
788                return null;
789            }
790            List<PackageParser.Package> overlayPackages =
791                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
792            if (overlayPackages == null || overlayPackages.isEmpty()) {
793                return null;
794            }
795            List<String> overlayPathList = null;
796            for (PackageParser.Package overlayPackage : overlayPackages) {
797                if (targetPath == null) {
798                    if (overlayPathList == null) {
799                        overlayPathList = new ArrayList<String>();
800                    }
801                    overlayPathList.add(overlayPackage.baseCodePath);
802                    continue;
803                }
804
805                try {
806                    // Creates idmaps for system to parse correctly the Android manifest of the
807                    // target package.
808                    //
809                    // OverlayManagerService will update each of them with a correct gid from its
810                    // target package app id.
811                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
812                            UserHandle.getSharedAppGid(
813                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
814                    if (overlayPathList == null) {
815                        overlayPathList = new ArrayList<String>();
816                    }
817                    overlayPathList.add(overlayPackage.baseCodePath);
818                } catch (InstallerException e) {
819                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
820                            overlayPackage.baseCodePath);
821                }
822            }
823            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
824        }
825
826        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
827            synchronized (mPackages) {
828                return getStaticOverlayPathsLocked(
829                        mPackages.values(), targetPackageName, targetPath);
830            }
831        }
832
833        @Override public final String[] getOverlayApks(String targetPackageName) {
834            return getStaticOverlayPaths(targetPackageName, null);
835        }
836
837        @Override public final String[] getOverlayPaths(String targetPackageName,
838                String targetPath) {
839            return getStaticOverlayPaths(targetPackageName, targetPath);
840        }
841    };
842
843    class ParallelPackageParserCallback extends PackageParserCallback {
844        List<PackageParser.Package> mOverlayPackages = null;
845
846        void findStaticOverlayPackages() {
847            synchronized (mPackages) {
848                for (PackageParser.Package p : mPackages.values()) {
849                    if (p.mIsStaticOverlay) {
850                        if (mOverlayPackages == null) {
851                            mOverlayPackages = new ArrayList<PackageParser.Package>();
852                        }
853                        mOverlayPackages.add(p);
854                    }
855                }
856            }
857        }
858
859        @Override
860        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
861            // We can trust mOverlayPackages without holding mPackages because package uninstall
862            // can't happen while running parallel parsing.
863            // Moreover holding mPackages on each parsing thread causes dead-lock.
864            return mOverlayPackages == null ? null :
865                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
866        }
867    }
868
869    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
870    final ParallelPackageParserCallback mParallelPackageParserCallback =
871            new ParallelPackageParserCallback();
872
873    public static final class SharedLibraryEntry {
874        public final @Nullable String path;
875        public final @Nullable String apk;
876        public final @NonNull SharedLibraryInfo info;
877
878        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
879                String declaringPackageName, int declaringPackageVersionCode) {
880            path = _path;
881            apk = _apk;
882            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
883                    declaringPackageName, declaringPackageVersionCode), null);
884        }
885    }
886
887    // Currently known shared libraries.
888    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
889    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
890            new ArrayMap<>();
891
892    // All available activities, for your resolving pleasure.
893    final ActivityIntentResolver mActivities =
894            new ActivityIntentResolver();
895
896    // All available receivers, for your resolving pleasure.
897    final ActivityIntentResolver mReceivers =
898            new ActivityIntentResolver();
899
900    // All available services, for your resolving pleasure.
901    final ServiceIntentResolver mServices = new ServiceIntentResolver();
902
903    // All available providers, for your resolving pleasure.
904    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
905
906    // Mapping from provider base names (first directory in content URI codePath)
907    // to the provider information.
908    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
909            new ArrayMap<String, PackageParser.Provider>();
910
911    // Mapping from instrumentation class names to info about them.
912    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
913            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
914
915    // Mapping from permission names to info about them.
916    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
917            new ArrayMap<String, PackageParser.PermissionGroup>();
918
919    // Packages whose data we have transfered into another package, thus
920    // should no longer exist.
921    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
922
923    // Broadcast actions that are only available to the system.
924    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
925
926    /** List of packages waiting for verification. */
927    final SparseArray<PackageVerificationState> mPendingVerification
928            = new SparseArray<PackageVerificationState>();
929
930    /** Set of packages associated with each app op permission. */
931    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
932
933    final PackageInstallerService mInstallerService;
934
935    private final PackageDexOptimizer mPackageDexOptimizer;
936    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
937    // is used by other apps).
938    private final DexManager mDexManager;
939
940    private AtomicInteger mNextMoveId = new AtomicInteger();
941    private final MoveCallbacks mMoveCallbacks;
942
943    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
944
945    // Cache of users who need badging.
946    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
947
948    /** Token for keys in mPendingVerification. */
949    private int mPendingVerificationToken = 0;
950
951    volatile boolean mSystemReady;
952    volatile boolean mSafeMode;
953    volatile boolean mHasSystemUidErrors;
954    private volatile boolean mEphemeralAppsDisabled;
955
956    ApplicationInfo mAndroidApplication;
957    final ActivityInfo mResolveActivity = new ActivityInfo();
958    final ResolveInfo mResolveInfo = new ResolveInfo();
959    ComponentName mResolveComponentName;
960    PackageParser.Package mPlatformPackage;
961    ComponentName mCustomResolverComponentName;
962
963    boolean mResolverReplaced = false;
964
965    private final @Nullable ComponentName mIntentFilterVerifierComponent;
966    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
967
968    private int mIntentFilterVerificationToken = 0;
969
970    /** The service connection to the ephemeral resolver */
971    final EphemeralResolverConnection mInstantAppResolverConnection;
972    /** Component used to show resolver settings for Instant Apps */
973    final ComponentName mInstantAppResolverSettingsComponent;
974
975    /** Activity used to install instant applications */
976    ActivityInfo mInstantAppInstallerActivity;
977    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
978
979    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
980            = new SparseArray<IntentFilterVerificationState>();
981
982    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
983
984    // List of packages names to keep cached, even if they are uninstalled for all users
985    private List<String> mKeepUninstalledPackages;
986
987    private UserManagerInternal mUserManagerInternal;
988
989    private DeviceIdleController.LocalService mDeviceIdleController;
990
991    private File mCacheDir;
992
993    private ArraySet<String> mPrivappPermissionsViolations;
994
995    private Future<?> mPrepareAppDataFuture;
996
997    private static class IFVerificationParams {
998        PackageParser.Package pkg;
999        boolean replacing;
1000        int userId;
1001        int verifierUid;
1002
1003        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1004                int _userId, int _verifierUid) {
1005            pkg = _pkg;
1006            replacing = _replacing;
1007            userId = _userId;
1008            replacing = _replacing;
1009            verifierUid = _verifierUid;
1010        }
1011    }
1012
1013    private interface IntentFilterVerifier<T extends IntentFilter> {
1014        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1015                                               T filter, String packageName);
1016        void startVerifications(int userId);
1017        void receiveVerificationResponse(int verificationId);
1018    }
1019
1020    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1021        private Context mContext;
1022        private ComponentName mIntentFilterVerifierComponent;
1023        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1024
1025        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1026            mContext = context;
1027            mIntentFilterVerifierComponent = verifierComponent;
1028        }
1029
1030        private String getDefaultScheme() {
1031            return IntentFilter.SCHEME_HTTPS;
1032        }
1033
1034        @Override
1035        public void startVerifications(int userId) {
1036            // Launch verifications requests
1037            int count = mCurrentIntentFilterVerifications.size();
1038            for (int n=0; n<count; n++) {
1039                int verificationId = mCurrentIntentFilterVerifications.get(n);
1040                final IntentFilterVerificationState ivs =
1041                        mIntentFilterVerificationStates.get(verificationId);
1042
1043                String packageName = ivs.getPackageName();
1044
1045                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1046                final int filterCount = filters.size();
1047                ArraySet<String> domainsSet = new ArraySet<>();
1048                for (int m=0; m<filterCount; m++) {
1049                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1050                    domainsSet.addAll(filter.getHostsList());
1051                }
1052                synchronized (mPackages) {
1053                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1054                            packageName, domainsSet) != null) {
1055                        scheduleWriteSettingsLocked();
1056                    }
1057                }
1058                sendVerificationRequest(userId, verificationId, ivs);
1059            }
1060            mCurrentIntentFilterVerifications.clear();
1061        }
1062
1063        private void sendVerificationRequest(int userId, int verificationId,
1064                IntentFilterVerificationState ivs) {
1065
1066            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1067            verificationIntent.putExtra(
1068                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1069                    verificationId);
1070            verificationIntent.putExtra(
1071                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1072                    getDefaultScheme());
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1075                    ivs.getHostsString());
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1078                    ivs.getPackageName());
1079            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1080            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1081
1082            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1083            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1084                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1085                    userId, false, "intent filter verifier");
1086
1087            UserHandle user = new UserHandle(userId);
1088            mContext.sendBroadcastAsUser(verificationIntent, user);
1089            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1090                    "Sending IntentFilter verification broadcast");
1091        }
1092
1093        public void receiveVerificationResponse(int verificationId) {
1094            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1095
1096            final boolean verified = ivs.isVerified();
1097
1098            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1099            final int count = filters.size();
1100            if (DEBUG_DOMAIN_VERIFICATION) {
1101                Slog.i(TAG, "Received verification response " + verificationId
1102                        + " for " + count + " filters, verified=" + verified);
1103            }
1104            for (int n=0; n<count; n++) {
1105                PackageParser.ActivityIntentInfo filter = filters.get(n);
1106                filter.setVerified(verified);
1107
1108                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1109                        + " verified with result:" + verified + " and hosts:"
1110                        + ivs.getHostsString());
1111            }
1112
1113            mIntentFilterVerificationStates.remove(verificationId);
1114
1115            final String packageName = ivs.getPackageName();
1116            IntentFilterVerificationInfo ivi = null;
1117
1118            synchronized (mPackages) {
1119                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1120            }
1121            if (ivi == null) {
1122                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1123                        + verificationId + " packageName:" + packageName);
1124                return;
1125            }
1126            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1127                    "Updating IntentFilterVerificationInfo for package " + packageName
1128                            +" verificationId:" + verificationId);
1129
1130            synchronized (mPackages) {
1131                if (verified) {
1132                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1133                } else {
1134                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1135                }
1136                scheduleWriteSettingsLocked();
1137
1138                final int userId = ivs.getUserId();
1139                if (userId != UserHandle.USER_ALL) {
1140                    final int userStatus =
1141                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1142
1143                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1144                    boolean needUpdate = false;
1145
1146                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1147                    // already been set by the User thru the Disambiguation dialog
1148                    switch (userStatus) {
1149                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1150                            if (verified) {
1151                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1152                            } else {
1153                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1154                            }
1155                            needUpdate = true;
1156                            break;
1157
1158                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1159                            if (verified) {
1160                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1161                                needUpdate = true;
1162                            }
1163                            break;
1164
1165                        default:
1166                            // Nothing to do
1167                    }
1168
1169                    if (needUpdate) {
1170                        mSettings.updateIntentFilterVerificationStatusLPw(
1171                                packageName, updatedStatus, userId);
1172                        scheduleWritePackageRestrictionsLocked(userId);
1173                    }
1174                }
1175            }
1176        }
1177
1178        @Override
1179        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1180                    ActivityIntentInfo filter, String packageName) {
1181            if (!hasValidDomains(filter)) {
1182                return false;
1183            }
1184            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1185            if (ivs == null) {
1186                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1187                        packageName);
1188            }
1189            if (DEBUG_DOMAIN_VERIFICATION) {
1190                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1191            }
1192            ivs.addFilter(filter);
1193            return true;
1194        }
1195
1196        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1197                int userId, int verificationId, String packageName) {
1198            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1199                    verifierUid, userId, packageName);
1200            ivs.setPendingState();
1201            synchronized (mPackages) {
1202                mIntentFilterVerificationStates.append(verificationId, ivs);
1203                mCurrentIntentFilterVerifications.add(verificationId);
1204            }
1205            return ivs;
1206        }
1207    }
1208
1209    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1210        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1211                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1212                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1213    }
1214
1215    // Set of pending broadcasts for aggregating enable/disable of components.
1216    static class PendingPackageBroadcasts {
1217        // for each user id, a map of <package name -> components within that package>
1218        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1219
1220        public PendingPackageBroadcasts() {
1221            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1222        }
1223
1224        public ArrayList<String> get(int userId, String packageName) {
1225            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1226            return packages.get(packageName);
1227        }
1228
1229        public void put(int userId, String packageName, ArrayList<String> components) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            packages.put(packageName, components);
1232        }
1233
1234        public void remove(int userId, String packageName) {
1235            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1236            if (packages != null) {
1237                packages.remove(packageName);
1238            }
1239        }
1240
1241        public void remove(int userId) {
1242            mUidMap.remove(userId);
1243        }
1244
1245        public int userIdCount() {
1246            return mUidMap.size();
1247        }
1248
1249        public int userIdAt(int n) {
1250            return mUidMap.keyAt(n);
1251        }
1252
1253        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1254            return mUidMap.get(userId);
1255        }
1256
1257        public int size() {
1258            // total number of pending broadcast entries across all userIds
1259            int num = 0;
1260            for (int i = 0; i< mUidMap.size(); i++) {
1261                num += mUidMap.valueAt(i).size();
1262            }
1263            return num;
1264        }
1265
1266        public void clear() {
1267            mUidMap.clear();
1268        }
1269
1270        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1271            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1272            if (map == null) {
1273                map = new ArrayMap<String, ArrayList<String>>();
1274                mUidMap.put(userId, map);
1275            }
1276            return map;
1277        }
1278    }
1279    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1280
1281    // Service Connection to remote media container service to copy
1282    // package uri's from external media onto secure containers
1283    // or internal storage.
1284    private IMediaContainerService mContainerService = null;
1285
1286    static final int SEND_PENDING_BROADCAST = 1;
1287    static final int MCS_BOUND = 3;
1288    static final int END_COPY = 4;
1289    static final int INIT_COPY = 5;
1290    static final int MCS_UNBIND = 6;
1291    static final int START_CLEANING_PACKAGE = 7;
1292    static final int FIND_INSTALL_LOC = 8;
1293    static final int POST_INSTALL = 9;
1294    static final int MCS_RECONNECT = 10;
1295    static final int MCS_GIVE_UP = 11;
1296    static final int UPDATED_MEDIA_STATUS = 12;
1297    static final int WRITE_SETTINGS = 13;
1298    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1299    static final int PACKAGE_VERIFIED = 15;
1300    static final int CHECK_PENDING_VERIFICATION = 16;
1301    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1302    static final int INTENT_FILTER_VERIFIED = 18;
1303    static final int WRITE_PACKAGE_LIST = 19;
1304    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1305
1306    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1307
1308    // Delay time in millisecs
1309    static final int BROADCAST_DELAY = 10 * 1000;
1310
1311    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1312            2 * 60 * 60 * 1000L; /* two hours */
1313
1314    static UserManagerService sUserManager;
1315
1316    // Stores a list of users whose package restrictions file needs to be updated
1317    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1318
1319    final private DefaultContainerConnection mDefContainerConn =
1320            new DefaultContainerConnection();
1321    class DefaultContainerConnection implements ServiceConnection {
1322        public void onServiceConnected(ComponentName name, IBinder service) {
1323            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1324            final IMediaContainerService imcs = IMediaContainerService.Stub
1325                    .asInterface(Binder.allowBlocking(service));
1326            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1327        }
1328
1329        public void onServiceDisconnected(ComponentName name) {
1330            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1331        }
1332    }
1333
1334    // Recordkeeping of restore-after-install operations that are currently in flight
1335    // between the Package Manager and the Backup Manager
1336    static class PostInstallData {
1337        public InstallArgs args;
1338        public PackageInstalledInfo res;
1339
1340        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1341            args = _a;
1342            res = _r;
1343        }
1344    }
1345
1346    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1347    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1348
1349    // XML tags for backup/restore of various bits of state
1350    private static final String TAG_PREFERRED_BACKUP = "pa";
1351    private static final String TAG_DEFAULT_APPS = "da";
1352    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1353
1354    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1355    private static final String TAG_ALL_GRANTS = "rt-grants";
1356    private static final String TAG_GRANT = "grant";
1357    private static final String ATTR_PACKAGE_NAME = "pkg";
1358
1359    private static final String TAG_PERMISSION = "perm";
1360    private static final String ATTR_PERMISSION_NAME = "name";
1361    private static final String ATTR_IS_GRANTED = "g";
1362    private static final String ATTR_USER_SET = "set";
1363    private static final String ATTR_USER_FIXED = "fixed";
1364    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1365
1366    // System/policy permission grants are not backed up
1367    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1368            FLAG_PERMISSION_POLICY_FIXED
1369            | FLAG_PERMISSION_SYSTEM_FIXED
1370            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1371
1372    // And we back up these user-adjusted states
1373    private static final int USER_RUNTIME_GRANT_MASK =
1374            FLAG_PERMISSION_USER_SET
1375            | FLAG_PERMISSION_USER_FIXED
1376            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1377
1378    final @Nullable String mRequiredVerifierPackage;
1379    final @NonNull String mRequiredInstallerPackage;
1380    final @NonNull String mRequiredUninstallerPackage;
1381    final @Nullable String mSetupWizardPackage;
1382    final @Nullable String mStorageManagerPackage;
1383    final @NonNull String mServicesSystemSharedLibraryPackageName;
1384    final @NonNull String mSharedSystemSharedLibraryPackageName;
1385
1386    final boolean mPermissionReviewRequired;
1387
1388    private final PackageUsage mPackageUsage = new PackageUsage();
1389    private final CompilerStats mCompilerStats = new CompilerStats();
1390
1391    class PackageHandler extends Handler {
1392        private boolean mBound = false;
1393        final ArrayList<HandlerParams> mPendingInstalls =
1394            new ArrayList<HandlerParams>();
1395
1396        private boolean connectToService() {
1397            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1398                    " DefaultContainerService");
1399            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1400            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1402                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1403                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                mBound = true;
1405                return true;
1406            }
1407            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408            return false;
1409        }
1410
1411        private void disconnectService() {
1412            mContainerService = null;
1413            mBound = false;
1414            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415            mContext.unbindService(mDefContainerConn);
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417        }
1418
1419        PackageHandler(Looper looper) {
1420            super(looper);
1421        }
1422
1423        public void handleMessage(Message msg) {
1424            try {
1425                doHandleMessage(msg);
1426            } finally {
1427                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428            }
1429        }
1430
1431        void doHandleMessage(Message msg) {
1432            switch (msg.what) {
1433                case INIT_COPY: {
1434                    HandlerParams params = (HandlerParams) msg.obj;
1435                    int idx = mPendingInstalls.size();
1436                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1437                    // If a bind was already initiated we dont really
1438                    // need to do anything. The pending install
1439                    // will be processed later on.
1440                    if (!mBound) {
1441                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1442                                System.identityHashCode(mHandler));
1443                        // If this is the only one pending we might
1444                        // have to bind to the service again.
1445                        if (!connectToService()) {
1446                            Slog.e(TAG, "Failed to bind to media container service");
1447                            params.serviceError();
1448                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                    System.identityHashCode(mHandler));
1450                            if (params.traceMethod != null) {
1451                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1452                                        params.traceCookie);
1453                            }
1454                            return;
1455                        } else {
1456                            // Once we bind to the service, the first
1457                            // pending request will be processed.
1458                            mPendingInstalls.add(idx, params);
1459                        }
1460                    } else {
1461                        mPendingInstalls.add(idx, params);
1462                        // Already bound to the service. Just make
1463                        // sure we trigger off processing the first request.
1464                        if (idx == 0) {
1465                            mHandler.sendEmptyMessage(MCS_BOUND);
1466                        }
1467                    }
1468                    break;
1469                }
1470                case MCS_BOUND: {
1471                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1472                    if (msg.obj != null) {
1473                        mContainerService = (IMediaContainerService) msg.obj;
1474                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                System.identityHashCode(mHandler));
1476                    }
1477                    if (mContainerService == null) {
1478                        if (!mBound) {
1479                            // Something seriously wrong since we are not bound and we are not
1480                            // waiting for connection. Bail out.
1481                            Slog.e(TAG, "Cannot bind to media container service");
1482                            for (HandlerParams params : mPendingInstalls) {
1483                                // Indicate service bind error
1484                                params.serviceError();
1485                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486                                        System.identityHashCode(params));
1487                                if (params.traceMethod != null) {
1488                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1489                                            params.traceMethod, params.traceCookie);
1490                                }
1491                                return;
1492                            }
1493                            mPendingInstalls.clear();
1494                        } else {
1495                            Slog.w(TAG, "Waiting to connect to media container service");
1496                        }
1497                    } else if (mPendingInstalls.size() > 0) {
1498                        HandlerParams params = mPendingInstalls.get(0);
1499                        if (params != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                    System.identityHashCode(params));
1502                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1503                            if (params.startCopy()) {
1504                                // We are done...  look for more work or to
1505                                // go idle.
1506                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1507                                        "Checking for more work or unbind...");
1508                                // Delete pending install
1509                                if (mPendingInstalls.size() > 0) {
1510                                    mPendingInstalls.remove(0);
1511                                }
1512                                if (mPendingInstalls.size() == 0) {
1513                                    if (mBound) {
1514                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                                "Posting delayed MCS_UNBIND");
1516                                        removeMessages(MCS_UNBIND);
1517                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1518                                        // Unbind after a little delay, to avoid
1519                                        // continual thrashing.
1520                                        sendMessageDelayed(ubmsg, 10000);
1521                                    }
1522                                } else {
1523                                    // There are more pending requests in queue.
1524                                    // Just post MCS_BOUND message to trigger processing
1525                                    // of next pending install.
1526                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                            "Posting MCS_BOUND for next work");
1528                                    mHandler.sendEmptyMessage(MCS_BOUND);
1529                                }
1530                            }
1531                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1532                        }
1533                    } else {
1534                        // Should never happen ideally.
1535                        Slog.w(TAG, "Empty queue");
1536                    }
1537                    break;
1538                }
1539                case MCS_RECONNECT: {
1540                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1541                    if (mPendingInstalls.size() > 0) {
1542                        if (mBound) {
1543                            disconnectService();
1544                        }
1545                        if (!connectToService()) {
1546                            Slog.e(TAG, "Failed to bind to media container service");
1547                            for (HandlerParams params : mPendingInstalls) {
1548                                // Indicate service bind error
1549                                params.serviceError();
1550                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1551                                        System.identityHashCode(params));
1552                            }
1553                            mPendingInstalls.clear();
1554                        }
1555                    }
1556                    break;
1557                }
1558                case MCS_UNBIND: {
1559                    // If there is no actual work left, then time to unbind.
1560                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1561
1562                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1563                        if (mBound) {
1564                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1565
1566                            disconnectService();
1567                        }
1568                    } else if (mPendingInstalls.size() > 0) {
1569                        // There are more pending requests in queue.
1570                        // Just post MCS_BOUND message to trigger processing
1571                        // of next pending install.
1572                        mHandler.sendEmptyMessage(MCS_BOUND);
1573                    }
1574
1575                    break;
1576                }
1577                case MCS_GIVE_UP: {
1578                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1579                    HandlerParams params = mPendingInstalls.remove(0);
1580                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1581                            System.identityHashCode(params));
1582                    break;
1583                }
1584                case SEND_PENDING_BROADCAST: {
1585                    String packages[];
1586                    ArrayList<String> components[];
1587                    int size = 0;
1588                    int uids[];
1589                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1590                    synchronized (mPackages) {
1591                        if (mPendingBroadcasts == null) {
1592                            return;
1593                        }
1594                        size = mPendingBroadcasts.size();
1595                        if (size <= 0) {
1596                            // Nothing to be done. Just return
1597                            return;
1598                        }
1599                        packages = new String[size];
1600                        components = new ArrayList[size];
1601                        uids = new int[size];
1602                        int i = 0;  // filling out the above arrays
1603
1604                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1605                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1606                            Iterator<Map.Entry<String, ArrayList<String>>> it
1607                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1608                                            .entrySet().iterator();
1609                            while (it.hasNext() && i < size) {
1610                                Map.Entry<String, ArrayList<String>> ent = it.next();
1611                                packages[i] = ent.getKey();
1612                                components[i] = ent.getValue();
1613                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1614                                uids[i] = (ps != null)
1615                                        ? UserHandle.getUid(packageUserId, ps.appId)
1616                                        : -1;
1617                                i++;
1618                            }
1619                        }
1620                        size = i;
1621                        mPendingBroadcasts.clear();
1622                    }
1623                    // Send broadcasts
1624                    for (int i = 0; i < size; i++) {
1625                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1626                    }
1627                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1628                    break;
1629                }
1630                case START_CLEANING_PACKAGE: {
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632                    final String packageName = (String)msg.obj;
1633                    final int userId = msg.arg1;
1634                    final boolean andCode = msg.arg2 != 0;
1635                    synchronized (mPackages) {
1636                        if (userId == UserHandle.USER_ALL) {
1637                            int[] users = sUserManager.getUserIds();
1638                            for (int user : users) {
1639                                mSettings.addPackageToCleanLPw(
1640                                        new PackageCleanItem(user, packageName, andCode));
1641                            }
1642                        } else {
1643                            mSettings.addPackageToCleanLPw(
1644                                    new PackageCleanItem(userId, packageName, andCode));
1645                        }
1646                    }
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                    startCleaningPackages();
1649                } break;
1650                case POST_INSTALL: {
1651                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1652
1653                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1654                    final boolean didRestore = (msg.arg2 != 0);
1655                    mRunningInstalls.delete(msg.arg1);
1656
1657                    if (data != null) {
1658                        InstallArgs args = data.args;
1659                        PackageInstalledInfo parentRes = data.res;
1660
1661                        final boolean grantPermissions = (args.installFlags
1662                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1663                        final boolean killApp = (args.installFlags
1664                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1665                        final String[] grantedPermissions = args.installGrantPermissions;
1666
1667                        // Handle the parent package
1668                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1669                                grantedPermissions, didRestore, args.installerPackageName,
1670                                args.observer);
1671
1672                        // Handle the child packages
1673                        final int childCount = (parentRes.addedChildPackages != null)
1674                                ? parentRes.addedChildPackages.size() : 0;
1675                        for (int i = 0; i < childCount; i++) {
1676                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1677                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1678                                    grantedPermissions, false, args.installerPackageName,
1679                                    args.observer);
1680                        }
1681
1682                        // Log tracing if needed
1683                        if (args.traceMethod != null) {
1684                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1685                                    args.traceCookie);
1686                        }
1687                    } else {
1688                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1689                    }
1690
1691                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1692                } break;
1693                case UPDATED_MEDIA_STATUS: {
1694                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1695                    boolean reportStatus = msg.arg1 == 1;
1696                    boolean doGc = msg.arg2 == 1;
1697                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1698                    if (doGc) {
1699                        // Force a gc to clear up stale containers.
1700                        Runtime.getRuntime().gc();
1701                    }
1702                    if (msg.obj != null) {
1703                        @SuppressWarnings("unchecked")
1704                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1705                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1706                        // Unload containers
1707                        unloadAllContainers(args);
1708                    }
1709                    if (reportStatus) {
1710                        try {
1711                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1712                                    "Invoking StorageManagerService call back");
1713                            PackageHelper.getStorageManager().finishMediaUpdate();
1714                        } catch (RemoteException e) {
1715                            Log.e(TAG, "StorageManagerService not running?");
1716                        }
1717                    }
1718                } break;
1719                case WRITE_SETTINGS: {
1720                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1721                    synchronized (mPackages) {
1722                        removeMessages(WRITE_SETTINGS);
1723                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1724                        mSettings.writeLPr();
1725                        mDirtyUsers.clear();
1726                    }
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                } break;
1729                case WRITE_PACKAGE_RESTRICTIONS: {
1730                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                    synchronized (mPackages) {
1732                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733                        for (int userId : mDirtyUsers) {
1734                            mSettings.writePackageRestrictionsLPr(userId);
1735                        }
1736                        mDirtyUsers.clear();
1737                    }
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                } break;
1740                case WRITE_PACKAGE_LIST: {
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                    synchronized (mPackages) {
1743                        removeMessages(WRITE_PACKAGE_LIST);
1744                        mSettings.writePackageListLPr(msg.arg1);
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case CHECK_PENDING_VERIFICATION: {
1749                    final int verificationId = msg.arg1;
1750                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1751
1752                    if ((state != null) && !state.timeoutExtended()) {
1753                        final InstallArgs args = state.getInstallArgs();
1754                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1755
1756                        Slog.i(TAG, "Verification timed out for " + originUri);
1757                        mPendingVerification.remove(verificationId);
1758
1759                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1760
1761                        final UserHandle user = args.getUser();
1762                        if (getDefaultVerificationResponse(user)
1763                                == PackageManager.VERIFICATION_ALLOW) {
1764                            Slog.i(TAG, "Continuing with installation of " + originUri);
1765                            state.setVerifierResponse(Binder.getCallingUid(),
1766                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1767                            broadcastPackageVerified(verificationId, originUri,
1768                                    PackageManager.VERIFICATION_ALLOW, user);
1769                            try {
1770                                ret = args.copyApk(mContainerService, true);
1771                            } catch (RemoteException e) {
1772                                Slog.e(TAG, "Could not contact the ContainerService");
1773                            }
1774                        } else {
1775                            broadcastPackageVerified(verificationId, originUri,
1776                                    PackageManager.VERIFICATION_REJECT, user);
1777                        }
1778
1779                        Trace.asyncTraceEnd(
1780                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1781
1782                        processPendingInstall(args, ret);
1783                        mHandler.sendEmptyMessage(MCS_UNBIND);
1784                    }
1785                    break;
1786                }
1787                case PACKAGE_VERIFIED: {
1788                    final int verificationId = msg.arg1;
1789
1790                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1791                    if (state == null) {
1792                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1793                        break;
1794                    }
1795
1796                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1797
1798                    state.setVerifierResponse(response.callerUid, response.code);
1799
1800                    if (state.isVerificationComplete()) {
1801                        mPendingVerification.remove(verificationId);
1802
1803                        final InstallArgs args = state.getInstallArgs();
1804                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1805
1806                        int ret;
1807                        if (state.isInstallAllowed()) {
1808                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1809                            broadcastPackageVerified(verificationId, originUri,
1810                                    response.code, state.getInstallArgs().getUser());
1811                            try {
1812                                ret = args.copyApk(mContainerService, true);
1813                            } catch (RemoteException e) {
1814                                Slog.e(TAG, "Could not contact the ContainerService");
1815                            }
1816                        } else {
1817                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1818                        }
1819
1820                        Trace.asyncTraceEnd(
1821                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1822
1823                        processPendingInstall(args, ret);
1824                        mHandler.sendEmptyMessage(MCS_UNBIND);
1825                    }
1826
1827                    break;
1828                }
1829                case START_INTENT_FILTER_VERIFICATIONS: {
1830                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1831                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1832                            params.replacing, params.pkg);
1833                    break;
1834                }
1835                case INTENT_FILTER_VERIFIED: {
1836                    final int verificationId = msg.arg1;
1837
1838                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1839                            verificationId);
1840                    if (state == null) {
1841                        Slog.w(TAG, "Invalid IntentFilter verification token "
1842                                + verificationId + " received");
1843                        break;
1844                    }
1845
1846                    final int userId = state.getUserId();
1847
1848                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1849                            "Processing IntentFilter verification with token:"
1850                            + verificationId + " and userId:" + userId);
1851
1852                    final IntentFilterVerificationResponse response =
1853                            (IntentFilterVerificationResponse) msg.obj;
1854
1855                    state.setVerifierResponse(response.callerUid, response.code);
1856
1857                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                            "IntentFilter verification with token:" + verificationId
1859                            + " and userId:" + userId
1860                            + " is settings verifier response with response code:"
1861                            + response.code);
1862
1863                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1864                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1865                                + response.getFailedDomainsString());
1866                    }
1867
1868                    if (state.isVerificationComplete()) {
1869                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1870                    } else {
1871                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                                "IntentFilter verification with token:" + verificationId
1873                                + " was not said to be complete");
1874                    }
1875
1876                    break;
1877                }
1878                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1879                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1880                            mInstantAppResolverConnection,
1881                            (InstantAppRequest) msg.obj,
1882                            mInstantAppInstallerActivity,
1883                            mHandler);
1884                }
1885            }
1886        }
1887    }
1888
1889    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1890            boolean killApp, String[] grantedPermissions,
1891            boolean launchedForRestore, String installerPackage,
1892            IPackageInstallObserver2 installObserver) {
1893        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1894            // Send the removed broadcasts
1895            if (res.removedInfo != null) {
1896                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1897            }
1898
1899            // Now that we successfully installed the package, grant runtime
1900            // permissions if requested before broadcasting the install. Also
1901            // for legacy apps in permission review mode we clear the permission
1902            // review flag which is used to emulate runtime permissions for
1903            // legacy apps.
1904            if (grantPermissions) {
1905                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1906            }
1907
1908            final boolean update = res.removedInfo != null
1909                    && res.removedInfo.removedPackage != null;
1910            final String origInstallerPackageName = res.removedInfo != null
1911                    ? res.removedInfo.installerPackageName : null;
1912
1913            // If this is the first time we have child packages for a disabled privileged
1914            // app that had no children, we grant requested runtime permissions to the new
1915            // children if the parent on the system image had them already granted.
1916            if (res.pkg.parentPackage != null) {
1917                synchronized (mPackages) {
1918                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1919                }
1920            }
1921
1922            synchronized (mPackages) {
1923                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1924            }
1925
1926            final String packageName = res.pkg.applicationInfo.packageName;
1927
1928            // Determine the set of users who are adding this package for
1929            // the first time vs. those who are seeing an update.
1930            int[] firstUsers = EMPTY_INT_ARRAY;
1931            int[] updateUsers = EMPTY_INT_ARRAY;
1932            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1933            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1934            for (int newUser : res.newUsers) {
1935                if (ps.getInstantApp(newUser)) {
1936                    continue;
1937                }
1938                if (allNewUsers) {
1939                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1940                    continue;
1941                }
1942                boolean isNew = true;
1943                for (int origUser : res.origUsers) {
1944                    if (origUser == newUser) {
1945                        isNew = false;
1946                        break;
1947                    }
1948                }
1949                if (isNew) {
1950                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1951                } else {
1952                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1953                }
1954            }
1955
1956            // Send installed broadcasts if the package is not a static shared lib.
1957            if (res.pkg.staticSharedLibName == null) {
1958                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1959
1960                // Send added for users that see the package for the first time
1961                // sendPackageAddedForNewUsers also deals with system apps
1962                int appId = UserHandle.getAppId(res.uid);
1963                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1964                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1965
1966                // Send added for users that don't see the package for the first time
1967                Bundle extras = new Bundle(1);
1968                extras.putInt(Intent.EXTRA_UID, res.uid);
1969                if (update) {
1970                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1971                }
1972                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1973                        extras, 0 /*flags*/,
1974                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1975                if (origInstallerPackageName != null) {
1976                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977                            extras, 0 /*flags*/,
1978                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1979                }
1980
1981                // Send replaced for users that don't see the package for the first time
1982                if (update) {
1983                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1984                            packageName, extras, 0 /*flags*/,
1985                            null /*targetPackage*/, null /*finishedReceiver*/,
1986                            updateUsers);
1987                    if (origInstallerPackageName != null) {
1988                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1989                                extras, 0 /*flags*/,
1990                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1991                    }
1992                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1993                            null /*package*/, null /*extras*/, 0 /*flags*/,
1994                            packageName /*targetPackage*/,
1995                            null /*finishedReceiver*/, updateUsers);
1996                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1997                    // First-install and we did a restore, so we're responsible for the
1998                    // first-launch broadcast.
1999                    if (DEBUG_BACKUP) {
2000                        Slog.i(TAG, "Post-restore of " + packageName
2001                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2002                    }
2003                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2004                }
2005
2006                // Send broadcast package appeared if forward locked/external for all users
2007                // treat asec-hosted packages like removable media on upgrade
2008                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2009                    if (DEBUG_INSTALL) {
2010                        Slog.i(TAG, "upgrading pkg " + res.pkg
2011                                + " is ASEC-hosted -> AVAILABLE");
2012                    }
2013                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2014                    ArrayList<String> pkgList = new ArrayList<>(1);
2015                    pkgList.add(packageName);
2016                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2017                }
2018            }
2019
2020            // Work that needs to happen on first install within each user
2021            if (firstUsers != null && firstUsers.length > 0) {
2022                synchronized (mPackages) {
2023                    for (int userId : firstUsers) {
2024                        // If this app is a browser and it's newly-installed for some
2025                        // users, clear any default-browser state in those users. The
2026                        // app's nature doesn't depend on the user, so we can just check
2027                        // its browser nature in any user and generalize.
2028                        if (packageIsBrowser(packageName, userId)) {
2029                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2030                        }
2031
2032                        // We may also need to apply pending (restored) runtime
2033                        // permission grants within these users.
2034                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2035                    }
2036                }
2037            }
2038
2039            // Log current value of "unknown sources" setting
2040            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2041                    getUnknownSourcesSettings());
2042
2043            // Remove the replaced package's older resources safely now
2044            // We delete after a gc for applications  on sdcard.
2045            if (res.removedInfo != null && res.removedInfo.args != null) {
2046                Runtime.getRuntime().gc();
2047                synchronized (mInstallLock) {
2048                    res.removedInfo.args.doPostDeleteLI(true);
2049                }
2050            } else {
2051                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2052                // and not block here.
2053                VMRuntime.getRuntime().requestConcurrentGC();
2054            }
2055
2056            // Notify DexManager that the package was installed for new users.
2057            // The updated users should already be indexed and the package code paths
2058            // should not change.
2059            // Don't notify the manager for ephemeral apps as they are not expected to
2060            // survive long enough to benefit of background optimizations.
2061            for (int userId : firstUsers) {
2062                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2063                // There's a race currently where some install events may interleave with an uninstall.
2064                // This can lead to package info being null (b/36642664).
2065                if (info != null) {
2066                    mDexManager.notifyPackageInstalled(info, userId);
2067                }
2068            }
2069        }
2070
2071        // If someone is watching installs - notify them
2072        if (installObserver != null) {
2073            try {
2074                Bundle extras = extrasForInstallResult(res);
2075                installObserver.onPackageInstalled(res.name, res.returnCode,
2076                        res.returnMsg, extras);
2077            } catch (RemoteException e) {
2078                Slog.i(TAG, "Observer no longer exists.");
2079            }
2080        }
2081    }
2082
2083    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2084            PackageParser.Package pkg) {
2085        if (pkg.parentPackage == null) {
2086            return;
2087        }
2088        if (pkg.requestedPermissions == null) {
2089            return;
2090        }
2091        final PackageSetting disabledSysParentPs = mSettings
2092                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2093        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2094                || !disabledSysParentPs.isPrivileged()
2095                || (disabledSysParentPs.childPackageNames != null
2096                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2097            return;
2098        }
2099        final int[] allUserIds = sUserManager.getUserIds();
2100        final int permCount = pkg.requestedPermissions.size();
2101        for (int i = 0; i < permCount; i++) {
2102            String permission = pkg.requestedPermissions.get(i);
2103            BasePermission bp = mSettings.mPermissions.get(permission);
2104            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2105                continue;
2106            }
2107            for (int userId : allUserIds) {
2108                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2109                        permission, userId)) {
2110                    grantRuntimePermission(pkg.packageName, permission, userId);
2111                }
2112            }
2113        }
2114    }
2115
2116    private StorageEventListener mStorageListener = new StorageEventListener() {
2117        @Override
2118        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2119            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2120                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2121                    final String volumeUuid = vol.getFsUuid();
2122
2123                    // Clean up any users or apps that were removed or recreated
2124                    // while this volume was missing
2125                    sUserManager.reconcileUsers(volumeUuid);
2126                    reconcileApps(volumeUuid);
2127
2128                    // Clean up any install sessions that expired or were
2129                    // cancelled while this volume was missing
2130                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2131
2132                    loadPrivatePackages(vol);
2133
2134                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2135                    unloadPrivatePackages(vol);
2136                }
2137            }
2138
2139            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2140                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2141                    updateExternalMediaStatus(true, false);
2142                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143                    updateExternalMediaStatus(false, false);
2144                }
2145            }
2146        }
2147
2148        @Override
2149        public void onVolumeForgotten(String fsUuid) {
2150            if (TextUtils.isEmpty(fsUuid)) {
2151                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2152                return;
2153            }
2154
2155            // Remove any apps installed on the forgotten volume
2156            synchronized (mPackages) {
2157                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2158                for (PackageSetting ps : packages) {
2159                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2160                    deletePackageVersioned(new VersionedPackage(ps.name,
2161                            PackageManager.VERSION_CODE_HIGHEST),
2162                            new LegacyPackageDeleteObserver(null).getBinder(),
2163                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2164                    // Try very hard to release any references to this package
2165                    // so we don't risk the system server being killed due to
2166                    // open FDs
2167                    AttributeCache.instance().removePackage(ps.name);
2168                }
2169
2170                mSettings.onVolumeForgotten(fsUuid);
2171                mSettings.writeLPr();
2172            }
2173        }
2174    };
2175
2176    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2177            String[] grantedPermissions) {
2178        for (int userId : userIds) {
2179            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2180        }
2181    }
2182
2183    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2184            String[] grantedPermissions) {
2185        PackageSetting ps = (PackageSetting) pkg.mExtras;
2186        if (ps == null) {
2187            return;
2188        }
2189
2190        PermissionsState permissionsState = ps.getPermissionsState();
2191
2192        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2193                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2194
2195        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2196                >= Build.VERSION_CODES.M;
2197
2198        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2199
2200        for (String permission : pkg.requestedPermissions) {
2201            final BasePermission bp;
2202            synchronized (mPackages) {
2203                bp = mSettings.mPermissions.get(permission);
2204            }
2205            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2206                    && (!instantApp || bp.isInstant())
2207                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2208                    && (grantedPermissions == null
2209                           || ArrayUtils.contains(grantedPermissions, permission))) {
2210                final int flags = permissionsState.getPermissionFlags(permission, userId);
2211                if (supportsRuntimePermissions) {
2212                    // Installer cannot change immutable permissions.
2213                    if ((flags & immutableFlags) == 0) {
2214                        grantRuntimePermission(pkg.packageName, permission, userId);
2215                    }
2216                } else if (mPermissionReviewRequired) {
2217                    // In permission review mode we clear the review flag when we
2218                    // are asked to install the app with all permissions granted.
2219                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2220                        updatePermissionFlags(permission, pkg.packageName,
2221                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2222                    }
2223                }
2224            }
2225        }
2226    }
2227
2228    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2229        Bundle extras = null;
2230        switch (res.returnCode) {
2231            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2232                extras = new Bundle();
2233                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2234                        res.origPermission);
2235                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2236                        res.origPackage);
2237                break;
2238            }
2239            case PackageManager.INSTALL_SUCCEEDED: {
2240                extras = new Bundle();
2241                extras.putBoolean(Intent.EXTRA_REPLACING,
2242                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2243                break;
2244            }
2245        }
2246        return extras;
2247    }
2248
2249    void scheduleWriteSettingsLocked() {
2250        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2251            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2252        }
2253    }
2254
2255    void scheduleWritePackageListLocked(int userId) {
2256        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2257            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2258            msg.arg1 = userId;
2259            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2260        }
2261    }
2262
2263    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2264        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2265        scheduleWritePackageRestrictionsLocked(userId);
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(int userId) {
2269        final int[] userIds = (userId == UserHandle.USER_ALL)
2270                ? sUserManager.getUserIds() : new int[]{userId};
2271        for (int nextUserId : userIds) {
2272            if (!sUserManager.exists(nextUserId)) return;
2273            mDirtyUsers.add(nextUserId);
2274            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2275                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2276            }
2277        }
2278    }
2279
2280    public static PackageManagerService main(Context context, Installer installer,
2281            boolean factoryTest, boolean onlyCore) {
2282        // Self-check for initial settings.
2283        PackageManagerServiceCompilerMapping.checkProperties();
2284
2285        PackageManagerService m = new PackageManagerService(context, installer,
2286                factoryTest, onlyCore);
2287        m.enableSystemUserPackages();
2288        ServiceManager.addService("package", m);
2289        return m;
2290    }
2291
2292    private void enableSystemUserPackages() {
2293        if (!UserManager.isSplitSystemUser()) {
2294            return;
2295        }
2296        // For system user, enable apps based on the following conditions:
2297        // - app is whitelisted or belong to one of these groups:
2298        //   -- system app which has no launcher icons
2299        //   -- system app which has INTERACT_ACROSS_USERS permission
2300        //   -- system IME app
2301        // - app is not in the blacklist
2302        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2303        Set<String> enableApps = new ArraySet<>();
2304        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2305                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2306                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2307        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2308        enableApps.addAll(wlApps);
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2310                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2311        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2312        enableApps.removeAll(blApps);
2313        Log.i(TAG, "Applications installed for system user: " + enableApps);
2314        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2315                UserHandle.SYSTEM);
2316        final int allAppsSize = allAps.size();
2317        synchronized (mPackages) {
2318            for (int i = 0; i < allAppsSize; i++) {
2319                String pName = allAps.get(i);
2320                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2321                // Should not happen, but we shouldn't be failing if it does
2322                if (pkgSetting == null) {
2323                    continue;
2324                }
2325                boolean install = enableApps.contains(pName);
2326                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2327                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2328                            + " for system user");
2329                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2330                }
2331            }
2332            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2333        }
2334    }
2335
2336    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2337        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2338                Context.DISPLAY_SERVICE);
2339        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2340    }
2341
2342    /**
2343     * Requests that files preopted on a secondary system partition be copied to the data partition
2344     * if possible.  Note that the actual copying of the files is accomplished by init for security
2345     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2346     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2347     */
2348    private static void requestCopyPreoptedFiles() {
2349        final int WAIT_TIME_MS = 100;
2350        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2351        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2352            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2353            // We will wait for up to 100 seconds.
2354            final long timeStart = SystemClock.uptimeMillis();
2355            final long timeEnd = timeStart + 100 * 1000;
2356            long timeNow = timeStart;
2357            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2358                try {
2359                    Thread.sleep(WAIT_TIME_MS);
2360                } catch (InterruptedException e) {
2361                    // Do nothing
2362                }
2363                timeNow = SystemClock.uptimeMillis();
2364                if (timeNow > timeEnd) {
2365                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2366                    Slog.wtf(TAG, "cppreopt did not finish!");
2367                    break;
2368                }
2369            }
2370
2371            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2372        }
2373    }
2374
2375    public PackageManagerService(Context context, Installer installer,
2376            boolean factoryTest, boolean onlyCore) {
2377        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2378        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2379        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2380                SystemClock.uptimeMillis());
2381
2382        if (mSdkVersion <= 0) {
2383            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2384        }
2385
2386        mContext = context;
2387
2388        mPermissionReviewRequired = context.getResources().getBoolean(
2389                R.bool.config_permissionReviewRequired);
2390
2391        mFactoryTest = factoryTest;
2392        mOnlyCore = onlyCore;
2393        mMetrics = new DisplayMetrics();
2394        mSettings = new Settings(mPackages);
2395        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407
2408        String separateProcesses = SystemProperties.get("debug.separate_processes");
2409        if (separateProcesses != null && separateProcesses.length() > 0) {
2410            if ("*".equals(separateProcesses)) {
2411                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2412                mSeparateProcesses = null;
2413                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2414            } else {
2415                mDefParseFlags = 0;
2416                mSeparateProcesses = separateProcesses.split(",");
2417                Slog.w(TAG, "Running with debug.separate_processes: "
2418                        + separateProcesses);
2419            }
2420        } else {
2421            mDefParseFlags = 0;
2422            mSeparateProcesses = null;
2423        }
2424
2425        mInstaller = installer;
2426        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2427                "*dexopt*");
2428        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2429        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2430
2431        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2432                FgThread.get().getLooper());
2433
2434        getDefaultDisplayMetrics(context, mMetrics);
2435
2436        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2437        SystemConfig systemConfig = SystemConfig.getInstance();
2438        mGlobalGids = systemConfig.getGlobalGids();
2439        mSystemPermissions = systemConfig.getSystemPermissions();
2440        mAvailableFeatures = systemConfig.getAvailableFeatures();
2441        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2442
2443        mProtectedPackages = new ProtectedPackages(mContext);
2444
2445        synchronized (mInstallLock) {
2446        // writer
2447        synchronized (mPackages) {
2448            mHandlerThread = new ServiceThread(TAG,
2449                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2450            mHandlerThread.start();
2451            mHandler = new PackageHandler(mHandlerThread.getLooper());
2452            mProcessLoggingHandler = new ProcessLoggingHandler();
2453            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2454
2455            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2456            mInstantAppRegistry = new InstantAppRegistry(this);
2457
2458            File dataDir = Environment.getDataDirectory();
2459            mAppInstallDir = new File(dataDir, "app");
2460            mAppLib32InstallDir = new File(dataDir, "app-lib");
2461            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2462            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2463            sUserManager = new UserManagerService(context, this,
2464                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2465
2466            // Propagate permission configuration in to package manager.
2467            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2468                    = systemConfig.getPermissions();
2469            for (int i=0; i<permConfig.size(); i++) {
2470                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2471                BasePermission bp = mSettings.mPermissions.get(perm.name);
2472                if (bp == null) {
2473                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2474                    mSettings.mPermissions.put(perm.name, bp);
2475                }
2476                if (perm.gids != null) {
2477                    bp.setGids(perm.gids, perm.perUser);
2478                }
2479            }
2480
2481            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2482            final int builtInLibCount = libConfig.size();
2483            for (int i = 0; i < builtInLibCount; i++) {
2484                String name = libConfig.keyAt(i);
2485                String path = libConfig.valueAt(i);
2486                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2487                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2488            }
2489
2490            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2491
2492            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2493            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2494            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2495
2496            // Clean up orphaned packages for which the code path doesn't exist
2497            // and they are an update to a system app - caused by bug/32321269
2498            final int packageSettingCount = mSettings.mPackages.size();
2499            for (int i = packageSettingCount - 1; i >= 0; i--) {
2500                PackageSetting ps = mSettings.mPackages.valueAt(i);
2501                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2502                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2503                    mSettings.mPackages.removeAt(i);
2504                    mSettings.enableSystemPackageLPw(ps.name);
2505                }
2506            }
2507
2508            if (mFirstBoot) {
2509                requestCopyPreoptedFiles();
2510            }
2511
2512            String customResolverActivity = Resources.getSystem().getString(
2513                    R.string.config_customResolverActivity);
2514            if (TextUtils.isEmpty(customResolverActivity)) {
2515                customResolverActivity = null;
2516            } else {
2517                mCustomResolverComponentName = ComponentName.unflattenFromString(
2518                        customResolverActivity);
2519            }
2520
2521            long startTime = SystemClock.uptimeMillis();
2522
2523            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2524                    startTime);
2525
2526            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2527            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2528
2529            if (bootClassPath == null) {
2530                Slog.w(TAG, "No BOOTCLASSPATH found!");
2531            }
2532
2533            if (systemServerClassPath == null) {
2534                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2535            }
2536
2537            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2538
2539            final VersionInfo ver = mSettings.getInternalVersion();
2540            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2541            if (mIsUpgrade) {
2542                logCriticalInfo(Log.INFO,
2543                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2544            }
2545
2546            // when upgrading from pre-M, promote system app permissions from install to runtime
2547            mPromoteSystemApps =
2548                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2549
2550            // When upgrading from pre-N, we need to handle package extraction like first boot,
2551            // as there is no profiling data available.
2552            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2553
2554            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2555
2556            // save off the names of pre-existing system packages prior to scanning; we don't
2557            // want to automatically grant runtime permissions for new system apps
2558            if (mPromoteSystemApps) {
2559                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2560                while (pkgSettingIter.hasNext()) {
2561                    PackageSetting ps = pkgSettingIter.next();
2562                    if (isSystemApp(ps)) {
2563                        mExistingSystemPackages.add(ps.name);
2564                    }
2565                }
2566            }
2567
2568            mCacheDir = preparePackageParserCache(mIsUpgrade);
2569
2570            // Set flag to monitor and not change apk file paths when
2571            // scanning install directories.
2572            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2573
2574            if (mIsUpgrade || mFirstBoot) {
2575                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2576            }
2577
2578            // Collect vendor overlay packages. (Do this before scanning any apps.)
2579            // For security and version matching reason, only consider
2580            // overlay packages if they reside in the right directory.
2581            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2582                    | PackageParser.PARSE_IS_SYSTEM
2583                    | PackageParser.PARSE_IS_SYSTEM_DIR
2584                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2585
2586            mParallelPackageParserCallback.findStaticOverlayPackages();
2587
2588            // Find base frameworks (resource packages without code).
2589            scanDirTracedLI(frameworkDir, mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR
2592                    | PackageParser.PARSE_IS_PRIVILEGED,
2593                    scanFlags | SCAN_NO_DEX, 0);
2594
2595            // Collected privileged system packages.
2596            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR
2600                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2601
2602            // Collect ordinary system packages.
2603            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604            scanDirTracedLI(systemAppDir, mDefParseFlags
2605                    | PackageParser.PARSE_IS_SYSTEM
2606                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2607
2608            // Collect all vendor packages.
2609            File vendorAppDir = new File("/vendor/app");
2610            try {
2611                vendorAppDir = vendorAppDir.getCanonicalFile();
2612            } catch (IOException e) {
2613                // failed to look up canonical path, continue with original one
2614            }
2615            scanDirTracedLI(vendorAppDir, mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2618
2619            // Collect all OEM packages.
2620            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2621            scanDirTracedLI(oemAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625            // Prune any system packages that no longer exist.
2626            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2627            if (!mOnlyCore) {
2628                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2629                while (psit.hasNext()) {
2630                    PackageSetting ps = psit.next();
2631
2632                    /*
2633                     * If this is not a system app, it can't be a
2634                     * disable system app.
2635                     */
2636                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2637                        continue;
2638                    }
2639
2640                    /*
2641                     * If the package is scanned, it's not erased.
2642                     */
2643                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2644                    if (scannedPkg != null) {
2645                        /*
2646                         * If the system app is both scanned and in the
2647                         * disabled packages list, then it must have been
2648                         * added via OTA. Remove it from the currently
2649                         * scanned package so the previously user-installed
2650                         * application can be scanned.
2651                         */
2652                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2653                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2654                                    + ps.name + "; removing system app.  Last known codePath="
2655                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2656                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2657                                    + scannedPkg.mVersionCode);
2658                            removePackageLI(scannedPkg, true);
2659                            mExpectingBetter.put(ps.name, ps.codePath);
2660                        }
2661
2662                        continue;
2663                    }
2664
2665                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2666                        psit.remove();
2667                        logCriticalInfo(Log.WARN, "System package " + ps.name
2668                                + " no longer exists; it's data will be wiped");
2669                        // Actual deletion of code and data will be handled by later
2670                        // reconciliation step
2671                    } else {
2672                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2673                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2674                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2675                        }
2676                    }
2677                }
2678            }
2679
2680            //look for any incomplete package installations
2681            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2682            for (int i = 0; i < deletePkgsList.size(); i++) {
2683                // Actual deletion of code and data will be handled by later
2684                // reconciliation step
2685                final String packageName = deletePkgsList.get(i).name;
2686                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2687                synchronized (mPackages) {
2688                    mSettings.removePackageLPw(packageName);
2689                }
2690            }
2691
2692            //delete tmp files
2693            deleteTempPackageFiles();
2694
2695            // Remove any shared userIDs that have no associated packages
2696            mSettings.pruneSharedUsersLPw();
2697
2698            if (!mOnlyCore) {
2699                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2700                        SystemClock.uptimeMillis());
2701                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2702
2703                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2704                        | PackageParser.PARSE_FORWARD_LOCK,
2705                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2706
2707                /**
2708                 * Remove disable package settings for any updated system
2709                 * apps that were removed via an OTA. If they're not a
2710                 * previously-updated app, remove them completely.
2711                 * Otherwise, just revoke their system-level permissions.
2712                 */
2713                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2714                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2715                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2716
2717                    String msg;
2718                    if (deletedPkg == null) {
2719                        msg = "Updated system package " + deletedAppName
2720                                + " no longer exists; it's data will be wiped";
2721                        // Actual deletion of code and data will be handled by later
2722                        // reconciliation step
2723                    } else {
2724                        msg = "Updated system app + " + deletedAppName
2725                                + " no longer present; removing system privileges for "
2726                                + deletedAppName;
2727
2728                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2729
2730                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2731                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2732                    }
2733                    logCriticalInfo(Log.WARN, msg);
2734                }
2735
2736                /**
2737                 * Make sure all system apps that we expected to appear on
2738                 * the userdata partition actually showed up. If they never
2739                 * appeared, crawl back and revive the system version.
2740                 */
2741                for (int i = 0; i < mExpectingBetter.size(); i++) {
2742                    final String packageName = mExpectingBetter.keyAt(i);
2743                    if (!mPackages.containsKey(packageName)) {
2744                        final File scanFile = mExpectingBetter.valueAt(i);
2745
2746                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2747                                + " but never showed up; reverting to system");
2748
2749                        int reparseFlags = mDefParseFlags;
2750                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2751                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2752                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2753                                    | PackageParser.PARSE_IS_PRIVILEGED;
2754                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2757                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2758                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2759                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2760                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                        } else {
2764                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2765                            continue;
2766                        }
2767
2768                        mSettings.enableSystemPackageLPw(packageName);
2769
2770                        try {
2771                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2772                        } catch (PackageManagerException e) {
2773                            Slog.e(TAG, "Failed to parse original system package: "
2774                                    + e.getMessage());
2775                        }
2776                    }
2777                }
2778            }
2779            mExpectingBetter.clear();
2780
2781            // Resolve the storage manager.
2782            mStorageManagerPackage = getStorageManagerPackageName();
2783
2784            // Resolve protected action filters. Only the setup wizard is allowed to
2785            // have a high priority filter for these actions.
2786            mSetupWizardPackage = getSetupWizardPackageName();
2787            if (mProtectedFilters.size() > 0) {
2788                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2789                    Slog.i(TAG, "No setup wizard;"
2790                        + " All protected intents capped to priority 0");
2791                }
2792                for (ActivityIntentInfo filter : mProtectedFilters) {
2793                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2794                        if (DEBUG_FILTERS) {
2795                            Slog.i(TAG, "Found setup wizard;"
2796                                + " allow priority " + filter.getPriority() + ";"
2797                                + " package: " + filter.activity.info.packageName
2798                                + " activity: " + filter.activity.className
2799                                + " priority: " + filter.getPriority());
2800                        }
2801                        // skip setup wizard; allow it to keep the high priority filter
2802                        continue;
2803                    }
2804                    if (DEBUG_FILTERS) {
2805                        Slog.i(TAG, "Protected action; cap priority to 0;"
2806                                + " package: " + filter.activity.info.packageName
2807                                + " activity: " + filter.activity.className
2808                                + " origPrio: " + filter.getPriority());
2809                    }
2810                    filter.setPriority(0);
2811                }
2812            }
2813            mDeferProtectedFilters = false;
2814            mProtectedFilters.clear();
2815
2816            // Now that we know all of the shared libraries, update all clients to have
2817            // the correct library paths.
2818            updateAllSharedLibrariesLPw(null);
2819
2820            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2821                // NOTE: We ignore potential failures here during a system scan (like
2822                // the rest of the commands above) because there's precious little we
2823                // can do about it. A settings error is reported, though.
2824                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2825            }
2826
2827            // Now that we know all the packages we are keeping,
2828            // read and update their last usage times.
2829            mPackageUsage.read(mPackages);
2830            mCompilerStats.read();
2831
2832            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2833                    SystemClock.uptimeMillis());
2834            Slog.i(TAG, "Time to scan packages: "
2835                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2836                    + " seconds");
2837
2838            // If the platform SDK has changed since the last time we booted,
2839            // we need to re-grant app permission to catch any new ones that
2840            // appear.  This is really a hack, and means that apps can in some
2841            // cases get permissions that the user didn't initially explicitly
2842            // allow...  it would be nice to have some better way to handle
2843            // this situation.
2844            int updateFlags = UPDATE_PERMISSIONS_ALL;
2845            if (ver.sdkVersion != mSdkVersion) {
2846                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2847                        + mSdkVersion + "; regranting permissions for internal storage");
2848                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2849            }
2850            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2851            ver.sdkVersion = mSdkVersion;
2852
2853            // If this is the first boot or an update from pre-M, and it is a normal
2854            // boot, then we need to initialize the default preferred apps across
2855            // all defined users.
2856            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2857                for (UserInfo user : sUserManager.getUsers(true)) {
2858                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2859                    applyFactoryDefaultBrowserLPw(user.id);
2860                    primeDomainVerificationsLPw(user.id);
2861                }
2862            }
2863
2864            // Prepare storage for system user really early during boot,
2865            // since core system apps like SettingsProvider and SystemUI
2866            // can't wait for user to start
2867            final int storageFlags;
2868            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2869                storageFlags = StorageManager.FLAG_STORAGE_DE;
2870            } else {
2871                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2872            }
2873            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2874                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2875                    true /* onlyCoreApps */);
2876            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2877                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2878                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2879                traceLog.traceBegin("AppDataFixup");
2880                try {
2881                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2882                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2883                } catch (InstallerException e) {
2884                    Slog.w(TAG, "Trouble fixing GIDs", e);
2885                }
2886                traceLog.traceEnd();
2887
2888                traceLog.traceBegin("AppDataPrepare");
2889                if (deferPackages == null || deferPackages.isEmpty()) {
2890                    return;
2891                }
2892                int count = 0;
2893                for (String pkgName : deferPackages) {
2894                    PackageParser.Package pkg = null;
2895                    synchronized (mPackages) {
2896                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2897                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2898                            pkg = ps.pkg;
2899                        }
2900                    }
2901                    if (pkg != null) {
2902                        synchronized (mInstallLock) {
2903                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2904                                    true /* maybeMigrateAppData */);
2905                        }
2906                        count++;
2907                    }
2908                }
2909                traceLog.traceEnd();
2910                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2911            }, "prepareAppData");
2912
2913            // If this is first boot after an OTA, and a normal boot, then
2914            // we need to clear code cache directories.
2915            // Note that we do *not* clear the application profiles. These remain valid
2916            // across OTAs and are used to drive profile verification (post OTA) and
2917            // profile compilation (without waiting to collect a fresh set of profiles).
2918            if (mIsUpgrade && !onlyCore) {
2919                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2920                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2921                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2922                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2923                        // No apps are running this early, so no need to freeze
2924                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2925                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2926                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2927                    }
2928                }
2929                ver.fingerprint = Build.FINGERPRINT;
2930            }
2931
2932            checkDefaultBrowser();
2933
2934            // clear only after permissions and other defaults have been updated
2935            mExistingSystemPackages.clear();
2936            mPromoteSystemApps = false;
2937
2938            // All the changes are done during package scanning.
2939            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2940
2941            // can downgrade to reader
2942            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2943            mSettings.writeLPr();
2944            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2946                    SystemClock.uptimeMillis());
2947
2948            if (!mOnlyCore) {
2949                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2950                mRequiredInstallerPackage = getRequiredInstallerLPr();
2951                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2952                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2953                if (mIntentFilterVerifierComponent != null) {
2954                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2955                            mIntentFilterVerifierComponent);
2956                } else {
2957                    mIntentFilterVerifier = null;
2958                }
2959                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2960                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2961                        SharedLibraryInfo.VERSION_UNDEFINED);
2962                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2963                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2964                        SharedLibraryInfo.VERSION_UNDEFINED);
2965            } else {
2966                mRequiredVerifierPackage = null;
2967                mRequiredInstallerPackage = null;
2968                mRequiredUninstallerPackage = null;
2969                mIntentFilterVerifierComponent = null;
2970                mIntentFilterVerifier = null;
2971                mServicesSystemSharedLibraryPackageName = null;
2972                mSharedSystemSharedLibraryPackageName = null;
2973            }
2974
2975            mInstallerService = new PackageInstallerService(context, this);
2976            final Pair<ComponentName, String> instantAppResolverComponent =
2977                    getInstantAppResolverLPr();
2978            if (instantAppResolverComponent != null) {
2979                if (DEBUG_EPHEMERAL) {
2980                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2981                }
2982                mInstantAppResolverConnection = new EphemeralResolverConnection(
2983                        mContext, instantAppResolverComponent.first,
2984                        instantAppResolverComponent.second);
2985                mInstantAppResolverSettingsComponent =
2986                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2987            } else {
2988                mInstantAppResolverConnection = null;
2989                mInstantAppResolverSettingsComponent = null;
2990            }
2991            updateInstantAppInstallerLocked(null);
2992
2993            // Read and update the usage of dex files.
2994            // Do this at the end of PM init so that all the packages have their
2995            // data directory reconciled.
2996            // At this point we know the code paths of the packages, so we can validate
2997            // the disk file and build the internal cache.
2998            // The usage file is expected to be small so loading and verifying it
2999            // should take a fairly small time compare to the other activities (e.g. package
3000            // scanning).
3001            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3002            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3003            for (int userId : currentUserIds) {
3004                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3005            }
3006            mDexManager.load(userPackages);
3007        } // synchronized (mPackages)
3008        } // synchronized (mInstallLock)
3009
3010        // Now after opening every single application zip, make sure they
3011        // are all flushed.  Not really needed, but keeps things nice and
3012        // tidy.
3013        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3014        Runtime.getRuntime().gc();
3015        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3016
3017        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3018        FallbackCategoryProvider.loadFallbacks();
3019        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3020
3021        // The initial scanning above does many calls into installd while
3022        // holding the mPackages lock, but we're mostly interested in yelling
3023        // once we have a booted system.
3024        mInstaller.setWarnIfHeld(mPackages);
3025
3026        // Expose private service for system components to use.
3027        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3028        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3029    }
3030
3031    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3032        // we're only interested in updating the installer appliction when 1) it's not
3033        // already set or 2) the modified package is the installer
3034        if (mInstantAppInstallerActivity != null
3035                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3036                        .equals(modifiedPackage)) {
3037            return;
3038        }
3039        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3040    }
3041
3042    private static File preparePackageParserCache(boolean isUpgrade) {
3043        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3044            return null;
3045        }
3046
3047        // Disable package parsing on eng builds to allow for faster incremental development.
3048        if ("eng".equals(Build.TYPE)) {
3049            return null;
3050        }
3051
3052        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3053            Slog.i(TAG, "Disabling package parser cache due to system property.");
3054            return null;
3055        }
3056
3057        // The base directory for the package parser cache lives under /data/system/.
3058        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3059                "package_cache");
3060        if (cacheBaseDir == null) {
3061            return null;
3062        }
3063
3064        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3065        // This also serves to "GC" unused entries when the package cache version changes (which
3066        // can only happen during upgrades).
3067        if (isUpgrade) {
3068            FileUtils.deleteContents(cacheBaseDir);
3069        }
3070
3071
3072        // Return the versioned package cache directory. This is something like
3073        // "/data/system/package_cache/1"
3074        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3075
3076        // The following is a workaround to aid development on non-numbered userdebug
3077        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3078        // the system partition is newer.
3079        //
3080        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3081        // that starts with "eng." to signify that this is an engineering build and not
3082        // destined for release.
3083        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3084            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3085
3086            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3087            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3088            // in general and should not be used for production changes. In this specific case,
3089            // we know that they will work.
3090            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3091            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3092                FileUtils.deleteContents(cacheBaseDir);
3093                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3094            }
3095        }
3096
3097        return cacheDir;
3098    }
3099
3100    @Override
3101    public boolean isFirstBoot() {
3102        // allow instant applications
3103        return mFirstBoot;
3104    }
3105
3106    @Override
3107    public boolean isOnlyCoreApps() {
3108        // allow instant applications
3109        return mOnlyCore;
3110    }
3111
3112    @Override
3113    public boolean isUpgrade() {
3114        // allow instant applications
3115        return mIsUpgrade;
3116    }
3117
3118    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3119        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3120
3121        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3122                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3123                UserHandle.USER_SYSTEM);
3124        if (matches.size() == 1) {
3125            return matches.get(0).getComponentInfo().packageName;
3126        } else if (matches.size() == 0) {
3127            Log.e(TAG, "There should probably be a verifier, but, none were found");
3128            return null;
3129        }
3130        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3131    }
3132
3133    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3134        synchronized (mPackages) {
3135            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3136            if (libraryEntry == null) {
3137                throw new IllegalStateException("Missing required shared library:" + name);
3138            }
3139            return libraryEntry.apk;
3140        }
3141    }
3142
3143    private @NonNull String getRequiredInstallerLPr() {
3144        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3145        intent.addCategory(Intent.CATEGORY_DEFAULT);
3146        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3147
3148        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3149                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3150                UserHandle.USER_SYSTEM);
3151        if (matches.size() == 1) {
3152            ResolveInfo resolveInfo = matches.get(0);
3153            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3154                throw new RuntimeException("The installer must be a privileged app");
3155            }
3156            return matches.get(0).getComponentInfo().packageName;
3157        } else {
3158            throw new RuntimeException("There must be exactly one installer; found " + matches);
3159        }
3160    }
3161
3162    private @NonNull String getRequiredUninstallerLPr() {
3163        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3164        intent.addCategory(Intent.CATEGORY_DEFAULT);
3165        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3166
3167        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3169                UserHandle.USER_SYSTEM);
3170        if (resolveInfo == null ||
3171                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3172            throw new RuntimeException("There must be exactly one uninstaller; found "
3173                    + resolveInfo);
3174        }
3175        return resolveInfo.getComponentInfo().packageName;
3176    }
3177
3178    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3179        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3180
3181        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3182                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3183                UserHandle.USER_SYSTEM);
3184        ResolveInfo best = null;
3185        final int N = matches.size();
3186        for (int i = 0; i < N; i++) {
3187            final ResolveInfo cur = matches.get(i);
3188            final String packageName = cur.getComponentInfo().packageName;
3189            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3190                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3191                continue;
3192            }
3193
3194            if (best == null || cur.priority > best.priority) {
3195                best = cur;
3196            }
3197        }
3198
3199        if (best != null) {
3200            return best.getComponentInfo().getComponentName();
3201        }
3202        Slog.w(TAG, "Intent filter verifier not found");
3203        return null;
3204    }
3205
3206    @Override
3207    public @Nullable ComponentName getInstantAppResolverComponent() {
3208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3209            return null;
3210        }
3211        synchronized (mPackages) {
3212            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3213            if (instantAppResolver == null) {
3214                return null;
3215            }
3216            return instantAppResolver.first;
3217        }
3218    }
3219
3220    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3221        final String[] packageArray =
3222                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3223        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3224            if (DEBUG_EPHEMERAL) {
3225                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3226            }
3227            return null;
3228        }
3229
3230        final int callingUid = Binder.getCallingUid();
3231        final int resolveFlags =
3232                MATCH_DIRECT_BOOT_AWARE
3233                | MATCH_DIRECT_BOOT_UNAWARE
3234                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3235        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3236        final Intent resolverIntent = new Intent(actionName);
3237        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3238                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3239        // temporarily look for the old action
3240        if (resolvers.size() == 0) {
3241            if (DEBUG_EPHEMERAL) {
3242                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3243            }
3244            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3245            resolverIntent.setAction(actionName);
3246            resolvers = queryIntentServicesInternal(resolverIntent, null,
3247                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3248        }
3249        final int N = resolvers.size();
3250        if (N == 0) {
3251            if (DEBUG_EPHEMERAL) {
3252                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3253            }
3254            return null;
3255        }
3256
3257        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3258        for (int i = 0; i < N; i++) {
3259            final ResolveInfo info = resolvers.get(i);
3260
3261            if (info.serviceInfo == null) {
3262                continue;
3263            }
3264
3265            final String packageName = info.serviceInfo.packageName;
3266            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3267                if (DEBUG_EPHEMERAL) {
3268                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3269                            + " pkg: " + packageName + ", info:" + info);
3270                }
3271                continue;
3272            }
3273
3274            if (DEBUG_EPHEMERAL) {
3275                Slog.v(TAG, "Ephemeral resolver found;"
3276                        + " pkg: " + packageName + ", info:" + info);
3277            }
3278            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3279        }
3280        if (DEBUG_EPHEMERAL) {
3281            Slog.v(TAG, "Ephemeral resolver NOT found");
3282        }
3283        return null;
3284    }
3285
3286    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3287        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3288        intent.addCategory(Intent.CATEGORY_DEFAULT);
3289        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3290
3291        final int resolveFlags =
3292                MATCH_DIRECT_BOOT_AWARE
3293                | MATCH_DIRECT_BOOT_UNAWARE
3294                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3295        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3296                resolveFlags, UserHandle.USER_SYSTEM);
3297        // temporarily look for the old action
3298        if (matches.isEmpty()) {
3299            if (DEBUG_EPHEMERAL) {
3300                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3301            }
3302            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3303            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3304                    resolveFlags, UserHandle.USER_SYSTEM);
3305        }
3306        Iterator<ResolveInfo> iter = matches.iterator();
3307        while (iter.hasNext()) {
3308            final ResolveInfo rInfo = iter.next();
3309            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3310            if (ps != null) {
3311                final PermissionsState permissionsState = ps.getPermissionsState();
3312                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3313                    continue;
3314                }
3315            }
3316            iter.remove();
3317        }
3318        if (matches.size() == 0) {
3319            return null;
3320        } else if (matches.size() == 1) {
3321            return (ActivityInfo) matches.get(0).getComponentInfo();
3322        } else {
3323            throw new RuntimeException(
3324                    "There must be at most one ephemeral installer; found " + matches);
3325        }
3326    }
3327
3328    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3329            @NonNull ComponentName resolver) {
3330        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3331                .addCategory(Intent.CATEGORY_DEFAULT)
3332                .setPackage(resolver.getPackageName());
3333        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3334        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3335                UserHandle.USER_SYSTEM);
3336        // temporarily look for the old action
3337        if (matches.isEmpty()) {
3338            if (DEBUG_EPHEMERAL) {
3339                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3340            }
3341            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3342            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3343                    UserHandle.USER_SYSTEM);
3344        }
3345        if (matches.isEmpty()) {
3346            return null;
3347        }
3348        return matches.get(0).getComponentInfo().getComponentName();
3349    }
3350
3351    private void primeDomainVerificationsLPw(int userId) {
3352        if (DEBUG_DOMAIN_VERIFICATION) {
3353            Slog.d(TAG, "Priming domain verifications in user " + userId);
3354        }
3355
3356        SystemConfig systemConfig = SystemConfig.getInstance();
3357        ArraySet<String> packages = systemConfig.getLinkedApps();
3358
3359        for (String packageName : packages) {
3360            PackageParser.Package pkg = mPackages.get(packageName);
3361            if (pkg != null) {
3362                if (!pkg.isSystemApp()) {
3363                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3364                    continue;
3365                }
3366
3367                ArraySet<String> domains = null;
3368                for (PackageParser.Activity a : pkg.activities) {
3369                    for (ActivityIntentInfo filter : a.intents) {
3370                        if (hasValidDomains(filter)) {
3371                            if (domains == null) {
3372                                domains = new ArraySet<String>();
3373                            }
3374                            domains.addAll(filter.getHostsList());
3375                        }
3376                    }
3377                }
3378
3379                if (domains != null && domains.size() > 0) {
3380                    if (DEBUG_DOMAIN_VERIFICATION) {
3381                        Slog.v(TAG, "      + " + packageName);
3382                    }
3383                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3384                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3385                    // and then 'always' in the per-user state actually used for intent resolution.
3386                    final IntentFilterVerificationInfo ivi;
3387                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3388                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3389                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3390                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3391                } else {
3392                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3393                            + "' does not handle web links");
3394                }
3395            } else {
3396                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3397            }
3398        }
3399
3400        scheduleWritePackageRestrictionsLocked(userId);
3401        scheduleWriteSettingsLocked();
3402    }
3403
3404    private void applyFactoryDefaultBrowserLPw(int userId) {
3405        // The default browser app's package name is stored in a string resource,
3406        // with a product-specific overlay used for vendor customization.
3407        String browserPkg = mContext.getResources().getString(
3408                com.android.internal.R.string.default_browser);
3409        if (!TextUtils.isEmpty(browserPkg)) {
3410            // non-empty string => required to be a known package
3411            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3412            if (ps == null) {
3413                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3414                browserPkg = null;
3415            } else {
3416                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3417            }
3418        }
3419
3420        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3421        // default.  If there's more than one, just leave everything alone.
3422        if (browserPkg == null) {
3423            calculateDefaultBrowserLPw(userId);
3424        }
3425    }
3426
3427    private void calculateDefaultBrowserLPw(int userId) {
3428        List<String> allBrowsers = resolveAllBrowserApps(userId);
3429        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3430        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3431    }
3432
3433    private List<String> resolveAllBrowserApps(int userId) {
3434        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3435        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3436                PackageManager.MATCH_ALL, userId);
3437
3438        final int count = list.size();
3439        List<String> result = new ArrayList<String>(count);
3440        for (int i=0; i<count; i++) {
3441            ResolveInfo info = list.get(i);
3442            if (info.activityInfo == null
3443                    || !info.handleAllWebDataURI
3444                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3445                    || result.contains(info.activityInfo.packageName)) {
3446                continue;
3447            }
3448            result.add(info.activityInfo.packageName);
3449        }
3450
3451        return result;
3452    }
3453
3454    private boolean packageIsBrowser(String packageName, int userId) {
3455        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3456                PackageManager.MATCH_ALL, userId);
3457        final int N = list.size();
3458        for (int i = 0; i < N; i++) {
3459            ResolveInfo info = list.get(i);
3460            if (packageName.equals(info.activityInfo.packageName)) {
3461                return true;
3462            }
3463        }
3464        return false;
3465    }
3466
3467    private void checkDefaultBrowser() {
3468        final int myUserId = UserHandle.myUserId();
3469        final String packageName = getDefaultBrowserPackageName(myUserId);
3470        if (packageName != null) {
3471            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3472            if (info == null) {
3473                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3474                synchronized (mPackages) {
3475                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3476                }
3477            }
3478        }
3479    }
3480
3481    @Override
3482    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3483            throws RemoteException {
3484        try {
3485            return super.onTransact(code, data, reply, flags);
3486        } catch (RuntimeException e) {
3487            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3488                Slog.wtf(TAG, "Package Manager Crash", e);
3489            }
3490            throw e;
3491        }
3492    }
3493
3494    static int[] appendInts(int[] cur, int[] add) {
3495        if (add == null) return cur;
3496        if (cur == null) return add;
3497        final int N = add.length;
3498        for (int i=0; i<N; i++) {
3499            cur = appendInt(cur, add[i]);
3500        }
3501        return cur;
3502    }
3503
3504    /**
3505     * Returns whether or not a full application can see an instant application.
3506     * <p>
3507     * Currently, there are three cases in which this can occur:
3508     * <ol>
3509     * <li>The calling application is a "special" process. The special
3510     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3511     *     and {@code 0}</li>
3512     * <li>The calling application has the permission
3513     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3514     * <li>The calling application is the default launcher on the
3515     *     system partition.</li>
3516     * </ol>
3517     */
3518    private boolean canViewInstantApps(int callingUid, int userId) {
3519        if (callingUid == Process.SYSTEM_UID
3520                || callingUid == Process.SHELL_UID
3521                || callingUid == Process.ROOT_UID) {
3522            return true;
3523        }
3524        if (mContext.checkCallingOrSelfPermission(
3525                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3526            return true;
3527        }
3528        if (mContext.checkCallingOrSelfPermission(
3529                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3530            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3531            if (homeComponent != null
3532                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3533                return true;
3534            }
3535        }
3536        return false;
3537    }
3538
3539    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3540        if (!sUserManager.exists(userId)) return null;
3541        if (ps == null) {
3542            return null;
3543        }
3544        PackageParser.Package p = ps.pkg;
3545        if (p == null) {
3546            return null;
3547        }
3548        final int callingUid = Binder.getCallingUid();
3549        // Filter out ephemeral app metadata:
3550        //   * The system/shell/root can see metadata for any app
3551        //   * An installed app can see metadata for 1) other installed apps
3552        //     and 2) ephemeral apps that have explicitly interacted with it
3553        //   * Ephemeral apps can only see their own data and exposed installed apps
3554        //   * Holding a signature permission allows seeing instant apps
3555        if (filterAppAccessLPr(ps, callingUid, userId)) {
3556            return null;
3557        }
3558
3559        final PermissionsState permissionsState = ps.getPermissionsState();
3560
3561        // Compute GIDs only if requested
3562        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3563                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3564        // Compute granted permissions only if package has requested permissions
3565        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3566                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3567        final PackageUserState state = ps.readUserState(userId);
3568
3569        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3570                && ps.isSystem()) {
3571            flags |= MATCH_ANY_USER;
3572        }
3573
3574        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3575                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3576
3577        if (packageInfo == null) {
3578            return null;
3579        }
3580
3581        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3582                resolveExternalPackageNameLPr(p);
3583
3584        return packageInfo;
3585    }
3586
3587    @Override
3588    public void checkPackageStartable(String packageName, int userId) {
3589        final int callingUid = Binder.getCallingUid();
3590        if (getInstantAppPackageName(callingUid) != null) {
3591            throw new SecurityException("Instant applications don't have access to this method");
3592        }
3593        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3594        synchronized (mPackages) {
3595            final PackageSetting ps = mSettings.mPackages.get(packageName);
3596            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3597                throw new SecurityException("Package " + packageName + " was not found!");
3598            }
3599
3600            if (!ps.getInstalled(userId)) {
3601                throw new SecurityException(
3602                        "Package " + packageName + " was not installed for user " + userId + "!");
3603            }
3604
3605            if (mSafeMode && !ps.isSystem()) {
3606                throw new SecurityException("Package " + packageName + " not a system app!");
3607            }
3608
3609            if (mFrozenPackages.contains(packageName)) {
3610                throw new SecurityException("Package " + packageName + " is currently frozen!");
3611            }
3612
3613            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3614                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3615                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3616            }
3617        }
3618    }
3619
3620    @Override
3621    public boolean isPackageAvailable(String packageName, int userId) {
3622        if (!sUserManager.exists(userId)) return false;
3623        final int callingUid = Binder.getCallingUid();
3624        enforceCrossUserPermission(callingUid, userId,
3625                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3626        synchronized (mPackages) {
3627            PackageParser.Package p = mPackages.get(packageName);
3628            if (p != null) {
3629                final PackageSetting ps = (PackageSetting) p.mExtras;
3630                if (filterAppAccessLPr(ps, callingUid, userId)) {
3631                    return false;
3632                }
3633                if (ps != null) {
3634                    final PackageUserState state = ps.readUserState(userId);
3635                    if (state != null) {
3636                        return PackageParser.isAvailable(state);
3637                    }
3638                }
3639            }
3640        }
3641        return false;
3642    }
3643
3644    @Override
3645    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3646        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3647                flags, Binder.getCallingUid(), userId);
3648    }
3649
3650    @Override
3651    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3652            int flags, int userId) {
3653        return getPackageInfoInternal(versionedPackage.getPackageName(),
3654                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3655    }
3656
3657    /**
3658     * Important: The provided filterCallingUid is used exclusively to filter out packages
3659     * that can be seen based on user state. It's typically the original caller uid prior
3660     * to clearing. Because it can only be provided by trusted code, it's value can be
3661     * trusted and will be used as-is; unlike userId which will be validated by this method.
3662     */
3663    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3664            int flags, int filterCallingUid, int userId) {
3665        if (!sUserManager.exists(userId)) return null;
3666        flags = updateFlagsForPackage(flags, userId, packageName);
3667        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3668                false /* requireFullPermission */, false /* checkShell */, "get package info");
3669
3670        // reader
3671        synchronized (mPackages) {
3672            // Normalize package name to handle renamed packages and static libs
3673            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3674
3675            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3676            if (matchFactoryOnly) {
3677                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3678                if (ps != null) {
3679                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3680                        return null;
3681                    }
3682                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3683                        return null;
3684                    }
3685                    return generatePackageInfo(ps, flags, userId);
3686                }
3687            }
3688
3689            PackageParser.Package p = mPackages.get(packageName);
3690            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3691                return null;
3692            }
3693            if (DEBUG_PACKAGE_INFO)
3694                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3695            if (p != null) {
3696                final PackageSetting ps = (PackageSetting) p.mExtras;
3697                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3698                    return null;
3699                }
3700                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3701                    return null;
3702                }
3703                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3704            }
3705            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3706                final PackageSetting ps = mSettings.mPackages.get(packageName);
3707                if (ps == null) return null;
3708                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3709                    return null;
3710                }
3711                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3712                    return null;
3713                }
3714                return generatePackageInfo(ps, flags, userId);
3715            }
3716        }
3717        return null;
3718    }
3719
3720    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3721        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3722            return true;
3723        }
3724        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3725            return true;
3726        }
3727        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3728            return true;
3729        }
3730        return false;
3731    }
3732
3733    private boolean isComponentVisibleToInstantApp(
3734            @Nullable ComponentName component, @ComponentType int type) {
3735        if (type == TYPE_ACTIVITY) {
3736            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3737            return activity != null
3738                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3739                    : false;
3740        } else if (type == TYPE_RECEIVER) {
3741            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3742            return activity != null
3743                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3744                    : false;
3745        } else if (type == TYPE_SERVICE) {
3746            final PackageParser.Service service = mServices.mServices.get(component);
3747            return service != null
3748                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_PROVIDER) {
3751            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3752            return provider != null
3753                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_UNKNOWN) {
3756            return isComponentVisibleToInstantApp(component);
3757        }
3758        return false;
3759    }
3760
3761    /**
3762     * Returns whether or not access to the application should be filtered.
3763     * <p>
3764     * Access may be limited based upon whether the calling or target applications
3765     * are instant applications.
3766     *
3767     * @see #canAccessInstantApps(int)
3768     */
3769    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3770            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3771        // if we're in an isolated process, get the real calling UID
3772        if (Process.isIsolated(callingUid)) {
3773            callingUid = mIsolatedOwners.get(callingUid);
3774        }
3775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3776        final boolean callerIsInstantApp = instantAppPkgName != null;
3777        if (ps == null) {
3778            if (callerIsInstantApp) {
3779                // pretend the application exists, but, needs to be filtered
3780                return true;
3781            }
3782            return false;
3783        }
3784        // if the target and caller are the same application, don't filter
3785        if (isCallerSameApp(ps.name, callingUid)) {
3786            return false;
3787        }
3788        if (callerIsInstantApp) {
3789            // request for a specific component; if it hasn't been explicitly exposed, filter
3790            if (component != null) {
3791                return !isComponentVisibleToInstantApp(component, componentType);
3792            }
3793            // request for application; if no components have been explicitly exposed, filter
3794            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3795        }
3796        if (ps.getInstantApp(userId)) {
3797            // caller can see all components of all instant applications, don't filter
3798            if (canViewInstantApps(callingUid, userId)) {
3799                return false;
3800            }
3801            // request for a specific instant application component, filter
3802            if (component != null) {
3803                return true;
3804            }
3805            // request for an instant application; if the caller hasn't been granted access, filter
3806            return !mInstantAppRegistry.isInstantAccessGranted(
3807                    userId, UserHandle.getAppId(callingUid), ps.appId);
3808        }
3809        return false;
3810    }
3811
3812    /**
3813     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3814     */
3815    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3816        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3817    }
3818
3819    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3820            int flags) {
3821        // Callers can access only the libs they depend on, otherwise they need to explicitly
3822        // ask for the shared libraries given the caller is allowed to access all static libs.
3823        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3824            // System/shell/root get to see all static libs
3825            final int appId = UserHandle.getAppId(uid);
3826            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3827                    || appId == Process.ROOT_UID) {
3828                return false;
3829            }
3830        }
3831
3832        // No package means no static lib as it is always on internal storage
3833        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3834            return false;
3835        }
3836
3837        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3838                ps.pkg.staticSharedLibVersion);
3839        if (libEntry == null) {
3840            return false;
3841        }
3842
3843        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3844        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3845        if (uidPackageNames == null) {
3846            return true;
3847        }
3848
3849        for (String uidPackageName : uidPackageNames) {
3850            if (ps.name.equals(uidPackageName)) {
3851                return false;
3852            }
3853            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3854            if (uidPs != null) {
3855                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3856                        libEntry.info.getName());
3857                if (index < 0) {
3858                    continue;
3859                }
3860                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3861                    return false;
3862                }
3863            }
3864        }
3865        return true;
3866    }
3867
3868    @Override
3869    public String[] currentToCanonicalPackageNames(String[] names) {
3870        final int callingUid = Binder.getCallingUid();
3871        if (getInstantAppPackageName(callingUid) != null) {
3872            return names;
3873        }
3874        final String[] out = new String[names.length];
3875        // reader
3876        synchronized (mPackages) {
3877            final int callingUserId = UserHandle.getUserId(callingUid);
3878            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3879            for (int i=names.length-1; i>=0; i--) {
3880                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3881                boolean translateName = false;
3882                if (ps != null && ps.realName != null) {
3883                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3884                    translateName = !targetIsInstantApp
3885                            || canViewInstantApps
3886                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3887                                    UserHandle.getAppId(callingUid), ps.appId);
3888                }
3889                out[i] = translateName ? ps.realName : names[i];
3890            }
3891        }
3892        return out;
3893    }
3894
3895    @Override
3896    public String[] canonicalToCurrentPackageNames(String[] names) {
3897        final int callingUid = Binder.getCallingUid();
3898        if (getInstantAppPackageName(callingUid) != null) {
3899            return names;
3900        }
3901        final String[] out = new String[names.length];
3902        // reader
3903        synchronized (mPackages) {
3904            final int callingUserId = UserHandle.getUserId(callingUid);
3905            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3906            for (int i=names.length-1; i>=0; i--) {
3907                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3908                boolean translateName = false;
3909                if (cur != null) {
3910                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3911                    final boolean targetIsInstantApp =
3912                            ps != null && ps.getInstantApp(callingUserId);
3913                    translateName = !targetIsInstantApp
3914                            || canViewInstantApps
3915                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3916                                    UserHandle.getAppId(callingUid), ps.appId);
3917                }
3918                out[i] = translateName ? cur : names[i];
3919            }
3920        }
3921        return out;
3922    }
3923
3924    @Override
3925    public int getPackageUid(String packageName, int flags, int userId) {
3926        if (!sUserManager.exists(userId)) return -1;
3927        final int callingUid = Binder.getCallingUid();
3928        flags = updateFlagsForPackage(flags, userId, packageName);
3929        enforceCrossUserPermission(callingUid, userId,
3930                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final PackageParser.Package p = mPackages.get(packageName);
3935            if (p != null && p.isMatch(flags)) {
3936                PackageSetting ps = (PackageSetting) p.mExtras;
3937                if (filterAppAccessLPr(ps, callingUid, userId)) {
3938                    return -1;
3939                }
3940                return UserHandle.getUid(userId, p.applicationInfo.uid);
3941            }
3942            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3943                final PackageSetting ps = mSettings.mPackages.get(packageName);
3944                if (ps != null && ps.isMatch(flags)
3945                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return UserHandle.getUid(userId, ps.appId);
3947                }
3948            }
3949        }
3950
3951        return -1;
3952    }
3953
3954    @Override
3955    public int[] getPackageGids(String packageName, int flags, int userId) {
3956        if (!sUserManager.exists(userId)) return null;
3957        final int callingUid = Binder.getCallingUid();
3958        flags = updateFlagsForPackage(flags, userId, packageName);
3959        enforceCrossUserPermission(callingUid, userId,
3960                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3961
3962        // reader
3963        synchronized (mPackages) {
3964            final PackageParser.Package p = mPackages.get(packageName);
3965            if (p != null && p.isMatch(flags)) {
3966                PackageSetting ps = (PackageSetting) p.mExtras;
3967                if (filterAppAccessLPr(ps, callingUid, userId)) {
3968                    return null;
3969                }
3970                // TODO: Shouldn't this be checking for package installed state for userId and
3971                // return null?
3972                return ps.getPermissionsState().computeGids(userId);
3973            }
3974            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3975                final PackageSetting ps = mSettings.mPackages.get(packageName);
3976                if (ps != null && ps.isMatch(flags)
3977                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3978                    return ps.getPermissionsState().computeGids(userId);
3979                }
3980            }
3981        }
3982
3983        return null;
3984    }
3985
3986    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3987        if (bp.perm != null) {
3988            return PackageParser.generatePermissionInfo(bp.perm, flags);
3989        }
3990        PermissionInfo pi = new PermissionInfo();
3991        pi.name = bp.name;
3992        pi.packageName = bp.sourcePackage;
3993        pi.nonLocalizedLabel = bp.name;
3994        pi.protectionLevel = bp.protectionLevel;
3995        return pi;
3996    }
3997
3998    @Override
3999    public PermissionInfo getPermissionInfo(String name, int flags) {
4000        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4001            return null;
4002        }
4003        // reader
4004        synchronized (mPackages) {
4005            final BasePermission p = mSettings.mPermissions.get(name);
4006            if (p != null) {
4007                return generatePermissionInfo(p, flags);
4008            }
4009            return null;
4010        }
4011    }
4012
4013    @Override
4014    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4015            int flags) {
4016        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4017            return null;
4018        }
4019        // reader
4020        synchronized (mPackages) {
4021            if (group != null && !mPermissionGroups.containsKey(group)) {
4022                // This is thrown as NameNotFoundException
4023                return null;
4024            }
4025
4026            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4027            for (BasePermission p : mSettings.mPermissions.values()) {
4028                if (group == null) {
4029                    if (p.perm == null || p.perm.info.group == null) {
4030                        out.add(generatePermissionInfo(p, flags));
4031                    }
4032                } else {
4033                    if (p.perm != null && group.equals(p.perm.info.group)) {
4034                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4035                    }
4036                }
4037            }
4038            return new ParceledListSlice<>(out);
4039        }
4040    }
4041
4042    @Override
4043    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4044        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4045            return null;
4046        }
4047        // reader
4048        synchronized (mPackages) {
4049            return PackageParser.generatePermissionGroupInfo(
4050                    mPermissionGroups.get(name), flags);
4051        }
4052    }
4053
4054    @Override
4055    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4056        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4057            return ParceledListSlice.emptyList();
4058        }
4059        // reader
4060        synchronized (mPackages) {
4061            final int N = mPermissionGroups.size();
4062            ArrayList<PermissionGroupInfo> out
4063                    = new ArrayList<PermissionGroupInfo>(N);
4064            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4065                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4066            }
4067            return new ParceledListSlice<>(out);
4068        }
4069    }
4070
4071    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4072            int filterCallingUid, int userId) {
4073        if (!sUserManager.exists(userId)) return null;
4074        PackageSetting ps = mSettings.mPackages.get(packageName);
4075        if (ps != null) {
4076            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4077                return null;
4078            }
4079            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4080                return null;
4081            }
4082            if (ps.pkg == null) {
4083                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4084                if (pInfo != null) {
4085                    return pInfo.applicationInfo;
4086                }
4087                return null;
4088            }
4089            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4090                    ps.readUserState(userId), userId);
4091            if (ai != null) {
4092                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4093            }
4094            return ai;
4095        }
4096        return null;
4097    }
4098
4099    @Override
4100    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4101        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4102    }
4103
4104    /**
4105     * Important: The provided filterCallingUid is used exclusively to filter out applications
4106     * that can be seen based on user state. It's typically the original caller uid prior
4107     * to clearing. Because it can only be provided by trusted code, it's value can be
4108     * trusted and will be used as-is; unlike userId which will be validated by this method.
4109     */
4110    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4111            int filterCallingUid, int userId) {
4112        if (!sUserManager.exists(userId)) return null;
4113        flags = updateFlagsForApplication(flags, userId, packageName);
4114        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4115                false /* requireFullPermission */, false /* checkShell */, "get application info");
4116
4117        // writer
4118        synchronized (mPackages) {
4119            // Normalize package name to handle renamed packages and static libs
4120            packageName = resolveInternalPackageNameLPr(packageName,
4121                    PackageManager.VERSION_CODE_HIGHEST);
4122
4123            PackageParser.Package p = mPackages.get(packageName);
4124            if (DEBUG_PACKAGE_INFO) Log.v(
4125                    TAG, "getApplicationInfo " + packageName
4126                    + ": " + p);
4127            if (p != null) {
4128                PackageSetting ps = mSettings.mPackages.get(packageName);
4129                if (ps == null) return null;
4130                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                    return null;
4132                }
4133                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                    return null;
4135                }
4136                // Note: isEnabledLP() does not apply here - always return info
4137                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4138                        p, flags, ps.readUserState(userId), userId);
4139                if (ai != null) {
4140                    ai.packageName = resolveExternalPackageNameLPr(p);
4141                }
4142                return ai;
4143            }
4144            if ("android".equals(packageName)||"system".equals(packageName)) {
4145                return mAndroidApplication;
4146            }
4147            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4148                // Already generates the external package name
4149                return generateApplicationInfoFromSettingsLPw(packageName,
4150                        flags, filterCallingUid, userId);
4151            }
4152        }
4153        return null;
4154    }
4155
4156    private String normalizePackageNameLPr(String packageName) {
4157        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4158        return normalizedPackageName != null ? normalizedPackageName : packageName;
4159    }
4160
4161    @Override
4162    public void deletePreloadsFileCache() {
4163        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4164            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4165        }
4166        File dir = Environment.getDataPreloadsFileCacheDirectory();
4167        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4168        FileUtils.deleteContents(dir);
4169    }
4170
4171    @Override
4172    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4173            final int storageFlags, final IPackageDataObserver observer) {
4174        mContext.enforceCallingOrSelfPermission(
4175                android.Manifest.permission.CLEAR_APP_CACHE, null);
4176        mHandler.post(() -> {
4177            boolean success = false;
4178            try {
4179                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4180                success = true;
4181            } catch (IOException e) {
4182                Slog.w(TAG, e);
4183            }
4184            if (observer != null) {
4185                try {
4186                    observer.onRemoveCompleted(null, success);
4187                } catch (RemoteException e) {
4188                    Slog.w(TAG, e);
4189                }
4190            }
4191        });
4192    }
4193
4194    @Override
4195    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4196            final int storageFlags, final IntentSender pi) {
4197        mContext.enforceCallingOrSelfPermission(
4198                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4199        mHandler.post(() -> {
4200            boolean success = false;
4201            try {
4202                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4203                success = true;
4204            } catch (IOException e) {
4205                Slog.w(TAG, e);
4206            }
4207            if (pi != null) {
4208                try {
4209                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4210                } catch (SendIntentException e) {
4211                    Slog.w(TAG, e);
4212                }
4213            }
4214        });
4215    }
4216
4217    /**
4218     * Blocking call to clear various types of cached data across the system
4219     * until the requested bytes are available.
4220     */
4221    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4222        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4223        final File file = storage.findPathForUuid(volumeUuid);
4224        if (file.getUsableSpace() >= bytes) return;
4225
4226        if (ENABLE_FREE_CACHE_V2) {
4227            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4228                    volumeUuid);
4229            final boolean aggressive = (storageFlags
4230                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4231            final boolean defyReserved = (storageFlags
4232                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4233            final long reservedBytes = (aggressive || defyReserved) ? 0
4234                    : storage.getStorageCacheBytes(file);
4235
4236            // 1. Pre-flight to determine if we have any chance to succeed
4237            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4238            if (internalVolume && (aggressive || SystemProperties
4239                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4240                deletePreloadsFileCache();
4241                if (file.getUsableSpace() >= bytes) return;
4242            }
4243
4244            // 3. Consider parsed APK data (aggressive only)
4245            if (internalVolume && aggressive) {
4246                FileUtils.deleteContents(mCacheDir);
4247                if (file.getUsableSpace() >= bytes) return;
4248            }
4249
4250            // 4. Consider cached app data (above quotas)
4251            try {
4252                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4253                        Installer.FLAG_FREE_CACHE_V2);
4254            } catch (InstallerException ignored) {
4255            }
4256            if (file.getUsableSpace() >= bytes) return;
4257
4258            // 5. Consider shared libraries with refcount=0 and age>min cache period
4259            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4260                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4261                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4262                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4263                return;
4264            }
4265
4266            // 6. Consider dexopt output (aggressive only)
4267            // TODO: Implement
4268
4269            // 7. Consider installed instant apps unused longer than min cache period
4270            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4271                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4272                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4273                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4274                return;
4275            }
4276
4277            // 8. Consider cached app data (below quotas)
4278            try {
4279                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4280                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4281            } catch (InstallerException ignored) {
4282            }
4283            if (file.getUsableSpace() >= bytes) return;
4284
4285            // 9. Consider DropBox entries
4286            // TODO: Implement
4287
4288            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4289            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4290                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4291                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4292                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4293                return;
4294            }
4295        } else {
4296            try {
4297                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4298            } catch (InstallerException ignored) {
4299            }
4300            if (file.getUsableSpace() >= bytes) return;
4301        }
4302
4303        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4304    }
4305
4306    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4307            throws IOException {
4308        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4309        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4310
4311        List<VersionedPackage> packagesToDelete = null;
4312        final long now = System.currentTimeMillis();
4313
4314        synchronized (mPackages) {
4315            final int[] allUsers = sUserManager.getUserIds();
4316            final int libCount = mSharedLibraries.size();
4317            for (int i = 0; i < libCount; i++) {
4318                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4319                if (versionedLib == null) {
4320                    continue;
4321                }
4322                final int versionCount = versionedLib.size();
4323                for (int j = 0; j < versionCount; j++) {
4324                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4325                    // Skip packages that are not static shared libs.
4326                    if (!libInfo.isStatic()) {
4327                        break;
4328                    }
4329                    // Important: We skip static shared libs used for some user since
4330                    // in such a case we need to keep the APK on the device. The check for
4331                    // a lib being used for any user is performed by the uninstall call.
4332                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4333                    // Resolve the package name - we use synthetic package names internally
4334                    final String internalPackageName = resolveInternalPackageNameLPr(
4335                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4336                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4337                    // Skip unused static shared libs cached less than the min period
4338                    // to prevent pruning a lib needed by a subsequently installed package.
4339                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4340                        continue;
4341                    }
4342                    if (packagesToDelete == null) {
4343                        packagesToDelete = new ArrayList<>();
4344                    }
4345                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4346                            declaringPackage.getVersionCode()));
4347                }
4348            }
4349        }
4350
4351        if (packagesToDelete != null) {
4352            final int packageCount = packagesToDelete.size();
4353            for (int i = 0; i < packageCount; i++) {
4354                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4355                // Delete the package synchronously (will fail of the lib used for any user).
4356                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4357                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4358                                == PackageManager.DELETE_SUCCEEDED) {
4359                    if (volume.getUsableSpace() >= neededSpace) {
4360                        return true;
4361                    }
4362                }
4363            }
4364        }
4365
4366        return false;
4367    }
4368
4369    /**
4370     * Update given flags based on encryption status of current user.
4371     */
4372    private int updateFlags(int flags, int userId) {
4373        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4374                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4375            // Caller expressed an explicit opinion about what encryption
4376            // aware/unaware components they want to see, so fall through and
4377            // give them what they want
4378        } else {
4379            // Caller expressed no opinion, so match based on user state
4380            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4381                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4382            } else {
4383                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4384            }
4385        }
4386        return flags;
4387    }
4388
4389    private UserManagerInternal getUserManagerInternal() {
4390        if (mUserManagerInternal == null) {
4391            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4392        }
4393        return mUserManagerInternal;
4394    }
4395
4396    private DeviceIdleController.LocalService getDeviceIdleController() {
4397        if (mDeviceIdleController == null) {
4398            mDeviceIdleController =
4399                    LocalServices.getService(DeviceIdleController.LocalService.class);
4400        }
4401        return mDeviceIdleController;
4402    }
4403
4404    /**
4405     * Update given flags when being used to request {@link PackageInfo}.
4406     */
4407    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4408        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4409        boolean triaged = true;
4410        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4411                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4412            // Caller is asking for component details, so they'd better be
4413            // asking for specific encryption matching behavior, or be triaged
4414            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4415                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4416                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4417                triaged = false;
4418            }
4419        }
4420        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4421                | PackageManager.MATCH_SYSTEM_ONLY
4422                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4423            triaged = false;
4424        }
4425        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4426            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4427                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4428                    + Debug.getCallers(5));
4429        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4430                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4431            // If the caller wants all packages and has a restricted profile associated with it,
4432            // then match all users. This is to make sure that launchers that need to access work
4433            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4434            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4435            flags |= PackageManager.MATCH_ANY_USER;
4436        }
4437        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4438            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4439                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4440        }
4441        return updateFlags(flags, userId);
4442    }
4443
4444    /**
4445     * Update given flags when being used to request {@link ApplicationInfo}.
4446     */
4447    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4448        return updateFlagsForPackage(flags, userId, cookie);
4449    }
4450
4451    /**
4452     * Update given flags when being used to request {@link ComponentInfo}.
4453     */
4454    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4455        if (cookie instanceof Intent) {
4456            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4457                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4458            }
4459        }
4460
4461        boolean triaged = true;
4462        // Caller is asking for component details, so they'd better be
4463        // asking for specific encryption matching behavior, or be triaged
4464        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4467            triaged = false;
4468        }
4469        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4470            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4471                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4472        }
4473
4474        return updateFlags(flags, userId);
4475    }
4476
4477    /**
4478     * Update given intent when being used to request {@link ResolveInfo}.
4479     */
4480    private Intent updateIntentForResolve(Intent intent) {
4481        if (intent.getSelector() != null) {
4482            intent = intent.getSelector();
4483        }
4484        if (DEBUG_PREFERRED) {
4485            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4486        }
4487        return intent;
4488    }
4489
4490    /**
4491     * Update given flags when being used to request {@link ResolveInfo}.
4492     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4493     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4494     * flag set. However, this flag is only honoured in three circumstances:
4495     * <ul>
4496     * <li>when called from a system process</li>
4497     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4498     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4499     * action and a {@code android.intent.category.BROWSABLE} category</li>
4500     * </ul>
4501     */
4502    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4503        return updateFlagsForResolve(flags, userId, intent, callingUid,
4504                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4505    }
4506    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4507            boolean wantInstantApps) {
4508        return updateFlagsForResolve(flags, userId, intent, callingUid,
4509                wantInstantApps, false /*onlyExposedExplicitly*/);
4510    }
4511    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4512            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4513        // Safe mode means we shouldn't match any third-party components
4514        if (mSafeMode) {
4515            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4516        }
4517        if (getInstantAppPackageName(callingUid) != null) {
4518            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4519            if (onlyExposedExplicitly) {
4520                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4521            }
4522            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4523            flags |= PackageManager.MATCH_INSTANT;
4524        } else {
4525            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4526            final boolean allowMatchInstant =
4527                    (wantInstantApps
4528                            && Intent.ACTION_VIEW.equals(intent.getAction())
4529                            && hasWebURI(intent))
4530                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4531            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4532                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4533            if (!allowMatchInstant) {
4534                flags &= ~PackageManager.MATCH_INSTANT;
4535            }
4536        }
4537        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4538    }
4539
4540    @Override
4541    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4542        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4543    }
4544
4545    /**
4546     * Important: The provided filterCallingUid is used exclusively to filter out activities
4547     * that can be seen based on user state. It's typically the original caller uid prior
4548     * to clearing. Because it can only be provided by trusted code, it's value can be
4549     * trusted and will be used as-is; unlike userId which will be validated by this method.
4550     */
4551    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4552            int filterCallingUid, int userId) {
4553        if (!sUserManager.exists(userId)) return null;
4554        flags = updateFlagsForComponent(flags, userId, component);
4555        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4556                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4557        synchronized (mPackages) {
4558            PackageParser.Activity a = mActivities.mActivities.get(component);
4559
4560            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4561            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4562                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4563                if (ps == null) return null;
4564                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4565                    return null;
4566                }
4567                return PackageParser.generateActivityInfo(
4568                        a, flags, ps.readUserState(userId), userId);
4569            }
4570            if (mResolveComponentName.equals(component)) {
4571                return PackageParser.generateActivityInfo(
4572                        mResolveActivity, flags, new PackageUserState(), userId);
4573            }
4574        }
4575        return null;
4576    }
4577
4578    @Override
4579    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4580            String resolvedType) {
4581        synchronized (mPackages) {
4582            if (component.equals(mResolveComponentName)) {
4583                // The resolver supports EVERYTHING!
4584                return true;
4585            }
4586            final int callingUid = Binder.getCallingUid();
4587            final int callingUserId = UserHandle.getUserId(callingUid);
4588            PackageParser.Activity a = mActivities.mActivities.get(component);
4589            if (a == null) {
4590                return false;
4591            }
4592            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4593            if (ps == null) {
4594                return false;
4595            }
4596            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4597                return false;
4598            }
4599            for (int i=0; i<a.intents.size(); i++) {
4600                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4601                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4602                    return true;
4603                }
4604            }
4605            return false;
4606        }
4607    }
4608
4609    @Override
4610    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4611        if (!sUserManager.exists(userId)) return null;
4612        final int callingUid = Binder.getCallingUid();
4613        flags = updateFlagsForComponent(flags, userId, component);
4614        enforceCrossUserPermission(callingUid, userId,
4615                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4616        synchronized (mPackages) {
4617            PackageParser.Activity a = mReceivers.mActivities.get(component);
4618            if (DEBUG_PACKAGE_INFO) Log.v(
4619                TAG, "getReceiverInfo " + component + ": " + a);
4620            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4621                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4622                if (ps == null) return null;
4623                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4624                    return null;
4625                }
4626                return PackageParser.generateActivityInfo(
4627                        a, flags, ps.readUserState(userId), userId);
4628            }
4629        }
4630        return null;
4631    }
4632
4633    @Override
4634    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4635            int flags, int userId) {
4636        if (!sUserManager.exists(userId)) return null;
4637        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4638        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4639            return null;
4640        }
4641
4642        flags = updateFlagsForPackage(flags, userId, null);
4643
4644        final boolean canSeeStaticLibraries =
4645                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4646                        == PERMISSION_GRANTED
4647                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4648                        == PERMISSION_GRANTED
4649                || canRequestPackageInstallsInternal(packageName,
4650                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4651                        false  /* throwIfPermNotDeclared*/)
4652                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4653                        == PERMISSION_GRANTED;
4654
4655        synchronized (mPackages) {
4656            List<SharedLibraryInfo> result = null;
4657
4658            final int libCount = mSharedLibraries.size();
4659            for (int i = 0; i < libCount; i++) {
4660                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4661                if (versionedLib == null) {
4662                    continue;
4663                }
4664
4665                final int versionCount = versionedLib.size();
4666                for (int j = 0; j < versionCount; j++) {
4667                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4668                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4669                        break;
4670                    }
4671                    final long identity = Binder.clearCallingIdentity();
4672                    try {
4673                        PackageInfo packageInfo = getPackageInfoVersioned(
4674                                libInfo.getDeclaringPackage(), flags
4675                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4676                        if (packageInfo == null) {
4677                            continue;
4678                        }
4679                    } finally {
4680                        Binder.restoreCallingIdentity(identity);
4681                    }
4682
4683                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4684                            libInfo.getVersion(), libInfo.getType(),
4685                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4686                            flags, userId));
4687
4688                    if (result == null) {
4689                        result = new ArrayList<>();
4690                    }
4691                    result.add(resLibInfo);
4692                }
4693            }
4694
4695            return result != null ? new ParceledListSlice<>(result) : null;
4696        }
4697    }
4698
4699    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4700            SharedLibraryInfo libInfo, int flags, int userId) {
4701        List<VersionedPackage> versionedPackages = null;
4702        final int packageCount = mSettings.mPackages.size();
4703        for (int i = 0; i < packageCount; i++) {
4704            PackageSetting ps = mSettings.mPackages.valueAt(i);
4705
4706            if (ps == null) {
4707                continue;
4708            }
4709
4710            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4711                continue;
4712            }
4713
4714            final String libName = libInfo.getName();
4715            if (libInfo.isStatic()) {
4716                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4717                if (libIdx < 0) {
4718                    continue;
4719                }
4720                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4721                    continue;
4722                }
4723                if (versionedPackages == null) {
4724                    versionedPackages = new ArrayList<>();
4725                }
4726                // If the dependent is a static shared lib, use the public package name
4727                String dependentPackageName = ps.name;
4728                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4729                    dependentPackageName = ps.pkg.manifestPackageName;
4730                }
4731                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4732            } else if (ps.pkg != null) {
4733                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4734                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4735                    if (versionedPackages == null) {
4736                        versionedPackages = new ArrayList<>();
4737                    }
4738                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4739                }
4740            }
4741        }
4742
4743        return versionedPackages;
4744    }
4745
4746    @Override
4747    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4748        if (!sUserManager.exists(userId)) return null;
4749        final int callingUid = Binder.getCallingUid();
4750        flags = updateFlagsForComponent(flags, userId, component);
4751        enforceCrossUserPermission(callingUid, userId,
4752                false /* requireFullPermission */, false /* checkShell */, "get service info");
4753        synchronized (mPackages) {
4754            PackageParser.Service s = mServices.mServices.get(component);
4755            if (DEBUG_PACKAGE_INFO) Log.v(
4756                TAG, "getServiceInfo " + component + ": " + s);
4757            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4758                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4759                if (ps == null) return null;
4760                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4761                    return null;
4762                }
4763                return PackageParser.generateServiceInfo(
4764                        s, flags, ps.readUserState(userId), userId);
4765            }
4766        }
4767        return null;
4768    }
4769
4770    @Override
4771    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4772        if (!sUserManager.exists(userId)) return null;
4773        final int callingUid = Binder.getCallingUid();
4774        flags = updateFlagsForComponent(flags, userId, component);
4775        enforceCrossUserPermission(callingUid, userId,
4776                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4777        synchronized (mPackages) {
4778            PackageParser.Provider p = mProviders.mProviders.get(component);
4779            if (DEBUG_PACKAGE_INFO) Log.v(
4780                TAG, "getProviderInfo " + component + ": " + p);
4781            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4782                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4783                if (ps == null) return null;
4784                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4785                    return null;
4786                }
4787                return PackageParser.generateProviderInfo(
4788                        p, flags, ps.readUserState(userId), userId);
4789            }
4790        }
4791        return null;
4792    }
4793
4794    @Override
4795    public String[] getSystemSharedLibraryNames() {
4796        // allow instant applications
4797        synchronized (mPackages) {
4798            Set<String> libs = null;
4799            final int libCount = mSharedLibraries.size();
4800            for (int i = 0; i < libCount; i++) {
4801                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4802                if (versionedLib == null) {
4803                    continue;
4804                }
4805                final int versionCount = versionedLib.size();
4806                for (int j = 0; j < versionCount; j++) {
4807                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4808                    if (!libEntry.info.isStatic()) {
4809                        if (libs == null) {
4810                            libs = new ArraySet<>();
4811                        }
4812                        libs.add(libEntry.info.getName());
4813                        break;
4814                    }
4815                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4816                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4817                            UserHandle.getUserId(Binder.getCallingUid()),
4818                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4819                        if (libs == null) {
4820                            libs = new ArraySet<>();
4821                        }
4822                        libs.add(libEntry.info.getName());
4823                        break;
4824                    }
4825                }
4826            }
4827
4828            if (libs != null) {
4829                String[] libsArray = new String[libs.size()];
4830                libs.toArray(libsArray);
4831                return libsArray;
4832            }
4833
4834            return null;
4835        }
4836    }
4837
4838    @Override
4839    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4840        // allow instant applications
4841        synchronized (mPackages) {
4842            return mServicesSystemSharedLibraryPackageName;
4843        }
4844    }
4845
4846    @Override
4847    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4848        // allow instant applications
4849        synchronized (mPackages) {
4850            return mSharedSystemSharedLibraryPackageName;
4851        }
4852    }
4853
4854    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4855        for (int i = userList.length - 1; i >= 0; --i) {
4856            final int userId = userList[i];
4857            // don't add instant app to the list of updates
4858            if (pkgSetting.getInstantApp(userId)) {
4859                continue;
4860            }
4861            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4862            if (changedPackages == null) {
4863                changedPackages = new SparseArray<>();
4864                mChangedPackages.put(userId, changedPackages);
4865            }
4866            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4867            if (sequenceNumbers == null) {
4868                sequenceNumbers = new HashMap<>();
4869                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4870            }
4871            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4872            if (sequenceNumber != null) {
4873                changedPackages.remove(sequenceNumber);
4874            }
4875            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4876            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4877        }
4878        mChangedPackagesSequenceNumber++;
4879    }
4880
4881    @Override
4882    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4883        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4884            return null;
4885        }
4886        synchronized (mPackages) {
4887            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4888                return null;
4889            }
4890            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4891            if (changedPackages == null) {
4892                return null;
4893            }
4894            final List<String> packageNames =
4895                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4896            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4897                final String packageName = changedPackages.get(i);
4898                if (packageName != null) {
4899                    packageNames.add(packageName);
4900                }
4901            }
4902            return packageNames.isEmpty()
4903                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4904        }
4905    }
4906
4907    @Override
4908    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4909        // allow instant applications
4910        ArrayList<FeatureInfo> res;
4911        synchronized (mAvailableFeatures) {
4912            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4913            res.addAll(mAvailableFeatures.values());
4914        }
4915        final FeatureInfo fi = new FeatureInfo();
4916        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4917                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4918        res.add(fi);
4919
4920        return new ParceledListSlice<>(res);
4921    }
4922
4923    @Override
4924    public boolean hasSystemFeature(String name, int version) {
4925        // allow instant applications
4926        synchronized (mAvailableFeatures) {
4927            final FeatureInfo feat = mAvailableFeatures.get(name);
4928            if (feat == null) {
4929                return false;
4930            } else {
4931                return feat.version >= version;
4932            }
4933        }
4934    }
4935
4936    @Override
4937    public int checkPermission(String permName, String pkgName, int userId) {
4938        if (!sUserManager.exists(userId)) {
4939            return PackageManager.PERMISSION_DENIED;
4940        }
4941        final int callingUid = Binder.getCallingUid();
4942
4943        synchronized (mPackages) {
4944            final PackageParser.Package p = mPackages.get(pkgName);
4945            if (p != null && p.mExtras != null) {
4946                final PackageSetting ps = (PackageSetting) p.mExtras;
4947                if (filterAppAccessLPr(ps, callingUid, userId)) {
4948                    return PackageManager.PERMISSION_DENIED;
4949                }
4950                final boolean instantApp = ps.getInstantApp(userId);
4951                final PermissionsState permissionsState = ps.getPermissionsState();
4952                if (permissionsState.hasPermission(permName, userId)) {
4953                    if (instantApp) {
4954                        BasePermission bp = mSettings.mPermissions.get(permName);
4955                        if (bp != null && bp.isInstant()) {
4956                            return PackageManager.PERMISSION_GRANTED;
4957                        }
4958                    } else {
4959                        return PackageManager.PERMISSION_GRANTED;
4960                    }
4961                }
4962                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4963                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4964                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4965                    return PackageManager.PERMISSION_GRANTED;
4966                }
4967            }
4968        }
4969
4970        return PackageManager.PERMISSION_DENIED;
4971    }
4972
4973    @Override
4974    public int checkUidPermission(String permName, int uid) {
4975        final int callingUid = Binder.getCallingUid();
4976        final int callingUserId = UserHandle.getUserId(callingUid);
4977        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4978        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
4979        final int userId = UserHandle.getUserId(uid);
4980        if (!sUserManager.exists(userId)) {
4981            return PackageManager.PERMISSION_DENIED;
4982        }
4983
4984        synchronized (mPackages) {
4985            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4986            if (obj != null) {
4987                if (obj instanceof SharedUserSetting) {
4988                    if (isCallerInstantApp) {
4989                        return PackageManager.PERMISSION_DENIED;
4990                    }
4991                } else if (obj instanceof PackageSetting) {
4992                    final PackageSetting ps = (PackageSetting) obj;
4993                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4994                        return PackageManager.PERMISSION_DENIED;
4995                    }
4996                }
4997                final SettingBase settingBase = (SettingBase) obj;
4998                final PermissionsState permissionsState = settingBase.getPermissionsState();
4999                if (permissionsState.hasPermission(permName, userId)) {
5000                    if (isUidInstantApp) {
5001                        BasePermission bp = mSettings.mPermissions.get(permName);
5002                        if (bp != null && bp.isInstant()) {
5003                            return PackageManager.PERMISSION_GRANTED;
5004                        }
5005                    } else {
5006                        return PackageManager.PERMISSION_GRANTED;
5007                    }
5008                }
5009                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5010                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5011                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5012                    return PackageManager.PERMISSION_GRANTED;
5013                }
5014            } else {
5015                ArraySet<String> perms = mSystemPermissions.get(uid);
5016                if (perms != null) {
5017                    if (perms.contains(permName)) {
5018                        return PackageManager.PERMISSION_GRANTED;
5019                    }
5020                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5021                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5022                        return PackageManager.PERMISSION_GRANTED;
5023                    }
5024                }
5025            }
5026        }
5027
5028        return PackageManager.PERMISSION_DENIED;
5029    }
5030
5031    @Override
5032    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5033        if (UserHandle.getCallingUserId() != userId) {
5034            mContext.enforceCallingPermission(
5035                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5036                    "isPermissionRevokedByPolicy for user " + userId);
5037        }
5038
5039        if (checkPermission(permission, packageName, userId)
5040                == PackageManager.PERMISSION_GRANTED) {
5041            return false;
5042        }
5043
5044        final int callingUid = Binder.getCallingUid();
5045        if (getInstantAppPackageName(callingUid) != null) {
5046            if (!isCallerSameApp(packageName, callingUid)) {
5047                return false;
5048            }
5049        } else {
5050            if (isInstantApp(packageName, userId)) {
5051                return false;
5052            }
5053        }
5054
5055        final long identity = Binder.clearCallingIdentity();
5056        try {
5057            final int flags = getPermissionFlags(permission, packageName, userId);
5058            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5059        } finally {
5060            Binder.restoreCallingIdentity(identity);
5061        }
5062    }
5063
5064    @Override
5065    public String getPermissionControllerPackageName() {
5066        synchronized (mPackages) {
5067            return mRequiredInstallerPackage;
5068        }
5069    }
5070
5071    /**
5072     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5073     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5074     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5075     * @param message the message to log on security exception
5076     */
5077    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5078            boolean checkShell, String message) {
5079        if (userId < 0) {
5080            throw new IllegalArgumentException("Invalid userId " + userId);
5081        }
5082        if (checkShell) {
5083            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5084        }
5085        if (userId == UserHandle.getUserId(callingUid)) return;
5086        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5087            if (requireFullPermission) {
5088                mContext.enforceCallingOrSelfPermission(
5089                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5090            } else {
5091                try {
5092                    mContext.enforceCallingOrSelfPermission(
5093                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5094                } catch (SecurityException se) {
5095                    mContext.enforceCallingOrSelfPermission(
5096                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5097                }
5098            }
5099        }
5100    }
5101
5102    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5103        if (callingUid == Process.SHELL_UID) {
5104            if (userHandle >= 0
5105                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5106                throw new SecurityException("Shell does not have permission to access user "
5107                        + userHandle);
5108            } else if (userHandle < 0) {
5109                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5110                        + Debug.getCallers(3));
5111            }
5112        }
5113    }
5114
5115    private BasePermission findPermissionTreeLP(String permName) {
5116        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5117            if (permName.startsWith(bp.name) &&
5118                    permName.length() > bp.name.length() &&
5119                    permName.charAt(bp.name.length()) == '.') {
5120                return bp;
5121            }
5122        }
5123        return null;
5124    }
5125
5126    private BasePermission checkPermissionTreeLP(String permName) {
5127        if (permName != null) {
5128            BasePermission bp = findPermissionTreeLP(permName);
5129            if (bp != null) {
5130                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5131                    return bp;
5132                }
5133                throw new SecurityException("Calling uid "
5134                        + Binder.getCallingUid()
5135                        + " is not allowed to add to permission tree "
5136                        + bp.name + " owned by uid " + bp.uid);
5137            }
5138        }
5139        throw new SecurityException("No permission tree found for " + permName);
5140    }
5141
5142    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5143        if (s1 == null) {
5144            return s2 == null;
5145        }
5146        if (s2 == null) {
5147            return false;
5148        }
5149        if (s1.getClass() != s2.getClass()) {
5150            return false;
5151        }
5152        return s1.equals(s2);
5153    }
5154
5155    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5156        if (pi1.icon != pi2.icon) return false;
5157        if (pi1.logo != pi2.logo) return false;
5158        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5159        if (!compareStrings(pi1.name, pi2.name)) return false;
5160        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5161        // We'll take care of setting this one.
5162        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5163        // These are not currently stored in settings.
5164        //if (!compareStrings(pi1.group, pi2.group)) return false;
5165        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5166        //if (pi1.labelRes != pi2.labelRes) return false;
5167        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5168        return true;
5169    }
5170
5171    int permissionInfoFootprint(PermissionInfo info) {
5172        int size = info.name.length();
5173        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5174        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5175        return size;
5176    }
5177
5178    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5179        int size = 0;
5180        for (BasePermission perm : mSettings.mPermissions.values()) {
5181            if (perm.uid == tree.uid) {
5182                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5183            }
5184        }
5185        return size;
5186    }
5187
5188    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5189        // We calculate the max size of permissions defined by this uid and throw
5190        // if that plus the size of 'info' would exceed our stated maximum.
5191        if (tree.uid != Process.SYSTEM_UID) {
5192            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5193            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5194                throw new SecurityException("Permission tree size cap exceeded");
5195            }
5196        }
5197    }
5198
5199    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5201            throw new SecurityException("Instant apps can't add permissions");
5202        }
5203        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5204            throw new SecurityException("Label must be specified in permission");
5205        }
5206        BasePermission tree = checkPermissionTreeLP(info.name);
5207        BasePermission bp = mSettings.mPermissions.get(info.name);
5208        boolean added = bp == null;
5209        boolean changed = true;
5210        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5211        if (added) {
5212            enforcePermissionCapLocked(info, tree);
5213            bp = new BasePermission(info.name, tree.sourcePackage,
5214                    BasePermission.TYPE_DYNAMIC);
5215        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5216            throw new SecurityException(
5217                    "Not allowed to modify non-dynamic permission "
5218                    + info.name);
5219        } else {
5220            if (bp.protectionLevel == fixedLevel
5221                    && bp.perm.owner.equals(tree.perm.owner)
5222                    && bp.uid == tree.uid
5223                    && comparePermissionInfos(bp.perm.info, info)) {
5224                changed = false;
5225            }
5226        }
5227        bp.protectionLevel = fixedLevel;
5228        info = new PermissionInfo(info);
5229        info.protectionLevel = fixedLevel;
5230        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5231        bp.perm.info.packageName = tree.perm.info.packageName;
5232        bp.uid = tree.uid;
5233        if (added) {
5234            mSettings.mPermissions.put(info.name, bp);
5235        }
5236        if (changed) {
5237            if (!async) {
5238                mSettings.writeLPr();
5239            } else {
5240                scheduleWriteSettingsLocked();
5241            }
5242        }
5243        return added;
5244    }
5245
5246    @Override
5247    public boolean addPermission(PermissionInfo info) {
5248        synchronized (mPackages) {
5249            return addPermissionLocked(info, false);
5250        }
5251    }
5252
5253    @Override
5254    public boolean addPermissionAsync(PermissionInfo info) {
5255        synchronized (mPackages) {
5256            return addPermissionLocked(info, true);
5257        }
5258    }
5259
5260    @Override
5261    public void removePermission(String name) {
5262        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5263            throw new SecurityException("Instant applications don't have access to this method");
5264        }
5265        synchronized (mPackages) {
5266            checkPermissionTreeLP(name);
5267            BasePermission bp = mSettings.mPermissions.get(name);
5268            if (bp != null) {
5269                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5270                    throw new SecurityException(
5271                            "Not allowed to modify non-dynamic permission "
5272                            + name);
5273                }
5274                mSettings.mPermissions.remove(name);
5275                mSettings.writeLPr();
5276            }
5277        }
5278    }
5279
5280    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5281            PackageParser.Package pkg, BasePermission bp) {
5282        int index = pkg.requestedPermissions.indexOf(bp.name);
5283        if (index == -1) {
5284            throw new SecurityException("Package " + pkg.packageName
5285                    + " has not requested permission " + bp.name);
5286        }
5287        if (!bp.isRuntime() && !bp.isDevelopment()) {
5288            throw new SecurityException("Permission " + bp.name
5289                    + " is not a changeable permission type");
5290        }
5291    }
5292
5293    @Override
5294    public void grantRuntimePermission(String packageName, String name, final int userId) {
5295        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5296    }
5297
5298    private void grantRuntimePermission(String packageName, String name, final int userId,
5299            boolean overridePolicy) {
5300        if (!sUserManager.exists(userId)) {
5301            Log.e(TAG, "No such user:" + userId);
5302            return;
5303        }
5304        final int callingUid = Binder.getCallingUid();
5305
5306        mContext.enforceCallingOrSelfPermission(
5307                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5308                "grantRuntimePermission");
5309
5310        enforceCrossUserPermission(callingUid, userId,
5311                true /* requireFullPermission */, true /* checkShell */,
5312                "grantRuntimePermission");
5313
5314        final int uid;
5315        final PackageSetting ps;
5316
5317        synchronized (mPackages) {
5318            final PackageParser.Package pkg = mPackages.get(packageName);
5319            if (pkg == null) {
5320                throw new IllegalArgumentException("Unknown package: " + packageName);
5321            }
5322            final BasePermission bp = mSettings.mPermissions.get(name);
5323            if (bp == null) {
5324                throw new IllegalArgumentException("Unknown permission: " + name);
5325            }
5326            ps = (PackageSetting) pkg.mExtras;
5327            if (ps == null
5328                    || filterAppAccessLPr(ps, callingUid, userId)) {
5329                throw new IllegalArgumentException("Unknown package: " + packageName);
5330            }
5331
5332            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5333
5334            // If a permission review is required for legacy apps we represent
5335            // their permissions as always granted runtime ones since we need
5336            // to keep the review required permission flag per user while an
5337            // install permission's state is shared across all users.
5338            if (mPermissionReviewRequired
5339                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5340                    && bp.isRuntime()) {
5341                return;
5342            }
5343
5344            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5345
5346            final PermissionsState permissionsState = ps.getPermissionsState();
5347
5348            final int flags = permissionsState.getPermissionFlags(name, userId);
5349            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5350                throw new SecurityException("Cannot grant system fixed permission "
5351                        + name + " for package " + packageName);
5352            }
5353            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5354                throw new SecurityException("Cannot grant policy fixed permission "
5355                        + name + " for package " + packageName);
5356            }
5357
5358            if (bp.isDevelopment()) {
5359                // Development permissions must be handled specially, since they are not
5360                // normal runtime permissions.  For now they apply to all users.
5361                if (permissionsState.grantInstallPermission(bp) !=
5362                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5363                    scheduleWriteSettingsLocked();
5364                }
5365                return;
5366            }
5367
5368            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5369                throw new SecurityException("Cannot grant non-ephemeral permission"
5370                        + name + " for package " + packageName);
5371            }
5372
5373            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5374                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5375                return;
5376            }
5377
5378            final int result = permissionsState.grantRuntimePermission(bp, userId);
5379            switch (result) {
5380                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5381                    return;
5382                }
5383
5384                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5385                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5386                    mHandler.post(new Runnable() {
5387                        @Override
5388                        public void run() {
5389                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5390                        }
5391                    });
5392                }
5393                break;
5394            }
5395
5396            if (bp.isRuntime()) {
5397                logPermissionGranted(mContext, name, packageName);
5398            }
5399
5400            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5401
5402            // Not critical if that is lost - app has to request again.
5403            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5404        }
5405
5406        // Only need to do this if user is initialized. Otherwise it's a new user
5407        // and there are no processes running as the user yet and there's no need
5408        // to make an expensive call to remount processes for the changed permissions.
5409        if (READ_EXTERNAL_STORAGE.equals(name)
5410                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5411            final long token = Binder.clearCallingIdentity();
5412            try {
5413                if (sUserManager.isInitialized(userId)) {
5414                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5415                            StorageManagerInternal.class);
5416                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5417                }
5418            } finally {
5419                Binder.restoreCallingIdentity(token);
5420            }
5421        }
5422    }
5423
5424    @Override
5425    public void revokeRuntimePermission(String packageName, String name, int userId) {
5426        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5427    }
5428
5429    private void revokeRuntimePermission(String packageName, String name, int userId,
5430            boolean overridePolicy) {
5431        if (!sUserManager.exists(userId)) {
5432            Log.e(TAG, "No such user:" + userId);
5433            return;
5434        }
5435
5436        mContext.enforceCallingOrSelfPermission(
5437                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5438                "revokeRuntimePermission");
5439
5440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5441                true /* requireFullPermission */, true /* checkShell */,
5442                "revokeRuntimePermission");
5443
5444        final int appId;
5445
5446        synchronized (mPackages) {
5447            final PackageParser.Package pkg = mPackages.get(packageName);
5448            if (pkg == null) {
5449                throw new IllegalArgumentException("Unknown package: " + packageName);
5450            }
5451            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5452            if (ps == null
5453                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5454                throw new IllegalArgumentException("Unknown package: " + packageName);
5455            }
5456            final BasePermission bp = mSettings.mPermissions.get(name);
5457            if (bp == null) {
5458                throw new IllegalArgumentException("Unknown permission: " + name);
5459            }
5460
5461            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5462
5463            // If a permission review is required for legacy apps we represent
5464            // their permissions as always granted runtime ones since we need
5465            // to keep the review required permission flag per user while an
5466            // install permission's state is shared across all users.
5467            if (mPermissionReviewRequired
5468                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5469                    && bp.isRuntime()) {
5470                return;
5471            }
5472
5473            final PermissionsState permissionsState = ps.getPermissionsState();
5474
5475            final int flags = permissionsState.getPermissionFlags(name, userId);
5476            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5477                throw new SecurityException("Cannot revoke system fixed permission "
5478                        + name + " for package " + packageName);
5479            }
5480            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5481                throw new SecurityException("Cannot revoke policy fixed permission "
5482                        + name + " for package " + packageName);
5483            }
5484
5485            if (bp.isDevelopment()) {
5486                // Development permissions must be handled specially, since they are not
5487                // normal runtime permissions.  For now they apply to all users.
5488                if (permissionsState.revokeInstallPermission(bp) !=
5489                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5490                    scheduleWriteSettingsLocked();
5491                }
5492                return;
5493            }
5494
5495            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5496                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5497                return;
5498            }
5499
5500            if (bp.isRuntime()) {
5501                logPermissionRevoked(mContext, name, packageName);
5502            }
5503
5504            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5505
5506            // Critical, after this call app should never have the permission.
5507            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5508
5509            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5510        }
5511
5512        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5513    }
5514
5515    /**
5516     * Get the first event id for the permission.
5517     *
5518     * <p>There are four events for each permission: <ul>
5519     *     <li>Request permission: first id + 0</li>
5520     *     <li>Grant permission: first id + 1</li>
5521     *     <li>Request for permission denied: first id + 2</li>
5522     *     <li>Revoke permission: first id + 3</li>
5523     * </ul></p>
5524     *
5525     * @param name name of the permission
5526     *
5527     * @return The first event id for the permission
5528     */
5529    private static int getBaseEventId(@NonNull String name) {
5530        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5531
5532        if (eventIdIndex == -1) {
5533            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5534                    || "user".equals(Build.TYPE)) {
5535                Log.i(TAG, "Unknown permission " + name);
5536
5537                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5538            } else {
5539                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5540                //
5541                // Also update
5542                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5543                // - metrics_constants.proto
5544                throw new IllegalStateException("Unknown permission " + name);
5545            }
5546        }
5547
5548        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5549    }
5550
5551    /**
5552     * Log that a permission was revoked.
5553     *
5554     * @param context Context of the caller
5555     * @param name name of the permission
5556     * @param packageName package permission if for
5557     */
5558    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5559            @NonNull String packageName) {
5560        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5561    }
5562
5563    /**
5564     * Log that a permission request was granted.
5565     *
5566     * @param context Context of the caller
5567     * @param name name of the permission
5568     * @param packageName package permission if for
5569     */
5570    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5571            @NonNull String packageName) {
5572        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5573    }
5574
5575    @Override
5576    public void resetRuntimePermissions() {
5577        mContext.enforceCallingOrSelfPermission(
5578                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5579                "revokeRuntimePermission");
5580
5581        int callingUid = Binder.getCallingUid();
5582        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5583            mContext.enforceCallingOrSelfPermission(
5584                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5585                    "resetRuntimePermissions");
5586        }
5587
5588        synchronized (mPackages) {
5589            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5590            for (int userId : UserManagerService.getInstance().getUserIds()) {
5591                final int packageCount = mPackages.size();
5592                for (int i = 0; i < packageCount; i++) {
5593                    PackageParser.Package pkg = mPackages.valueAt(i);
5594                    if (!(pkg.mExtras instanceof PackageSetting)) {
5595                        continue;
5596                    }
5597                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5598                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5599                }
5600            }
5601        }
5602    }
5603
5604    @Override
5605    public int getPermissionFlags(String name, String packageName, int userId) {
5606        if (!sUserManager.exists(userId)) {
5607            return 0;
5608        }
5609
5610        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5611
5612        final int callingUid = Binder.getCallingUid();
5613        enforceCrossUserPermission(callingUid, userId,
5614                true /* requireFullPermission */, false /* checkShell */,
5615                "getPermissionFlags");
5616
5617        synchronized (mPackages) {
5618            final PackageParser.Package pkg = mPackages.get(packageName);
5619            if (pkg == null) {
5620                return 0;
5621            }
5622            final BasePermission bp = mSettings.mPermissions.get(name);
5623            if (bp == null) {
5624                return 0;
5625            }
5626            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5627            if (ps == null
5628                    || filterAppAccessLPr(ps, callingUid, userId)) {
5629                return 0;
5630            }
5631            PermissionsState permissionsState = ps.getPermissionsState();
5632            return permissionsState.getPermissionFlags(name, userId);
5633        }
5634    }
5635
5636    @Override
5637    public void updatePermissionFlags(String name, String packageName, int flagMask,
5638            int flagValues, int userId) {
5639        if (!sUserManager.exists(userId)) {
5640            return;
5641        }
5642
5643        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5644
5645        final int callingUid = Binder.getCallingUid();
5646        enforceCrossUserPermission(callingUid, userId,
5647                true /* requireFullPermission */, true /* checkShell */,
5648                "updatePermissionFlags");
5649
5650        // Only the system can change these flags and nothing else.
5651        if (getCallingUid() != Process.SYSTEM_UID) {
5652            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5653            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5654            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5655            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5656            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5657        }
5658
5659        synchronized (mPackages) {
5660            final PackageParser.Package pkg = mPackages.get(packageName);
5661            if (pkg == null) {
5662                throw new IllegalArgumentException("Unknown package: " + packageName);
5663            }
5664            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5665            if (ps == null
5666                    || filterAppAccessLPr(ps, callingUid, userId)) {
5667                throw new IllegalArgumentException("Unknown package: " + packageName);
5668            }
5669
5670            final BasePermission bp = mSettings.mPermissions.get(name);
5671            if (bp == null) {
5672                throw new IllegalArgumentException("Unknown permission: " + name);
5673            }
5674
5675            PermissionsState permissionsState = ps.getPermissionsState();
5676
5677            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5678
5679            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5680                // Install and runtime permissions are stored in different places,
5681                // so figure out what permission changed and persist the change.
5682                if (permissionsState.getInstallPermissionState(name) != null) {
5683                    scheduleWriteSettingsLocked();
5684                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5685                        || hadState) {
5686                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5687                }
5688            }
5689        }
5690    }
5691
5692    /**
5693     * Update the permission flags for all packages and runtime permissions of a user in order
5694     * to allow device or profile owner to remove POLICY_FIXED.
5695     */
5696    @Override
5697    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5698        if (!sUserManager.exists(userId)) {
5699            return;
5700        }
5701
5702        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5703
5704        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5705                true /* requireFullPermission */, true /* checkShell */,
5706                "updatePermissionFlagsForAllApps");
5707
5708        // Only the system can change system fixed flags.
5709        if (getCallingUid() != Process.SYSTEM_UID) {
5710            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5711            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5712        }
5713
5714        synchronized (mPackages) {
5715            boolean changed = false;
5716            final int packageCount = mPackages.size();
5717            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5718                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5719                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5720                if (ps == null) {
5721                    continue;
5722                }
5723                PermissionsState permissionsState = ps.getPermissionsState();
5724                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5725                        userId, flagMask, flagValues);
5726            }
5727            if (changed) {
5728                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5729            }
5730        }
5731    }
5732
5733    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5734        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5735                != PackageManager.PERMISSION_GRANTED
5736            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5737                != PackageManager.PERMISSION_GRANTED) {
5738            throw new SecurityException(message + " requires "
5739                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5740                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5741        }
5742    }
5743
5744    @Override
5745    public boolean shouldShowRequestPermissionRationale(String permissionName,
5746            String packageName, int userId) {
5747        if (UserHandle.getCallingUserId() != userId) {
5748            mContext.enforceCallingPermission(
5749                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5750                    "canShowRequestPermissionRationale for user " + userId);
5751        }
5752
5753        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5754        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5755            return false;
5756        }
5757
5758        if (checkPermission(permissionName, packageName, userId)
5759                == PackageManager.PERMISSION_GRANTED) {
5760            return false;
5761        }
5762
5763        final int flags;
5764
5765        final long identity = Binder.clearCallingIdentity();
5766        try {
5767            flags = getPermissionFlags(permissionName,
5768                    packageName, userId);
5769        } finally {
5770            Binder.restoreCallingIdentity(identity);
5771        }
5772
5773        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5774                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5775                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5776
5777        if ((flags & fixedFlags) != 0) {
5778            return false;
5779        }
5780
5781        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5782    }
5783
5784    @Override
5785    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5786        mContext.enforceCallingOrSelfPermission(
5787                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5788                "addOnPermissionsChangeListener");
5789
5790        synchronized (mPackages) {
5791            mOnPermissionChangeListeners.addListenerLocked(listener);
5792        }
5793    }
5794
5795    @Override
5796    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5797        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5798            throw new SecurityException("Instant applications don't have access to this method");
5799        }
5800        synchronized (mPackages) {
5801            mOnPermissionChangeListeners.removeListenerLocked(listener);
5802        }
5803    }
5804
5805    @Override
5806    public boolean isProtectedBroadcast(String actionName) {
5807        // allow instant applications
5808        synchronized (mPackages) {
5809            if (mProtectedBroadcasts.contains(actionName)) {
5810                return true;
5811            } else if (actionName != null) {
5812                // TODO: remove these terrible hacks
5813                if (actionName.startsWith("android.net.netmon.lingerExpired")
5814                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5815                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5816                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5817                    return true;
5818                }
5819            }
5820        }
5821        return false;
5822    }
5823
5824    @Override
5825    public int checkSignatures(String pkg1, String pkg2) {
5826        synchronized (mPackages) {
5827            final PackageParser.Package p1 = mPackages.get(pkg1);
5828            final PackageParser.Package p2 = mPackages.get(pkg2);
5829            if (p1 == null || p1.mExtras == null
5830                    || p2 == null || p2.mExtras == null) {
5831                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5832            }
5833            final int callingUid = Binder.getCallingUid();
5834            final int callingUserId = UserHandle.getUserId(callingUid);
5835            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5836            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5837            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5838                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5839                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5840            }
5841            return compareSignatures(p1.mSignatures, p2.mSignatures);
5842        }
5843    }
5844
5845    @Override
5846    public int checkUidSignatures(int uid1, int uid2) {
5847        final int callingUid = Binder.getCallingUid();
5848        final int callingUserId = UserHandle.getUserId(callingUid);
5849        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5850        // Map to base uids.
5851        uid1 = UserHandle.getAppId(uid1);
5852        uid2 = UserHandle.getAppId(uid2);
5853        // reader
5854        synchronized (mPackages) {
5855            Signature[] s1;
5856            Signature[] s2;
5857            Object obj = mSettings.getUserIdLPr(uid1);
5858            if (obj != null) {
5859                if (obj instanceof SharedUserSetting) {
5860                    if (isCallerInstantApp) {
5861                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5862                    }
5863                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5864                } else if (obj instanceof PackageSetting) {
5865                    final PackageSetting ps = (PackageSetting) obj;
5866                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5867                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5868                    }
5869                    s1 = ps.signatures.mSignatures;
5870                } else {
5871                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5872                }
5873            } else {
5874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5875            }
5876            obj = mSettings.getUserIdLPr(uid2);
5877            if (obj != null) {
5878                if (obj instanceof SharedUserSetting) {
5879                    if (isCallerInstantApp) {
5880                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5881                    }
5882                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5883                } else if (obj instanceof PackageSetting) {
5884                    final PackageSetting ps = (PackageSetting) obj;
5885                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5886                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5887                    }
5888                    s2 = ps.signatures.mSignatures;
5889                } else {
5890                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891                }
5892            } else {
5893                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5894            }
5895            return compareSignatures(s1, s2);
5896        }
5897    }
5898
5899    /**
5900     * This method should typically only be used when granting or revoking
5901     * permissions, since the app may immediately restart after this call.
5902     * <p>
5903     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5904     * guard your work against the app being relaunched.
5905     */
5906    private void killUid(int appId, int userId, String reason) {
5907        final long identity = Binder.clearCallingIdentity();
5908        try {
5909            IActivityManager am = ActivityManager.getService();
5910            if (am != null) {
5911                try {
5912                    am.killUid(appId, userId, reason);
5913                } catch (RemoteException e) {
5914                    /* ignore - same process */
5915                }
5916            }
5917        } finally {
5918            Binder.restoreCallingIdentity(identity);
5919        }
5920    }
5921
5922    /**
5923     * Compares two sets of signatures. Returns:
5924     * <br />
5925     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5926     * <br />
5927     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5928     * <br />
5929     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5930     * <br />
5931     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5932     * <br />
5933     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5934     */
5935    static int compareSignatures(Signature[] s1, Signature[] s2) {
5936        if (s1 == null) {
5937            return s2 == null
5938                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5939                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5940        }
5941
5942        if (s2 == null) {
5943            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5944        }
5945
5946        if (s1.length != s2.length) {
5947            return PackageManager.SIGNATURE_NO_MATCH;
5948        }
5949
5950        // Since both signature sets are of size 1, we can compare without HashSets.
5951        if (s1.length == 1) {
5952            return s1[0].equals(s2[0]) ?
5953                    PackageManager.SIGNATURE_MATCH :
5954                    PackageManager.SIGNATURE_NO_MATCH;
5955        }
5956
5957        ArraySet<Signature> set1 = new ArraySet<Signature>();
5958        for (Signature sig : s1) {
5959            set1.add(sig);
5960        }
5961        ArraySet<Signature> set2 = new ArraySet<Signature>();
5962        for (Signature sig : s2) {
5963            set2.add(sig);
5964        }
5965        // Make sure s2 contains all signatures in s1.
5966        if (set1.equals(set2)) {
5967            return PackageManager.SIGNATURE_MATCH;
5968        }
5969        return PackageManager.SIGNATURE_NO_MATCH;
5970    }
5971
5972    /**
5973     * If the database version for this type of package (internal storage or
5974     * external storage) is less than the version where package signatures
5975     * were updated, return true.
5976     */
5977    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5978        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5979        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5980    }
5981
5982    /**
5983     * Used for backward compatibility to make sure any packages with
5984     * certificate chains get upgraded to the new style. {@code existingSigs}
5985     * will be in the old format (since they were stored on disk from before the
5986     * system upgrade) and {@code scannedSigs} will be in the newer format.
5987     */
5988    private int compareSignaturesCompat(PackageSignatures existingSigs,
5989            PackageParser.Package scannedPkg) {
5990        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5991            return PackageManager.SIGNATURE_NO_MATCH;
5992        }
5993
5994        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5995        for (Signature sig : existingSigs.mSignatures) {
5996            existingSet.add(sig);
5997        }
5998        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5999        for (Signature sig : scannedPkg.mSignatures) {
6000            try {
6001                Signature[] chainSignatures = sig.getChainSignatures();
6002                for (Signature chainSig : chainSignatures) {
6003                    scannedCompatSet.add(chainSig);
6004                }
6005            } catch (CertificateEncodingException e) {
6006                scannedCompatSet.add(sig);
6007            }
6008        }
6009        /*
6010         * Make sure the expanded scanned set contains all signatures in the
6011         * existing one.
6012         */
6013        if (scannedCompatSet.equals(existingSet)) {
6014            // Migrate the old signatures to the new scheme.
6015            existingSigs.assignSignatures(scannedPkg.mSignatures);
6016            // The new KeySets will be re-added later in the scanning process.
6017            synchronized (mPackages) {
6018                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6019            }
6020            return PackageManager.SIGNATURE_MATCH;
6021        }
6022        return PackageManager.SIGNATURE_NO_MATCH;
6023    }
6024
6025    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6026        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6027        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6028    }
6029
6030    private int compareSignaturesRecover(PackageSignatures existingSigs,
6031            PackageParser.Package scannedPkg) {
6032        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6033            return PackageManager.SIGNATURE_NO_MATCH;
6034        }
6035
6036        String msg = null;
6037        try {
6038            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6039                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6040                        + scannedPkg.packageName);
6041                return PackageManager.SIGNATURE_MATCH;
6042            }
6043        } catch (CertificateException e) {
6044            msg = e.getMessage();
6045        }
6046
6047        logCriticalInfo(Log.INFO,
6048                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6049        return PackageManager.SIGNATURE_NO_MATCH;
6050    }
6051
6052    @Override
6053    public List<String> getAllPackages() {
6054        final int callingUid = Binder.getCallingUid();
6055        final int callingUserId = UserHandle.getUserId(callingUid);
6056        synchronized (mPackages) {
6057            if (canViewInstantApps(callingUid, callingUserId)) {
6058                return new ArrayList<String>(mPackages.keySet());
6059            }
6060            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6061            final List<String> result = new ArrayList<>();
6062            if (instantAppPkgName != null) {
6063                // caller is an instant application; filter unexposed applications
6064                for (PackageParser.Package pkg : mPackages.values()) {
6065                    if (!pkg.visibleToInstantApps) {
6066                        continue;
6067                    }
6068                    result.add(pkg.packageName);
6069                }
6070            } else {
6071                // caller is a normal application; filter instant applications
6072                for (PackageParser.Package pkg : mPackages.values()) {
6073                    final PackageSetting ps =
6074                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6075                    if (ps != null
6076                            && ps.getInstantApp(callingUserId)
6077                            && !mInstantAppRegistry.isInstantAccessGranted(
6078                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6079                        continue;
6080                    }
6081                    result.add(pkg.packageName);
6082                }
6083            }
6084            return result;
6085        }
6086    }
6087
6088    @Override
6089    public String[] getPackagesForUid(int uid) {
6090        final int callingUid = Binder.getCallingUid();
6091        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6092        final int userId = UserHandle.getUserId(uid);
6093        uid = UserHandle.getAppId(uid);
6094        // reader
6095        synchronized (mPackages) {
6096            Object obj = mSettings.getUserIdLPr(uid);
6097            if (obj instanceof SharedUserSetting) {
6098                if (isCallerInstantApp) {
6099                    return null;
6100                }
6101                final SharedUserSetting sus = (SharedUserSetting) obj;
6102                final int N = sus.packages.size();
6103                String[] res = new String[N];
6104                final Iterator<PackageSetting> it = sus.packages.iterator();
6105                int i = 0;
6106                while (it.hasNext()) {
6107                    PackageSetting ps = it.next();
6108                    if (ps.getInstalled(userId)) {
6109                        res[i++] = ps.name;
6110                    } else {
6111                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6112                    }
6113                }
6114                return res;
6115            } else if (obj instanceof PackageSetting) {
6116                final PackageSetting ps = (PackageSetting) obj;
6117                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6118                    return new String[]{ps.name};
6119                }
6120            }
6121        }
6122        return null;
6123    }
6124
6125    @Override
6126    public String getNameForUid(int uid) {
6127        final int callingUid = Binder.getCallingUid();
6128        if (getInstantAppPackageName(callingUid) != null) {
6129            return null;
6130        }
6131        synchronized (mPackages) {
6132            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6133            if (obj instanceof SharedUserSetting) {
6134                final SharedUserSetting sus = (SharedUserSetting) obj;
6135                return sus.name + ":" + sus.userId;
6136            } else if (obj instanceof PackageSetting) {
6137                final PackageSetting ps = (PackageSetting) obj;
6138                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6139                    return null;
6140                }
6141                return ps.name;
6142            }
6143        }
6144        return null;
6145    }
6146
6147    @Override
6148    public int getUidForSharedUser(String sharedUserName) {
6149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6150            return -1;
6151        }
6152        if (sharedUserName == null) {
6153            return -1;
6154        }
6155        // reader
6156        synchronized (mPackages) {
6157            SharedUserSetting suid;
6158            try {
6159                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6160                if (suid != null) {
6161                    return suid.userId;
6162                }
6163            } catch (PackageManagerException ignore) {
6164                // can't happen, but, still need to catch it
6165            }
6166            return -1;
6167        }
6168    }
6169
6170    @Override
6171    public int getFlagsForUid(int uid) {
6172        final int callingUid = Binder.getCallingUid();
6173        if (getInstantAppPackageName(callingUid) != null) {
6174            return 0;
6175        }
6176        synchronized (mPackages) {
6177            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6178            if (obj instanceof SharedUserSetting) {
6179                final SharedUserSetting sus = (SharedUserSetting) obj;
6180                return sus.pkgFlags;
6181            } else if (obj instanceof PackageSetting) {
6182                final PackageSetting ps = (PackageSetting) obj;
6183                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6184                    return 0;
6185                }
6186                return ps.pkgFlags;
6187            }
6188        }
6189        return 0;
6190    }
6191
6192    @Override
6193    public int getPrivateFlagsForUid(int uid) {
6194        final int callingUid = Binder.getCallingUid();
6195        if (getInstantAppPackageName(callingUid) != null) {
6196            return 0;
6197        }
6198        synchronized (mPackages) {
6199            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6200            if (obj instanceof SharedUserSetting) {
6201                final SharedUserSetting sus = (SharedUserSetting) obj;
6202                return sus.pkgPrivateFlags;
6203            } else if (obj instanceof PackageSetting) {
6204                final PackageSetting ps = (PackageSetting) obj;
6205                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6206                    return 0;
6207                }
6208                return ps.pkgPrivateFlags;
6209            }
6210        }
6211        return 0;
6212    }
6213
6214    @Override
6215    public boolean isUidPrivileged(int uid) {
6216        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6217            return false;
6218        }
6219        uid = UserHandle.getAppId(uid);
6220        // reader
6221        synchronized (mPackages) {
6222            Object obj = mSettings.getUserIdLPr(uid);
6223            if (obj instanceof SharedUserSetting) {
6224                final SharedUserSetting sus = (SharedUserSetting) obj;
6225                final Iterator<PackageSetting> it = sus.packages.iterator();
6226                while (it.hasNext()) {
6227                    if (it.next().isPrivileged()) {
6228                        return true;
6229                    }
6230                }
6231            } else if (obj instanceof PackageSetting) {
6232                final PackageSetting ps = (PackageSetting) obj;
6233                return ps.isPrivileged();
6234            }
6235        }
6236        return false;
6237    }
6238
6239    @Override
6240    public String[] getAppOpPermissionPackages(String permissionName) {
6241        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6242            return null;
6243        }
6244        synchronized (mPackages) {
6245            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6246            if (pkgs == null) {
6247                return null;
6248            }
6249            return pkgs.toArray(new String[pkgs.size()]);
6250        }
6251    }
6252
6253    @Override
6254    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6255            int flags, int userId) {
6256        return resolveIntentInternal(
6257                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6258    }
6259
6260    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6261            int flags, int userId, boolean resolveForStart) {
6262        try {
6263            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6264
6265            if (!sUserManager.exists(userId)) return null;
6266            final int callingUid = Binder.getCallingUid();
6267            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6268            enforceCrossUserPermission(callingUid, userId,
6269                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6270
6271            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6272            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6273                    flags, callingUid, userId, resolveForStart);
6274            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6275
6276            final ResolveInfo bestChoice =
6277                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6278            return bestChoice;
6279        } finally {
6280            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6281        }
6282    }
6283
6284    @Override
6285    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6286        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6287            throw new SecurityException(
6288                    "findPersistentPreferredActivity can only be run by the system");
6289        }
6290        if (!sUserManager.exists(userId)) {
6291            return null;
6292        }
6293        final int callingUid = Binder.getCallingUid();
6294        intent = updateIntentForResolve(intent);
6295        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6296        final int flags = updateFlagsForResolve(
6297                0, userId, intent, callingUid, false /*includeInstantApps*/);
6298        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6299                userId);
6300        synchronized (mPackages) {
6301            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6302                    userId);
6303        }
6304    }
6305
6306    @Override
6307    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6308            IntentFilter filter, int match, ComponentName activity) {
6309        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6310            return;
6311        }
6312        final int userId = UserHandle.getCallingUserId();
6313        if (DEBUG_PREFERRED) {
6314            Log.v(TAG, "setLastChosenActivity intent=" + intent
6315                + " resolvedType=" + resolvedType
6316                + " flags=" + flags
6317                + " filter=" + filter
6318                + " match=" + match
6319                + " activity=" + activity);
6320            filter.dump(new PrintStreamPrinter(System.out), "    ");
6321        }
6322        intent.setComponent(null);
6323        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6324                userId);
6325        // Find any earlier preferred or last chosen entries and nuke them
6326        findPreferredActivity(intent, resolvedType,
6327                flags, query, 0, false, true, false, userId);
6328        // Add the new activity as the last chosen for this filter
6329        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6330                "Setting last chosen");
6331    }
6332
6333    @Override
6334    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6336            return null;
6337        }
6338        final int userId = UserHandle.getCallingUserId();
6339        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6340        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6341                userId);
6342        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6343                false, false, false, userId);
6344    }
6345
6346    /**
6347     * Returns whether or not instant apps have been disabled remotely.
6348     */
6349    private boolean isEphemeralDisabled() {
6350        return mEphemeralAppsDisabled;
6351    }
6352
6353    private boolean isInstantAppAllowed(
6354            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6355            boolean skipPackageCheck) {
6356        if (mInstantAppResolverConnection == null) {
6357            return false;
6358        }
6359        if (mInstantAppInstallerActivity == null) {
6360            return false;
6361        }
6362        if (intent.getComponent() != null) {
6363            return false;
6364        }
6365        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6366            return false;
6367        }
6368        if (!skipPackageCheck && intent.getPackage() != null) {
6369            return false;
6370        }
6371        final boolean isWebUri = hasWebURI(intent);
6372        if (!isWebUri || intent.getData().getHost() == null) {
6373            return false;
6374        }
6375        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6376        // Or if there's already an ephemeral app installed that handles the action
6377        synchronized (mPackages) {
6378            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6379            for (int n = 0; n < count; n++) {
6380                final ResolveInfo info = resolvedActivities.get(n);
6381                final String packageName = info.activityInfo.packageName;
6382                final PackageSetting ps = mSettings.mPackages.get(packageName);
6383                if (ps != null) {
6384                    // only check domain verification status if the app is not a browser
6385                    if (!info.handleAllWebDataURI) {
6386                        // Try to get the status from User settings first
6387                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6388                        final int status = (int) (packedStatus >> 32);
6389                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6390                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6391                            if (DEBUG_EPHEMERAL) {
6392                                Slog.v(TAG, "DENY instant app;"
6393                                    + " pkg: " + packageName + ", status: " + status);
6394                            }
6395                            return false;
6396                        }
6397                    }
6398                    if (ps.getInstantApp(userId)) {
6399                        if (DEBUG_EPHEMERAL) {
6400                            Slog.v(TAG, "DENY instant app installed;"
6401                                    + " pkg: " + packageName);
6402                        }
6403                        return false;
6404                    }
6405                }
6406            }
6407        }
6408        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6409        return true;
6410    }
6411
6412    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6413            Intent origIntent, String resolvedType, String callingPackage,
6414            Bundle verificationBundle, int userId) {
6415        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6416                new InstantAppRequest(responseObj, origIntent, resolvedType,
6417                        callingPackage, userId, verificationBundle));
6418        mHandler.sendMessage(msg);
6419    }
6420
6421    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6422            int flags, List<ResolveInfo> query, int userId) {
6423        if (query != null) {
6424            final int N = query.size();
6425            if (N == 1) {
6426                return query.get(0);
6427            } else if (N > 1) {
6428                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6429                // If there is more than one activity with the same priority,
6430                // then let the user decide between them.
6431                ResolveInfo r0 = query.get(0);
6432                ResolveInfo r1 = query.get(1);
6433                if (DEBUG_INTENT_MATCHING || debug) {
6434                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6435                            + r1.activityInfo.name + "=" + r1.priority);
6436                }
6437                // If the first activity has a higher priority, or a different
6438                // default, then it is always desirable to pick it.
6439                if (r0.priority != r1.priority
6440                        || r0.preferredOrder != r1.preferredOrder
6441                        || r0.isDefault != r1.isDefault) {
6442                    return query.get(0);
6443                }
6444                // If we have saved a preference for a preferred activity for
6445                // this Intent, use that.
6446                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6447                        flags, query, r0.priority, true, false, debug, userId);
6448                if (ri != null) {
6449                    return ri;
6450                }
6451                // If we have an ephemeral app, use it
6452                for (int i = 0; i < N; i++) {
6453                    ri = query.get(i);
6454                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6455                        final String packageName = ri.activityInfo.packageName;
6456                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6457                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6458                        final int status = (int)(packedStatus >> 32);
6459                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6460                            return ri;
6461                        }
6462                    }
6463                }
6464                ri = new ResolveInfo(mResolveInfo);
6465                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6466                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6467                // If all of the options come from the same package, show the application's
6468                // label and icon instead of the generic resolver's.
6469                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6470                // and then throw away the ResolveInfo itself, meaning that the caller loses
6471                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6472                // a fallback for this case; we only set the target package's resources on
6473                // the ResolveInfo, not the ActivityInfo.
6474                final String intentPackage = intent.getPackage();
6475                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6476                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6477                    ri.resolvePackageName = intentPackage;
6478                    if (userNeedsBadging(userId)) {
6479                        ri.noResourceId = true;
6480                    } else {
6481                        ri.icon = appi.icon;
6482                    }
6483                    ri.iconResourceId = appi.icon;
6484                    ri.labelRes = appi.labelRes;
6485                }
6486                ri.activityInfo.applicationInfo = new ApplicationInfo(
6487                        ri.activityInfo.applicationInfo);
6488                if (userId != 0) {
6489                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6490                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6491                }
6492                // Make sure that the resolver is displayable in car mode
6493                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6494                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6495                return ri;
6496            }
6497        }
6498        return null;
6499    }
6500
6501    /**
6502     * Return true if the given list is not empty and all of its contents have
6503     * an activityInfo with the given package name.
6504     */
6505    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6506        if (ArrayUtils.isEmpty(list)) {
6507            return false;
6508        }
6509        for (int i = 0, N = list.size(); i < N; i++) {
6510            final ResolveInfo ri = list.get(i);
6511            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6512            if (ai == null || !packageName.equals(ai.packageName)) {
6513                return false;
6514            }
6515        }
6516        return true;
6517    }
6518
6519    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6520            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6521        final int N = query.size();
6522        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6523                .get(userId);
6524        // Get the list of persistent preferred activities that handle the intent
6525        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6526        List<PersistentPreferredActivity> pprefs = ppir != null
6527                ? ppir.queryIntent(intent, resolvedType,
6528                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6529                        userId)
6530                : null;
6531        if (pprefs != null && pprefs.size() > 0) {
6532            final int M = pprefs.size();
6533            for (int i=0; i<M; i++) {
6534                final PersistentPreferredActivity ppa = pprefs.get(i);
6535                if (DEBUG_PREFERRED || debug) {
6536                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6537                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6538                            + "\n  component=" + ppa.mComponent);
6539                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6540                }
6541                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6542                        flags | MATCH_DISABLED_COMPONENTS, userId);
6543                if (DEBUG_PREFERRED || debug) {
6544                    Slog.v(TAG, "Found persistent preferred activity:");
6545                    if (ai != null) {
6546                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6547                    } else {
6548                        Slog.v(TAG, "  null");
6549                    }
6550                }
6551                if (ai == null) {
6552                    // This previously registered persistent preferred activity
6553                    // component is no longer known. Ignore it and do NOT remove it.
6554                    continue;
6555                }
6556                for (int j=0; j<N; j++) {
6557                    final ResolveInfo ri = query.get(j);
6558                    if (!ri.activityInfo.applicationInfo.packageName
6559                            .equals(ai.applicationInfo.packageName)) {
6560                        continue;
6561                    }
6562                    if (!ri.activityInfo.name.equals(ai.name)) {
6563                        continue;
6564                    }
6565                    //  Found a persistent preference that can handle the intent.
6566                    if (DEBUG_PREFERRED || debug) {
6567                        Slog.v(TAG, "Returning persistent preferred activity: " +
6568                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6569                    }
6570                    return ri;
6571                }
6572            }
6573        }
6574        return null;
6575    }
6576
6577    // TODO: handle preferred activities missing while user has amnesia
6578    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6579            List<ResolveInfo> query, int priority, boolean always,
6580            boolean removeMatches, boolean debug, int userId) {
6581        if (!sUserManager.exists(userId)) return null;
6582        final int callingUid = Binder.getCallingUid();
6583        flags = updateFlagsForResolve(
6584                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6585        intent = updateIntentForResolve(intent);
6586        // writer
6587        synchronized (mPackages) {
6588            // Try to find a matching persistent preferred activity.
6589            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6590                    debug, userId);
6591
6592            // If a persistent preferred activity matched, use it.
6593            if (pri != null) {
6594                return pri;
6595            }
6596
6597            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6598            // Get the list of preferred activities that handle the intent
6599            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6600            List<PreferredActivity> prefs = pir != null
6601                    ? pir.queryIntent(intent, resolvedType,
6602                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6603                            userId)
6604                    : null;
6605            if (prefs != null && prefs.size() > 0) {
6606                boolean changed = false;
6607                try {
6608                    // First figure out how good the original match set is.
6609                    // We will only allow preferred activities that came
6610                    // from the same match quality.
6611                    int match = 0;
6612
6613                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6614
6615                    final int N = query.size();
6616                    for (int j=0; j<N; j++) {
6617                        final ResolveInfo ri = query.get(j);
6618                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6619                                + ": 0x" + Integer.toHexString(match));
6620                        if (ri.match > match) {
6621                            match = ri.match;
6622                        }
6623                    }
6624
6625                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6626                            + Integer.toHexString(match));
6627
6628                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6629                    final int M = prefs.size();
6630                    for (int i=0; i<M; i++) {
6631                        final PreferredActivity pa = prefs.get(i);
6632                        if (DEBUG_PREFERRED || debug) {
6633                            Slog.v(TAG, "Checking PreferredActivity ds="
6634                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6635                                    + "\n  component=" + pa.mPref.mComponent);
6636                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6637                        }
6638                        if (pa.mPref.mMatch != match) {
6639                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6640                                    + Integer.toHexString(pa.mPref.mMatch));
6641                            continue;
6642                        }
6643                        // If it's not an "always" type preferred activity and that's what we're
6644                        // looking for, skip it.
6645                        if (always && !pa.mPref.mAlways) {
6646                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6647                            continue;
6648                        }
6649                        final ActivityInfo ai = getActivityInfo(
6650                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6651                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6652                                userId);
6653                        if (DEBUG_PREFERRED || debug) {
6654                            Slog.v(TAG, "Found preferred activity:");
6655                            if (ai != null) {
6656                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6657                            } else {
6658                                Slog.v(TAG, "  null");
6659                            }
6660                        }
6661                        if (ai == null) {
6662                            // This previously registered preferred activity
6663                            // component is no longer known.  Most likely an update
6664                            // to the app was installed and in the new version this
6665                            // component no longer exists.  Clean it up by removing
6666                            // it from the preferred activities list, and skip it.
6667                            Slog.w(TAG, "Removing dangling preferred activity: "
6668                                    + pa.mPref.mComponent);
6669                            pir.removeFilter(pa);
6670                            changed = true;
6671                            continue;
6672                        }
6673                        for (int j=0; j<N; j++) {
6674                            final ResolveInfo ri = query.get(j);
6675                            if (!ri.activityInfo.applicationInfo.packageName
6676                                    .equals(ai.applicationInfo.packageName)) {
6677                                continue;
6678                            }
6679                            if (!ri.activityInfo.name.equals(ai.name)) {
6680                                continue;
6681                            }
6682
6683                            if (removeMatches) {
6684                                pir.removeFilter(pa);
6685                                changed = true;
6686                                if (DEBUG_PREFERRED) {
6687                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6688                                }
6689                                break;
6690                            }
6691
6692                            // Okay we found a previously set preferred or last chosen app.
6693                            // If the result set is different from when this
6694                            // was created, we need to clear it and re-ask the
6695                            // user their preference, if we're looking for an "always" type entry.
6696                            if (always && !pa.mPref.sameSet(query)) {
6697                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6698                                        + intent + " type " + resolvedType);
6699                                if (DEBUG_PREFERRED) {
6700                                    Slog.v(TAG, "Removing preferred activity since set changed "
6701                                            + pa.mPref.mComponent);
6702                                }
6703                                pir.removeFilter(pa);
6704                                // Re-add the filter as a "last chosen" entry (!always)
6705                                PreferredActivity lastChosen = new PreferredActivity(
6706                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6707                                pir.addFilter(lastChosen);
6708                                changed = true;
6709                                return null;
6710                            }
6711
6712                            // Yay! Either the set matched or we're looking for the last chosen
6713                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6714                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6715                            return ri;
6716                        }
6717                    }
6718                } finally {
6719                    if (changed) {
6720                        if (DEBUG_PREFERRED) {
6721                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6722                        }
6723                        scheduleWritePackageRestrictionsLocked(userId);
6724                    }
6725                }
6726            }
6727        }
6728        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6729        return null;
6730    }
6731
6732    /*
6733     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6734     */
6735    @Override
6736    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6737            int targetUserId) {
6738        mContext.enforceCallingOrSelfPermission(
6739                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6740        List<CrossProfileIntentFilter> matches =
6741                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6742        if (matches != null) {
6743            int size = matches.size();
6744            for (int i = 0; i < size; i++) {
6745                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6746            }
6747        }
6748        if (hasWebURI(intent)) {
6749            // cross-profile app linking works only towards the parent.
6750            final int callingUid = Binder.getCallingUid();
6751            final UserInfo parent = getProfileParent(sourceUserId);
6752            synchronized(mPackages) {
6753                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6754                        false /*includeInstantApps*/);
6755                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6756                        intent, resolvedType, flags, sourceUserId, parent.id);
6757                return xpDomainInfo != null;
6758            }
6759        }
6760        return false;
6761    }
6762
6763    private UserInfo getProfileParent(int userId) {
6764        final long identity = Binder.clearCallingIdentity();
6765        try {
6766            return sUserManager.getProfileParent(userId);
6767        } finally {
6768            Binder.restoreCallingIdentity(identity);
6769        }
6770    }
6771
6772    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6773            String resolvedType, int userId) {
6774        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6775        if (resolver != null) {
6776            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6777        }
6778        return null;
6779    }
6780
6781    @Override
6782    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6783            String resolvedType, int flags, int userId) {
6784        try {
6785            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6786
6787            return new ParceledListSlice<>(
6788                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6789        } finally {
6790            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6791        }
6792    }
6793
6794    /**
6795     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6796     * instant, returns {@code null}.
6797     */
6798    private String getInstantAppPackageName(int callingUid) {
6799        synchronized (mPackages) {
6800            // If the caller is an isolated app use the owner's uid for the lookup.
6801            if (Process.isIsolated(callingUid)) {
6802                callingUid = mIsolatedOwners.get(callingUid);
6803            }
6804            final int appId = UserHandle.getAppId(callingUid);
6805            final Object obj = mSettings.getUserIdLPr(appId);
6806            if (obj instanceof PackageSetting) {
6807                final PackageSetting ps = (PackageSetting) obj;
6808                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6809                return isInstantApp ? ps.pkg.packageName : null;
6810            }
6811        }
6812        return null;
6813    }
6814
6815    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6816            String resolvedType, int flags, int userId) {
6817        return queryIntentActivitiesInternal(
6818                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6819    }
6820
6821    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6822            String resolvedType, int flags, int filterCallingUid, int userId,
6823            boolean resolveForStart) {
6824        if (!sUserManager.exists(userId)) return Collections.emptyList();
6825        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6826        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6827                false /* requireFullPermission */, false /* checkShell */,
6828                "query intent activities");
6829        final String pkgName = intent.getPackage();
6830        ComponentName comp = intent.getComponent();
6831        if (comp == null) {
6832            if (intent.getSelector() != null) {
6833                intent = intent.getSelector();
6834                comp = intent.getComponent();
6835            }
6836        }
6837
6838        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6839                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6840        if (comp != null) {
6841            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6842            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6843            if (ai != null) {
6844                // When specifying an explicit component, we prevent the activity from being
6845                // used when either 1) the calling package is normal and the activity is within
6846                // an ephemeral application or 2) the calling package is ephemeral and the
6847                // activity is not visible to ephemeral applications.
6848                final boolean matchInstantApp =
6849                        (flags & PackageManager.MATCH_INSTANT) != 0;
6850                final boolean matchVisibleToInstantAppOnly =
6851                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6852                final boolean matchExplicitlyVisibleOnly =
6853                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6854                final boolean isCallerInstantApp =
6855                        instantAppPkgName != null;
6856                final boolean isTargetSameInstantApp =
6857                        comp.getPackageName().equals(instantAppPkgName);
6858                final boolean isTargetInstantApp =
6859                        (ai.applicationInfo.privateFlags
6860                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6861                final boolean isTargetVisibleToInstantApp =
6862                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6863                final boolean isTargetExplicitlyVisibleToInstantApp =
6864                        isTargetVisibleToInstantApp
6865                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6866                final boolean isTargetHiddenFromInstantApp =
6867                        !isTargetVisibleToInstantApp
6868                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6869                final boolean blockResolution =
6870                        !isTargetSameInstantApp
6871                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6872                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6873                                        && isTargetHiddenFromInstantApp));
6874                if (!blockResolution) {
6875                    final ResolveInfo ri = new ResolveInfo();
6876                    ri.activityInfo = ai;
6877                    list.add(ri);
6878                }
6879            }
6880            return applyPostResolutionFilter(list, instantAppPkgName);
6881        }
6882
6883        // reader
6884        boolean sortResult = false;
6885        boolean addEphemeral = false;
6886        List<ResolveInfo> result;
6887        final boolean ephemeralDisabled = isEphemeralDisabled();
6888        synchronized (mPackages) {
6889            if (pkgName == null) {
6890                List<CrossProfileIntentFilter> matchingFilters =
6891                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6892                // Check for results that need to skip the current profile.
6893                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6894                        resolvedType, flags, userId);
6895                if (xpResolveInfo != null) {
6896                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6897                    xpResult.add(xpResolveInfo);
6898                    return applyPostResolutionFilter(
6899                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6900                }
6901
6902                // Check for results in the current profile.
6903                result = filterIfNotSystemUser(mActivities.queryIntent(
6904                        intent, resolvedType, flags, userId), userId);
6905                addEphemeral = !ephemeralDisabled
6906                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6907                // Check for cross profile results.
6908                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6909                xpResolveInfo = queryCrossProfileIntents(
6910                        matchingFilters, intent, resolvedType, flags, userId,
6911                        hasNonNegativePriorityResult);
6912                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6913                    boolean isVisibleToUser = filterIfNotSystemUser(
6914                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6915                    if (isVisibleToUser) {
6916                        result.add(xpResolveInfo);
6917                        sortResult = true;
6918                    }
6919                }
6920                if (hasWebURI(intent)) {
6921                    CrossProfileDomainInfo xpDomainInfo = null;
6922                    final UserInfo parent = getProfileParent(userId);
6923                    if (parent != null) {
6924                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6925                                flags, userId, parent.id);
6926                    }
6927                    if (xpDomainInfo != null) {
6928                        if (xpResolveInfo != null) {
6929                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6930                            // in the result.
6931                            result.remove(xpResolveInfo);
6932                        }
6933                        if (result.size() == 0 && !addEphemeral) {
6934                            // No result in current profile, but found candidate in parent user.
6935                            // And we are not going to add emphemeral app, so we can return the
6936                            // result straight away.
6937                            result.add(xpDomainInfo.resolveInfo);
6938                            return applyPostResolutionFilter(result, instantAppPkgName);
6939                        }
6940                    } else if (result.size() <= 1 && !addEphemeral) {
6941                        // No result in parent user and <= 1 result in current profile, and we
6942                        // are not going to add emphemeral app, so we can return the result without
6943                        // further processing.
6944                        return applyPostResolutionFilter(result, instantAppPkgName);
6945                    }
6946                    // We have more than one candidate (combining results from current and parent
6947                    // profile), so we need filtering and sorting.
6948                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6949                            intent, flags, result, xpDomainInfo, userId);
6950                    sortResult = true;
6951                }
6952            } else {
6953                final PackageParser.Package pkg = mPackages.get(pkgName);
6954                result = null;
6955                if (pkg != null) {
6956                    result = filterIfNotSystemUser(
6957                            mActivities.queryIntentForPackage(
6958                                    intent, resolvedType, flags, pkg.activities, userId),
6959                            userId);
6960                }
6961                if (result == null || result.size() == 0) {
6962                    // the caller wants to resolve for a particular package; however, there
6963                    // were no installed results, so, try to find an ephemeral result
6964                    addEphemeral = !ephemeralDisabled
6965                            && isInstantAppAllowed(
6966                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6967                    if (result == null) {
6968                        result = new ArrayList<>();
6969                    }
6970                }
6971            }
6972        }
6973        if (addEphemeral) {
6974            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6975        }
6976        if (sortResult) {
6977            Collections.sort(result, mResolvePrioritySorter);
6978        }
6979        return applyPostResolutionFilter(result, instantAppPkgName);
6980    }
6981
6982    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6983            String resolvedType, int flags, int userId) {
6984        // first, check to see if we've got an instant app already installed
6985        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6986        ResolveInfo localInstantApp = null;
6987        boolean blockResolution = false;
6988        if (!alreadyResolvedLocally) {
6989            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6990                    flags
6991                        | PackageManager.GET_RESOLVED_FILTER
6992                        | PackageManager.MATCH_INSTANT
6993                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6994                    userId);
6995            for (int i = instantApps.size() - 1; i >= 0; --i) {
6996                final ResolveInfo info = instantApps.get(i);
6997                final String packageName = info.activityInfo.packageName;
6998                final PackageSetting ps = mSettings.mPackages.get(packageName);
6999                if (ps.getInstantApp(userId)) {
7000                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7001                    final int status = (int)(packedStatus >> 32);
7002                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7003                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7004                        // there's a local instant application installed, but, the user has
7005                        // chosen to never use it; skip resolution and don't acknowledge
7006                        // an instant application is even available
7007                        if (DEBUG_EPHEMERAL) {
7008                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7009                        }
7010                        blockResolution = true;
7011                        break;
7012                    } else {
7013                        // we have a locally installed instant application; skip resolution
7014                        // but acknowledge there's an instant application available
7015                        if (DEBUG_EPHEMERAL) {
7016                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7017                        }
7018                        localInstantApp = info;
7019                        break;
7020                    }
7021                }
7022            }
7023        }
7024        // no app installed, let's see if one's available
7025        AuxiliaryResolveInfo auxiliaryResponse = null;
7026        if (!blockResolution) {
7027            if (localInstantApp == null) {
7028                // we don't have an instant app locally, resolve externally
7029                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7030                final InstantAppRequest requestObject = new InstantAppRequest(
7031                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7032                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7033                auxiliaryResponse =
7034                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7035                                mContext, mInstantAppResolverConnection, requestObject);
7036                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7037            } else {
7038                // we have an instant application locally, but, we can't admit that since
7039                // callers shouldn't be able to determine prior browsing. create a dummy
7040                // auxiliary response so the downstream code behaves as if there's an
7041                // instant application available externally. when it comes time to start
7042                // the instant application, we'll do the right thing.
7043                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7044                auxiliaryResponse = new AuxiliaryResolveInfo(
7045                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7046            }
7047        }
7048        if (auxiliaryResponse != null) {
7049            if (DEBUG_EPHEMERAL) {
7050                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7051            }
7052            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7053            final PackageSetting ps =
7054                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7055            if (ps != null) {
7056                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7057                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7058                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7059                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7060                // make sure this resolver is the default
7061                ephemeralInstaller.isDefault = true;
7062                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7063                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7064                // add a non-generic filter
7065                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7066                ephemeralInstaller.filter.addDataPath(
7067                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7068                ephemeralInstaller.isInstantAppAvailable = true;
7069                result.add(ephemeralInstaller);
7070            }
7071        }
7072        return result;
7073    }
7074
7075    private static class CrossProfileDomainInfo {
7076        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7077        ResolveInfo resolveInfo;
7078        /* Best domain verification status of the activities found in the other profile */
7079        int bestDomainVerificationStatus;
7080    }
7081
7082    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7083            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7084        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7085                sourceUserId)) {
7086            return null;
7087        }
7088        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7089                resolvedType, flags, parentUserId);
7090
7091        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7092            return null;
7093        }
7094        CrossProfileDomainInfo result = null;
7095        int size = resultTargetUser.size();
7096        for (int i = 0; i < size; i++) {
7097            ResolveInfo riTargetUser = resultTargetUser.get(i);
7098            // Intent filter verification is only for filters that specify a host. So don't return
7099            // those that handle all web uris.
7100            if (riTargetUser.handleAllWebDataURI) {
7101                continue;
7102            }
7103            String packageName = riTargetUser.activityInfo.packageName;
7104            PackageSetting ps = mSettings.mPackages.get(packageName);
7105            if (ps == null) {
7106                continue;
7107            }
7108            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7109            int status = (int)(verificationState >> 32);
7110            if (result == null) {
7111                result = new CrossProfileDomainInfo();
7112                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7113                        sourceUserId, parentUserId);
7114                result.bestDomainVerificationStatus = status;
7115            } else {
7116                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7117                        result.bestDomainVerificationStatus);
7118            }
7119        }
7120        // Don't consider matches with status NEVER across profiles.
7121        if (result != null && result.bestDomainVerificationStatus
7122                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7123            return null;
7124        }
7125        return result;
7126    }
7127
7128    /**
7129     * Verification statuses are ordered from the worse to the best, except for
7130     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7131     */
7132    private int bestDomainVerificationStatus(int status1, int status2) {
7133        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7134            return status2;
7135        }
7136        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7137            return status1;
7138        }
7139        return (int) MathUtils.max(status1, status2);
7140    }
7141
7142    private boolean isUserEnabled(int userId) {
7143        long callingId = Binder.clearCallingIdentity();
7144        try {
7145            UserInfo userInfo = sUserManager.getUserInfo(userId);
7146            return userInfo != null && userInfo.isEnabled();
7147        } finally {
7148            Binder.restoreCallingIdentity(callingId);
7149        }
7150    }
7151
7152    /**
7153     * Filter out activities with systemUserOnly flag set, when current user is not System.
7154     *
7155     * @return filtered list
7156     */
7157    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7158        if (userId == UserHandle.USER_SYSTEM) {
7159            return resolveInfos;
7160        }
7161        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7162            ResolveInfo info = resolveInfos.get(i);
7163            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7164                resolveInfos.remove(i);
7165            }
7166        }
7167        return resolveInfos;
7168    }
7169
7170    /**
7171     * Filters out ephemeral activities.
7172     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7173     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7174     *
7175     * @param resolveInfos The pre-filtered list of resolved activities
7176     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7177     *          is performed.
7178     * @return A filtered list of resolved activities.
7179     */
7180    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7181            String ephemeralPkgName) {
7182        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7183            final ResolveInfo info = resolveInfos.get(i);
7184            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7185            // TODO: When adding on-demand split support for non-instant apps, remove this check
7186            // and always apply post filtering
7187            // allow activities that are defined in the provided package
7188            if (isEphemeralApp) {
7189                if (info.activityInfo.splitName != null
7190                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7191                                info.activityInfo.splitName)) {
7192                    // requested activity is defined in a split that hasn't been installed yet.
7193                    // add the installer to the resolve list
7194                    if (DEBUG_EPHEMERAL) {
7195                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7196                    }
7197                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7198                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7199                            info.activityInfo.packageName, info.activityInfo.splitName,
7200                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7201                    // make sure this resolver is the default
7202                    installerInfo.isDefault = true;
7203                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7204                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7205                    // add a non-generic filter
7206                    installerInfo.filter = new IntentFilter();
7207                    // load resources from the correct package
7208                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7209                    resolveInfos.set(i, installerInfo);
7210                    continue;
7211                }
7212            }
7213            // caller is a full app, don't need to apply any other filtering
7214            if (ephemeralPkgName == null) {
7215                continue;
7216            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7217                // caller is same app; don't need to apply any other filtering
7218                continue;
7219            }
7220            // allow activities that have been explicitly exposed to ephemeral apps
7221            if (!isEphemeralApp
7222                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7223                continue;
7224            }
7225            resolveInfos.remove(i);
7226        }
7227        return resolveInfos;
7228    }
7229
7230    /**
7231     * @param resolveInfos list of resolve infos in descending priority order
7232     * @return if the list contains a resolve info with non-negative priority
7233     */
7234    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7235        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7236    }
7237
7238    private static boolean hasWebURI(Intent intent) {
7239        if (intent.getData() == null) {
7240            return false;
7241        }
7242        final String scheme = intent.getScheme();
7243        if (TextUtils.isEmpty(scheme)) {
7244            return false;
7245        }
7246        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7247    }
7248
7249    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7250            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7251            int userId) {
7252        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7253
7254        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7255            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7256                    candidates.size());
7257        }
7258
7259        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7260        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7261        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7262        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7263        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7264        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7265
7266        synchronized (mPackages) {
7267            final int count = candidates.size();
7268            // First, try to use linked apps. Partition the candidates into four lists:
7269            // one for the final results, one for the "do not use ever", one for "undefined status"
7270            // and finally one for "browser app type".
7271            for (int n=0; n<count; n++) {
7272                ResolveInfo info = candidates.get(n);
7273                String packageName = info.activityInfo.packageName;
7274                PackageSetting ps = mSettings.mPackages.get(packageName);
7275                if (ps != null) {
7276                    // Add to the special match all list (Browser use case)
7277                    if (info.handleAllWebDataURI) {
7278                        matchAllList.add(info);
7279                        continue;
7280                    }
7281                    // Try to get the status from User settings first
7282                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7283                    int status = (int)(packedStatus >> 32);
7284                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7285                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7286                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7287                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7288                                    + " : linkgen=" + linkGeneration);
7289                        }
7290                        // Use link-enabled generation as preferredOrder, i.e.
7291                        // prefer newly-enabled over earlier-enabled.
7292                        info.preferredOrder = linkGeneration;
7293                        alwaysList.add(info);
7294                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7295                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7296                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7297                        }
7298                        neverList.add(info);
7299                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7300                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7301                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7302                        }
7303                        alwaysAskList.add(info);
7304                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7305                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7306                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7307                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7308                        }
7309                        undefinedList.add(info);
7310                    }
7311                }
7312            }
7313
7314            // We'll want to include browser possibilities in a few cases
7315            boolean includeBrowser = false;
7316
7317            // First try to add the "always" resolution(s) for the current user, if any
7318            if (alwaysList.size() > 0) {
7319                result.addAll(alwaysList);
7320            } else {
7321                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7322                result.addAll(undefinedList);
7323                // Maybe add one for the other profile.
7324                if (xpDomainInfo != null && (
7325                        xpDomainInfo.bestDomainVerificationStatus
7326                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7327                    result.add(xpDomainInfo.resolveInfo);
7328                }
7329                includeBrowser = true;
7330            }
7331
7332            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7333            // If there were 'always' entries their preferred order has been set, so we also
7334            // back that off to make the alternatives equivalent
7335            if (alwaysAskList.size() > 0) {
7336                for (ResolveInfo i : result) {
7337                    i.preferredOrder = 0;
7338                }
7339                result.addAll(alwaysAskList);
7340                includeBrowser = true;
7341            }
7342
7343            if (includeBrowser) {
7344                // Also add browsers (all of them or only the default one)
7345                if (DEBUG_DOMAIN_VERIFICATION) {
7346                    Slog.v(TAG, "   ...including browsers in candidate set");
7347                }
7348                if ((matchFlags & MATCH_ALL) != 0) {
7349                    result.addAll(matchAllList);
7350                } else {
7351                    // Browser/generic handling case.  If there's a default browser, go straight
7352                    // to that (but only if there is no other higher-priority match).
7353                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7354                    int maxMatchPrio = 0;
7355                    ResolveInfo defaultBrowserMatch = null;
7356                    final int numCandidates = matchAllList.size();
7357                    for (int n = 0; n < numCandidates; n++) {
7358                        ResolveInfo info = matchAllList.get(n);
7359                        // track the highest overall match priority...
7360                        if (info.priority > maxMatchPrio) {
7361                            maxMatchPrio = info.priority;
7362                        }
7363                        // ...and the highest-priority default browser match
7364                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7365                            if (defaultBrowserMatch == null
7366                                    || (defaultBrowserMatch.priority < info.priority)) {
7367                                if (debug) {
7368                                    Slog.v(TAG, "Considering default browser match " + info);
7369                                }
7370                                defaultBrowserMatch = info;
7371                            }
7372                        }
7373                    }
7374                    if (defaultBrowserMatch != null
7375                            && defaultBrowserMatch.priority >= maxMatchPrio
7376                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7377                    {
7378                        if (debug) {
7379                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7380                        }
7381                        result.add(defaultBrowserMatch);
7382                    } else {
7383                        result.addAll(matchAllList);
7384                    }
7385                }
7386
7387                // If there is nothing selected, add all candidates and remove the ones that the user
7388                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7389                if (result.size() == 0) {
7390                    result.addAll(candidates);
7391                    result.removeAll(neverList);
7392                }
7393            }
7394        }
7395        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7396            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7397                    result.size());
7398            for (ResolveInfo info : result) {
7399                Slog.v(TAG, "  + " + info.activityInfo);
7400            }
7401        }
7402        return result;
7403    }
7404
7405    // Returns a packed value as a long:
7406    //
7407    // high 'int'-sized word: link status: undefined/ask/never/always.
7408    // low 'int'-sized word: relative priority among 'always' results.
7409    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7410        long result = ps.getDomainVerificationStatusForUser(userId);
7411        // if none available, get the master status
7412        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7413            if (ps.getIntentFilterVerificationInfo() != null) {
7414                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7415            }
7416        }
7417        return result;
7418    }
7419
7420    private ResolveInfo querySkipCurrentProfileIntents(
7421            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7422            int flags, int sourceUserId) {
7423        if (matchingFilters != null) {
7424            int size = matchingFilters.size();
7425            for (int i = 0; i < size; i ++) {
7426                CrossProfileIntentFilter filter = matchingFilters.get(i);
7427                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7428                    // Checking if there are activities in the target user that can handle the
7429                    // intent.
7430                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7431                            resolvedType, flags, sourceUserId);
7432                    if (resolveInfo != null) {
7433                        return resolveInfo;
7434                    }
7435                }
7436            }
7437        }
7438        return null;
7439    }
7440
7441    // Return matching ResolveInfo in target user if any.
7442    private ResolveInfo queryCrossProfileIntents(
7443            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7444            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7445        if (matchingFilters != null) {
7446            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7447            // match the same intent. For performance reasons, it is better not to
7448            // run queryIntent twice for the same userId
7449            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7450            int size = matchingFilters.size();
7451            for (int i = 0; i < size; i++) {
7452                CrossProfileIntentFilter filter = matchingFilters.get(i);
7453                int targetUserId = filter.getTargetUserId();
7454                boolean skipCurrentProfile =
7455                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7456                boolean skipCurrentProfileIfNoMatchFound =
7457                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7458                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7459                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7460                    // Checking if there are activities in the target user that can handle the
7461                    // intent.
7462                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7463                            resolvedType, flags, sourceUserId);
7464                    if (resolveInfo != null) return resolveInfo;
7465                    alreadyTriedUserIds.put(targetUserId, true);
7466                }
7467            }
7468        }
7469        return null;
7470    }
7471
7472    /**
7473     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7474     * will forward the intent to the filter's target user.
7475     * Otherwise, returns null.
7476     */
7477    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7478            String resolvedType, int flags, int sourceUserId) {
7479        int targetUserId = filter.getTargetUserId();
7480        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7481                resolvedType, flags, targetUserId);
7482        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7483            // If all the matches in the target profile are suspended, return null.
7484            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7485                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7486                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7487                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7488                            targetUserId);
7489                }
7490            }
7491        }
7492        return null;
7493    }
7494
7495    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7496            int sourceUserId, int targetUserId) {
7497        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7498        long ident = Binder.clearCallingIdentity();
7499        boolean targetIsProfile;
7500        try {
7501            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7502        } finally {
7503            Binder.restoreCallingIdentity(ident);
7504        }
7505        String className;
7506        if (targetIsProfile) {
7507            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7508        } else {
7509            className = FORWARD_INTENT_TO_PARENT;
7510        }
7511        ComponentName forwardingActivityComponentName = new ComponentName(
7512                mAndroidApplication.packageName, className);
7513        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7514                sourceUserId);
7515        if (!targetIsProfile) {
7516            forwardingActivityInfo.showUserIcon = targetUserId;
7517            forwardingResolveInfo.noResourceId = true;
7518        }
7519        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7520        forwardingResolveInfo.priority = 0;
7521        forwardingResolveInfo.preferredOrder = 0;
7522        forwardingResolveInfo.match = 0;
7523        forwardingResolveInfo.isDefault = true;
7524        forwardingResolveInfo.filter = filter;
7525        forwardingResolveInfo.targetUserId = targetUserId;
7526        return forwardingResolveInfo;
7527    }
7528
7529    @Override
7530    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7531            Intent[] specifics, String[] specificTypes, Intent intent,
7532            String resolvedType, int flags, int userId) {
7533        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7534                specificTypes, intent, resolvedType, flags, userId));
7535    }
7536
7537    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7538            Intent[] specifics, String[] specificTypes, Intent intent,
7539            String resolvedType, int flags, int userId) {
7540        if (!sUserManager.exists(userId)) return Collections.emptyList();
7541        final int callingUid = Binder.getCallingUid();
7542        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7543                false /*includeInstantApps*/);
7544        enforceCrossUserPermission(callingUid, userId,
7545                false /*requireFullPermission*/, false /*checkShell*/,
7546                "query intent activity options");
7547        final String resultsAction = intent.getAction();
7548
7549        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7550                | PackageManager.GET_RESOLVED_FILTER, userId);
7551
7552        if (DEBUG_INTENT_MATCHING) {
7553            Log.v(TAG, "Query " + intent + ": " + results);
7554        }
7555
7556        int specificsPos = 0;
7557        int N;
7558
7559        // todo: note that the algorithm used here is O(N^2).  This
7560        // isn't a problem in our current environment, but if we start running
7561        // into situations where we have more than 5 or 10 matches then this
7562        // should probably be changed to something smarter...
7563
7564        // First we go through and resolve each of the specific items
7565        // that were supplied, taking care of removing any corresponding
7566        // duplicate items in the generic resolve list.
7567        if (specifics != null) {
7568            for (int i=0; i<specifics.length; i++) {
7569                final Intent sintent = specifics[i];
7570                if (sintent == null) {
7571                    continue;
7572                }
7573
7574                if (DEBUG_INTENT_MATCHING) {
7575                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7576                }
7577
7578                String action = sintent.getAction();
7579                if (resultsAction != null && resultsAction.equals(action)) {
7580                    // If this action was explicitly requested, then don't
7581                    // remove things that have it.
7582                    action = null;
7583                }
7584
7585                ResolveInfo ri = null;
7586                ActivityInfo ai = null;
7587
7588                ComponentName comp = sintent.getComponent();
7589                if (comp == null) {
7590                    ri = resolveIntent(
7591                        sintent,
7592                        specificTypes != null ? specificTypes[i] : null,
7593                            flags, userId);
7594                    if (ri == null) {
7595                        continue;
7596                    }
7597                    if (ri == mResolveInfo) {
7598                        // ACK!  Must do something better with this.
7599                    }
7600                    ai = ri.activityInfo;
7601                    comp = new ComponentName(ai.applicationInfo.packageName,
7602                            ai.name);
7603                } else {
7604                    ai = getActivityInfo(comp, flags, userId);
7605                    if (ai == null) {
7606                        continue;
7607                    }
7608                }
7609
7610                // Look for any generic query activities that are duplicates
7611                // of this specific one, and remove them from the results.
7612                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7613                N = results.size();
7614                int j;
7615                for (j=specificsPos; j<N; j++) {
7616                    ResolveInfo sri = results.get(j);
7617                    if ((sri.activityInfo.name.equals(comp.getClassName())
7618                            && sri.activityInfo.applicationInfo.packageName.equals(
7619                                    comp.getPackageName()))
7620                        || (action != null && sri.filter.matchAction(action))) {
7621                        results.remove(j);
7622                        if (DEBUG_INTENT_MATCHING) Log.v(
7623                            TAG, "Removing duplicate item from " + j
7624                            + " due to specific " + specificsPos);
7625                        if (ri == null) {
7626                            ri = sri;
7627                        }
7628                        j--;
7629                        N--;
7630                    }
7631                }
7632
7633                // Add this specific item to its proper place.
7634                if (ri == null) {
7635                    ri = new ResolveInfo();
7636                    ri.activityInfo = ai;
7637                }
7638                results.add(specificsPos, ri);
7639                ri.specificIndex = i;
7640                specificsPos++;
7641            }
7642        }
7643
7644        // Now we go through the remaining generic results and remove any
7645        // duplicate actions that are found here.
7646        N = results.size();
7647        for (int i=specificsPos; i<N-1; i++) {
7648            final ResolveInfo rii = results.get(i);
7649            if (rii.filter == null) {
7650                continue;
7651            }
7652
7653            // Iterate over all of the actions of this result's intent
7654            // filter...  typically this should be just one.
7655            final Iterator<String> it = rii.filter.actionsIterator();
7656            if (it == null) {
7657                continue;
7658            }
7659            while (it.hasNext()) {
7660                final String action = it.next();
7661                if (resultsAction != null && resultsAction.equals(action)) {
7662                    // If this action was explicitly requested, then don't
7663                    // remove things that have it.
7664                    continue;
7665                }
7666                for (int j=i+1; j<N; j++) {
7667                    final ResolveInfo rij = results.get(j);
7668                    if (rij.filter != null && rij.filter.hasAction(action)) {
7669                        results.remove(j);
7670                        if (DEBUG_INTENT_MATCHING) Log.v(
7671                            TAG, "Removing duplicate item from " + j
7672                            + " due to action " + action + " at " + i);
7673                        j--;
7674                        N--;
7675                    }
7676                }
7677            }
7678
7679            // If the caller didn't request filter information, drop it now
7680            // so we don't have to marshall/unmarshall it.
7681            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7682                rii.filter = null;
7683            }
7684        }
7685
7686        // Filter out the caller activity if so requested.
7687        if (caller != null) {
7688            N = results.size();
7689            for (int i=0; i<N; i++) {
7690                ActivityInfo ainfo = results.get(i).activityInfo;
7691                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7692                        && caller.getClassName().equals(ainfo.name)) {
7693                    results.remove(i);
7694                    break;
7695                }
7696            }
7697        }
7698
7699        // If the caller didn't request filter information,
7700        // drop them now so we don't have to
7701        // marshall/unmarshall it.
7702        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7703            N = results.size();
7704            for (int i=0; i<N; i++) {
7705                results.get(i).filter = null;
7706            }
7707        }
7708
7709        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7710        return results;
7711    }
7712
7713    @Override
7714    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7715            String resolvedType, int flags, int userId) {
7716        return new ParceledListSlice<>(
7717                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7718    }
7719
7720    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7721            String resolvedType, int flags, int userId) {
7722        if (!sUserManager.exists(userId)) return Collections.emptyList();
7723        final int callingUid = Binder.getCallingUid();
7724        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7725        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7726                false /*includeInstantApps*/);
7727        ComponentName comp = intent.getComponent();
7728        if (comp == null) {
7729            if (intent.getSelector() != null) {
7730                intent = intent.getSelector();
7731                comp = intent.getComponent();
7732            }
7733        }
7734        if (comp != null) {
7735            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7736            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7737            if (ai != null) {
7738                // When specifying an explicit component, we prevent the activity from being
7739                // used when either 1) the calling package is normal and the activity is within
7740                // an instant application or 2) the calling package is ephemeral and the
7741                // activity is not visible to instant applications.
7742                final boolean matchInstantApp =
7743                        (flags & PackageManager.MATCH_INSTANT) != 0;
7744                final boolean matchVisibleToInstantAppOnly =
7745                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7746                final boolean matchExplicitlyVisibleOnly =
7747                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7748                final boolean isCallerInstantApp =
7749                        instantAppPkgName != null;
7750                final boolean isTargetSameInstantApp =
7751                        comp.getPackageName().equals(instantAppPkgName);
7752                final boolean isTargetInstantApp =
7753                        (ai.applicationInfo.privateFlags
7754                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7755                final boolean isTargetVisibleToInstantApp =
7756                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7757                final boolean isTargetExplicitlyVisibleToInstantApp =
7758                        isTargetVisibleToInstantApp
7759                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7760                final boolean isTargetHiddenFromInstantApp =
7761                        !isTargetVisibleToInstantApp
7762                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7763                final boolean blockResolution =
7764                        !isTargetSameInstantApp
7765                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7766                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7767                                        && isTargetHiddenFromInstantApp));
7768                if (!blockResolution) {
7769                    ResolveInfo ri = new ResolveInfo();
7770                    ri.activityInfo = ai;
7771                    list.add(ri);
7772                }
7773            }
7774            return applyPostResolutionFilter(list, instantAppPkgName);
7775        }
7776
7777        // reader
7778        synchronized (mPackages) {
7779            String pkgName = intent.getPackage();
7780            if (pkgName == null) {
7781                final List<ResolveInfo> result =
7782                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7783                return applyPostResolutionFilter(result, instantAppPkgName);
7784            }
7785            final PackageParser.Package pkg = mPackages.get(pkgName);
7786            if (pkg != null) {
7787                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7788                        intent, resolvedType, flags, pkg.receivers, userId);
7789                return applyPostResolutionFilter(result, instantAppPkgName);
7790            }
7791            return Collections.emptyList();
7792        }
7793    }
7794
7795    @Override
7796    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7797        final int callingUid = Binder.getCallingUid();
7798        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7799    }
7800
7801    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7802            int userId, int callingUid) {
7803        if (!sUserManager.exists(userId)) return null;
7804        flags = updateFlagsForResolve(
7805                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7806        List<ResolveInfo> query = queryIntentServicesInternal(
7807                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7808        if (query != null) {
7809            if (query.size() >= 1) {
7810                // If there is more than one service with the same priority,
7811                // just arbitrarily pick the first one.
7812                return query.get(0);
7813            }
7814        }
7815        return null;
7816    }
7817
7818    @Override
7819    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7820            String resolvedType, int flags, int userId) {
7821        final int callingUid = Binder.getCallingUid();
7822        return new ParceledListSlice<>(queryIntentServicesInternal(
7823                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7824    }
7825
7826    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7827            String resolvedType, int flags, int userId, int callingUid,
7828            boolean includeInstantApps) {
7829        if (!sUserManager.exists(userId)) return Collections.emptyList();
7830        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7831        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7832        ComponentName comp = intent.getComponent();
7833        if (comp == null) {
7834            if (intent.getSelector() != null) {
7835                intent = intent.getSelector();
7836                comp = intent.getComponent();
7837            }
7838        }
7839        if (comp != null) {
7840            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7841            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7842            if (si != null) {
7843                // When specifying an explicit component, we prevent the service from being
7844                // used when either 1) the service is in an instant application and the
7845                // caller is not the same instant application or 2) the calling package is
7846                // ephemeral and the activity is not visible to ephemeral applications.
7847                final boolean matchInstantApp =
7848                        (flags & PackageManager.MATCH_INSTANT) != 0;
7849                final boolean matchVisibleToInstantAppOnly =
7850                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7851                final boolean isCallerInstantApp =
7852                        instantAppPkgName != null;
7853                final boolean isTargetSameInstantApp =
7854                        comp.getPackageName().equals(instantAppPkgName);
7855                final boolean isTargetInstantApp =
7856                        (si.applicationInfo.privateFlags
7857                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7858                final boolean isTargetHiddenFromInstantApp =
7859                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7860                final boolean blockResolution =
7861                        !isTargetSameInstantApp
7862                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7863                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7864                                        && isTargetHiddenFromInstantApp));
7865                if (!blockResolution) {
7866                    final ResolveInfo ri = new ResolveInfo();
7867                    ri.serviceInfo = si;
7868                    list.add(ri);
7869                }
7870            }
7871            return list;
7872        }
7873
7874        // reader
7875        synchronized (mPackages) {
7876            String pkgName = intent.getPackage();
7877            if (pkgName == null) {
7878                return applyPostServiceResolutionFilter(
7879                        mServices.queryIntent(intent, resolvedType, flags, userId),
7880                        instantAppPkgName);
7881            }
7882            final PackageParser.Package pkg = mPackages.get(pkgName);
7883            if (pkg != null) {
7884                return applyPostServiceResolutionFilter(
7885                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7886                                userId),
7887                        instantAppPkgName);
7888            }
7889            return Collections.emptyList();
7890        }
7891    }
7892
7893    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7894            String instantAppPkgName) {
7895        // TODO: When adding on-demand split support for non-instant apps, remove this check
7896        // and always apply post filtering
7897        if (instantAppPkgName == null) {
7898            return resolveInfos;
7899        }
7900        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7901            final ResolveInfo info = resolveInfos.get(i);
7902            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7903            // allow services that are defined in the provided package
7904            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7905                if (info.serviceInfo.splitName != null
7906                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7907                                info.serviceInfo.splitName)) {
7908                    // requested service is defined in a split that hasn't been installed yet.
7909                    // add the installer to the resolve list
7910                    if (DEBUG_EPHEMERAL) {
7911                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7912                    }
7913                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7914                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7915                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7916                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7917                    // make sure this resolver is the default
7918                    installerInfo.isDefault = true;
7919                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7920                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7921                    // add a non-generic filter
7922                    installerInfo.filter = new IntentFilter();
7923                    // load resources from the correct package
7924                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7925                    resolveInfos.set(i, installerInfo);
7926                }
7927                continue;
7928            }
7929            // allow services that have been explicitly exposed to ephemeral apps
7930            if (!isEphemeralApp
7931                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7932                continue;
7933            }
7934            resolveInfos.remove(i);
7935        }
7936        return resolveInfos;
7937    }
7938
7939    @Override
7940    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7941            String resolvedType, int flags, int userId) {
7942        return new ParceledListSlice<>(
7943                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7944    }
7945
7946    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7947            Intent intent, String resolvedType, int flags, int userId) {
7948        if (!sUserManager.exists(userId)) return Collections.emptyList();
7949        final int callingUid = Binder.getCallingUid();
7950        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7951        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7952                false /*includeInstantApps*/);
7953        ComponentName comp = intent.getComponent();
7954        if (comp == null) {
7955            if (intent.getSelector() != null) {
7956                intent = intent.getSelector();
7957                comp = intent.getComponent();
7958            }
7959        }
7960        if (comp != null) {
7961            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7962            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7963            if (pi != null) {
7964                // When specifying an explicit component, we prevent the provider from being
7965                // used when either 1) the provider is in an instant application and the
7966                // caller is not the same instant application or 2) the calling package is an
7967                // instant application and the provider is not visible to instant applications.
7968                final boolean matchInstantApp =
7969                        (flags & PackageManager.MATCH_INSTANT) != 0;
7970                final boolean matchVisibleToInstantAppOnly =
7971                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7972                final boolean isCallerInstantApp =
7973                        instantAppPkgName != null;
7974                final boolean isTargetSameInstantApp =
7975                        comp.getPackageName().equals(instantAppPkgName);
7976                final boolean isTargetInstantApp =
7977                        (pi.applicationInfo.privateFlags
7978                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7979                final boolean isTargetHiddenFromInstantApp =
7980                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7981                final boolean blockResolution =
7982                        !isTargetSameInstantApp
7983                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7984                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7985                                        && isTargetHiddenFromInstantApp));
7986                if (!blockResolution) {
7987                    final ResolveInfo ri = new ResolveInfo();
7988                    ri.providerInfo = pi;
7989                    list.add(ri);
7990                }
7991            }
7992            return list;
7993        }
7994
7995        // reader
7996        synchronized (mPackages) {
7997            String pkgName = intent.getPackage();
7998            if (pkgName == null) {
7999                return applyPostContentProviderResolutionFilter(
8000                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8001                        instantAppPkgName);
8002            }
8003            final PackageParser.Package pkg = mPackages.get(pkgName);
8004            if (pkg != null) {
8005                return applyPostContentProviderResolutionFilter(
8006                        mProviders.queryIntentForPackage(
8007                        intent, resolvedType, flags, pkg.providers, userId),
8008                        instantAppPkgName);
8009            }
8010            return Collections.emptyList();
8011        }
8012    }
8013
8014    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8015            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8016        // TODO: When adding on-demand split support for non-instant applications, remove
8017        // this check and always apply post filtering
8018        if (instantAppPkgName == null) {
8019            return resolveInfos;
8020        }
8021        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8022            final ResolveInfo info = resolveInfos.get(i);
8023            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8024            // allow providers that are defined in the provided package
8025            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8026                if (info.providerInfo.splitName != null
8027                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8028                                info.providerInfo.splitName)) {
8029                    // requested provider is defined in a split that hasn't been installed yet.
8030                    // add the installer to the resolve list
8031                    if (DEBUG_EPHEMERAL) {
8032                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8033                    }
8034                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8035                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8036                            info.providerInfo.packageName, info.providerInfo.splitName,
8037                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8038                    // make sure this resolver is the default
8039                    installerInfo.isDefault = true;
8040                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8041                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8042                    // add a non-generic filter
8043                    installerInfo.filter = new IntentFilter();
8044                    // load resources from the correct package
8045                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8046                    resolveInfos.set(i, installerInfo);
8047                }
8048                continue;
8049            }
8050            // allow providers that have been explicitly exposed to instant applications
8051            if (!isEphemeralApp
8052                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8053                continue;
8054            }
8055            resolveInfos.remove(i);
8056        }
8057        return resolveInfos;
8058    }
8059
8060    @Override
8061    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8062        final int callingUid = Binder.getCallingUid();
8063        if (getInstantAppPackageName(callingUid) != null) {
8064            return ParceledListSlice.emptyList();
8065        }
8066        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8067        flags = updateFlagsForPackage(flags, userId, null);
8068        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8069        enforceCrossUserPermission(callingUid, userId,
8070                true /* requireFullPermission */, false /* checkShell */,
8071                "get installed packages");
8072
8073        // writer
8074        synchronized (mPackages) {
8075            ArrayList<PackageInfo> list;
8076            if (listUninstalled) {
8077                list = new ArrayList<>(mSettings.mPackages.size());
8078                for (PackageSetting ps : mSettings.mPackages.values()) {
8079                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8080                        continue;
8081                    }
8082                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8083                        return null;
8084                    }
8085                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8086                    if (pi != null) {
8087                        list.add(pi);
8088                    }
8089                }
8090            } else {
8091                list = new ArrayList<>(mPackages.size());
8092                for (PackageParser.Package p : mPackages.values()) {
8093                    final PackageSetting ps = (PackageSetting) p.mExtras;
8094                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8095                        continue;
8096                    }
8097                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8098                        return null;
8099                    }
8100                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8101                            p.mExtras, flags, userId);
8102                    if (pi != null) {
8103                        list.add(pi);
8104                    }
8105                }
8106            }
8107
8108            return new ParceledListSlice<>(list);
8109        }
8110    }
8111
8112    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8113            String[] permissions, boolean[] tmp, int flags, int userId) {
8114        int numMatch = 0;
8115        final PermissionsState permissionsState = ps.getPermissionsState();
8116        for (int i=0; i<permissions.length; i++) {
8117            final String permission = permissions[i];
8118            if (permissionsState.hasPermission(permission, userId)) {
8119                tmp[i] = true;
8120                numMatch++;
8121            } else {
8122                tmp[i] = false;
8123            }
8124        }
8125        if (numMatch == 0) {
8126            return;
8127        }
8128        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8129
8130        // The above might return null in cases of uninstalled apps or install-state
8131        // skew across users/profiles.
8132        if (pi != null) {
8133            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8134                if (numMatch == permissions.length) {
8135                    pi.requestedPermissions = permissions;
8136                } else {
8137                    pi.requestedPermissions = new String[numMatch];
8138                    numMatch = 0;
8139                    for (int i=0; i<permissions.length; i++) {
8140                        if (tmp[i]) {
8141                            pi.requestedPermissions[numMatch] = permissions[i];
8142                            numMatch++;
8143                        }
8144                    }
8145                }
8146            }
8147            list.add(pi);
8148        }
8149    }
8150
8151    @Override
8152    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8153            String[] permissions, int flags, int userId) {
8154        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8155        flags = updateFlagsForPackage(flags, userId, permissions);
8156        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8157                true /* requireFullPermission */, false /* checkShell */,
8158                "get packages holding permissions");
8159        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8160
8161        // writer
8162        synchronized (mPackages) {
8163            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8164            boolean[] tmpBools = new boolean[permissions.length];
8165            if (listUninstalled) {
8166                for (PackageSetting ps : mSettings.mPackages.values()) {
8167                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8168                            userId);
8169                }
8170            } else {
8171                for (PackageParser.Package pkg : mPackages.values()) {
8172                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8173                    if (ps != null) {
8174                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8175                                userId);
8176                    }
8177                }
8178            }
8179
8180            return new ParceledListSlice<PackageInfo>(list);
8181        }
8182    }
8183
8184    @Override
8185    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8186        final int callingUid = Binder.getCallingUid();
8187        if (getInstantAppPackageName(callingUid) != null) {
8188            return ParceledListSlice.emptyList();
8189        }
8190        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8191        flags = updateFlagsForApplication(flags, userId, null);
8192        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8193
8194        // writer
8195        synchronized (mPackages) {
8196            ArrayList<ApplicationInfo> list;
8197            if (listUninstalled) {
8198                list = new ArrayList<>(mSettings.mPackages.size());
8199                for (PackageSetting ps : mSettings.mPackages.values()) {
8200                    ApplicationInfo ai;
8201                    int effectiveFlags = flags;
8202                    if (ps.isSystem()) {
8203                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8204                    }
8205                    if (ps.pkg != null) {
8206                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8207                            continue;
8208                        }
8209                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8210                            return null;
8211                        }
8212                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8213                                ps.readUserState(userId), userId);
8214                        if (ai != null) {
8215                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8216                        }
8217                    } else {
8218                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8219                        // and already converts to externally visible package name
8220                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8221                                callingUid, effectiveFlags, userId);
8222                    }
8223                    if (ai != null) {
8224                        list.add(ai);
8225                    }
8226                }
8227            } else {
8228                list = new ArrayList<>(mPackages.size());
8229                for (PackageParser.Package p : mPackages.values()) {
8230                    if (p.mExtras != null) {
8231                        PackageSetting ps = (PackageSetting) p.mExtras;
8232                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8233                            continue;
8234                        }
8235                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8236                            return null;
8237                        }
8238                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8239                                ps.readUserState(userId), userId);
8240                        if (ai != null) {
8241                            ai.packageName = resolveExternalPackageNameLPr(p);
8242                            list.add(ai);
8243                        }
8244                    }
8245                }
8246            }
8247
8248            return new ParceledListSlice<>(list);
8249        }
8250    }
8251
8252    @Override
8253    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8254        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8255            return null;
8256        }
8257        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8258                "getEphemeralApplications");
8259        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8260                true /* requireFullPermission */, false /* checkShell */,
8261                "getEphemeralApplications");
8262        synchronized (mPackages) {
8263            List<InstantAppInfo> instantApps = mInstantAppRegistry
8264                    .getInstantAppsLPr(userId);
8265            if (instantApps != null) {
8266                return new ParceledListSlice<>(instantApps);
8267            }
8268        }
8269        return null;
8270    }
8271
8272    @Override
8273    public boolean isInstantApp(String packageName, int userId) {
8274        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8275                true /* requireFullPermission */, false /* checkShell */,
8276                "isInstantApp");
8277        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8278            return false;
8279        }
8280        int callingUid = Binder.getCallingUid();
8281        if (Process.isIsolated(callingUid)) {
8282            callingUid = mIsolatedOwners.get(callingUid);
8283        }
8284
8285        synchronized (mPackages) {
8286            final PackageSetting ps = mSettings.mPackages.get(packageName);
8287            PackageParser.Package pkg = mPackages.get(packageName);
8288            final boolean returnAllowed =
8289                    ps != null
8290                    && (isCallerSameApp(packageName, callingUid)
8291                            || canViewInstantApps(callingUid, userId)
8292                            || mInstantAppRegistry.isInstantAccessGranted(
8293                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8294            if (returnAllowed) {
8295                return ps.getInstantApp(userId);
8296            }
8297        }
8298        return false;
8299    }
8300
8301    @Override
8302    public byte[] getInstantAppCookie(String packageName, int userId) {
8303        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8304            return null;
8305        }
8306
8307        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8308                true /* requireFullPermission */, false /* checkShell */,
8309                "getInstantAppCookie");
8310        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8311            return null;
8312        }
8313        synchronized (mPackages) {
8314            return mInstantAppRegistry.getInstantAppCookieLPw(
8315                    packageName, userId);
8316        }
8317    }
8318
8319    @Override
8320    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8321        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8322            return true;
8323        }
8324
8325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8326                true /* requireFullPermission */, true /* checkShell */,
8327                "setInstantAppCookie");
8328        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8329            return false;
8330        }
8331        synchronized (mPackages) {
8332            return mInstantAppRegistry.setInstantAppCookieLPw(
8333                    packageName, cookie, userId);
8334        }
8335    }
8336
8337    @Override
8338    public Bitmap getInstantAppIcon(String packageName, int userId) {
8339        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8340            return null;
8341        }
8342
8343        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8344                "getInstantAppIcon");
8345
8346        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8347                true /* requireFullPermission */, false /* checkShell */,
8348                "getInstantAppIcon");
8349
8350        synchronized (mPackages) {
8351            return mInstantAppRegistry.getInstantAppIconLPw(
8352                    packageName, userId);
8353        }
8354    }
8355
8356    private boolean isCallerSameApp(String packageName, int uid) {
8357        PackageParser.Package pkg = mPackages.get(packageName);
8358        return pkg != null
8359                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8360    }
8361
8362    @Override
8363    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8364        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8365            return ParceledListSlice.emptyList();
8366        }
8367        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8368    }
8369
8370    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8371        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8372
8373        // reader
8374        synchronized (mPackages) {
8375            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8376            final int userId = UserHandle.getCallingUserId();
8377            while (i.hasNext()) {
8378                final PackageParser.Package p = i.next();
8379                if (p.applicationInfo == null) continue;
8380
8381                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8382                        && !p.applicationInfo.isDirectBootAware();
8383                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8384                        && p.applicationInfo.isDirectBootAware();
8385
8386                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8387                        && (!mSafeMode || isSystemApp(p))
8388                        && (matchesUnaware || matchesAware)) {
8389                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8390                    if (ps != null) {
8391                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8392                                ps.readUserState(userId), userId);
8393                        if (ai != null) {
8394                            finalList.add(ai);
8395                        }
8396                    }
8397                }
8398            }
8399        }
8400
8401        return finalList;
8402    }
8403
8404    @Override
8405    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8406        if (!sUserManager.exists(userId)) return null;
8407        flags = updateFlagsForComponent(flags, userId, name);
8408        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8409        // reader
8410        synchronized (mPackages) {
8411            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8412            PackageSetting ps = provider != null
8413                    ? mSettings.mPackages.get(provider.owner.packageName)
8414                    : null;
8415            if (ps != null) {
8416                final boolean isInstantApp = ps.getInstantApp(userId);
8417                // normal application; filter out instant application provider
8418                if (instantAppPkgName == null && isInstantApp) {
8419                    return null;
8420                }
8421                // instant application; filter out other instant applications
8422                if (instantAppPkgName != null
8423                        && isInstantApp
8424                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8425                    return null;
8426                }
8427                // instant application; filter out non-exposed provider
8428                if (instantAppPkgName != null
8429                        && !isInstantApp
8430                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8431                    return null;
8432                }
8433                // provider not enabled
8434                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8435                    return null;
8436                }
8437                return PackageParser.generateProviderInfo(
8438                        provider, flags, ps.readUserState(userId), userId);
8439            }
8440            return null;
8441        }
8442    }
8443
8444    /**
8445     * @deprecated
8446     */
8447    @Deprecated
8448    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8449        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8450            return;
8451        }
8452        // reader
8453        synchronized (mPackages) {
8454            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8455                    .entrySet().iterator();
8456            final int userId = UserHandle.getCallingUserId();
8457            while (i.hasNext()) {
8458                Map.Entry<String, PackageParser.Provider> entry = i.next();
8459                PackageParser.Provider p = entry.getValue();
8460                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8461
8462                if (ps != null && p.syncable
8463                        && (!mSafeMode || (p.info.applicationInfo.flags
8464                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8465                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8466                            ps.readUserState(userId), userId);
8467                    if (info != null) {
8468                        outNames.add(entry.getKey());
8469                        outInfo.add(info);
8470                    }
8471                }
8472            }
8473        }
8474    }
8475
8476    @Override
8477    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8478            int uid, int flags, String metaDataKey) {
8479        final int callingUid = Binder.getCallingUid();
8480        final int userId = processName != null ? UserHandle.getUserId(uid)
8481                : UserHandle.getCallingUserId();
8482        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8483        flags = updateFlagsForComponent(flags, userId, processName);
8484        ArrayList<ProviderInfo> finalList = null;
8485        // reader
8486        synchronized (mPackages) {
8487            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8488            while (i.hasNext()) {
8489                final PackageParser.Provider p = i.next();
8490                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8491                if (ps != null && p.info.authority != null
8492                        && (processName == null
8493                                || (p.info.processName.equals(processName)
8494                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8495                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8496
8497                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8498                    // parameter.
8499                    if (metaDataKey != null
8500                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8501                        continue;
8502                    }
8503                    final ComponentName component =
8504                            new ComponentName(p.info.packageName, p.info.name);
8505                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8506                        continue;
8507                    }
8508                    if (finalList == null) {
8509                        finalList = new ArrayList<ProviderInfo>(3);
8510                    }
8511                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8512                            ps.readUserState(userId), userId);
8513                    if (info != null) {
8514                        finalList.add(info);
8515                    }
8516                }
8517            }
8518        }
8519
8520        if (finalList != null) {
8521            Collections.sort(finalList, mProviderInitOrderSorter);
8522            return new ParceledListSlice<ProviderInfo>(finalList);
8523        }
8524
8525        return ParceledListSlice.emptyList();
8526    }
8527
8528    @Override
8529    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8530        // reader
8531        synchronized (mPackages) {
8532            final int callingUid = Binder.getCallingUid();
8533            final int callingUserId = UserHandle.getUserId(callingUid);
8534            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8535            if (ps == null) return null;
8536            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8537                return null;
8538            }
8539            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8540            return PackageParser.generateInstrumentationInfo(i, flags);
8541        }
8542    }
8543
8544    @Override
8545    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8546            String targetPackage, int flags) {
8547        final int callingUid = Binder.getCallingUid();
8548        final int callingUserId = UserHandle.getUserId(callingUid);
8549        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8550        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8551            return ParceledListSlice.emptyList();
8552        }
8553        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8554    }
8555
8556    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8557            int flags) {
8558        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8559
8560        // reader
8561        synchronized (mPackages) {
8562            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8563            while (i.hasNext()) {
8564                final PackageParser.Instrumentation p = i.next();
8565                if (targetPackage == null
8566                        || targetPackage.equals(p.info.targetPackage)) {
8567                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8568                            flags);
8569                    if (ii != null) {
8570                        finalList.add(ii);
8571                    }
8572                }
8573            }
8574        }
8575
8576        return finalList;
8577    }
8578
8579    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8580        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8581        try {
8582            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8583        } finally {
8584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8585        }
8586    }
8587
8588    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8589        final File[] files = dir.listFiles();
8590        if (ArrayUtils.isEmpty(files)) {
8591            Log.d(TAG, "No files in app dir " + dir);
8592            return;
8593        }
8594
8595        if (DEBUG_PACKAGE_SCANNING) {
8596            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8597                    + " flags=0x" + Integer.toHexString(parseFlags));
8598        }
8599        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8600                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8601                mParallelPackageParserCallback);
8602
8603        // Submit files for parsing in parallel
8604        int fileCount = 0;
8605        for (File file : files) {
8606            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8607                    && !PackageInstallerService.isStageName(file.getName());
8608            if (!isPackage) {
8609                // Ignore entries which are not packages
8610                continue;
8611            }
8612            parallelPackageParser.submit(file, parseFlags);
8613            fileCount++;
8614        }
8615
8616        // Process results one by one
8617        for (; fileCount > 0; fileCount--) {
8618            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8619            Throwable throwable = parseResult.throwable;
8620            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8621
8622            if (throwable == null) {
8623                // Static shared libraries have synthetic package names
8624                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8625                    renameStaticSharedLibraryPackage(parseResult.pkg);
8626                }
8627                try {
8628                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8629                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8630                                currentTime, null);
8631                    }
8632                } catch (PackageManagerException e) {
8633                    errorCode = e.error;
8634                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8635                }
8636            } else if (throwable instanceof PackageParser.PackageParserException) {
8637                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8638                        throwable;
8639                errorCode = e.error;
8640                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8641            } else {
8642                throw new IllegalStateException("Unexpected exception occurred while parsing "
8643                        + parseResult.scanFile, throwable);
8644            }
8645
8646            // Delete invalid userdata apps
8647            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8648                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8649                logCriticalInfo(Log.WARN,
8650                        "Deleting invalid package at " + parseResult.scanFile);
8651                removeCodePathLI(parseResult.scanFile);
8652            }
8653        }
8654        parallelPackageParser.close();
8655    }
8656
8657    private static File getSettingsProblemFile() {
8658        File dataDir = Environment.getDataDirectory();
8659        File systemDir = new File(dataDir, "system");
8660        File fname = new File(systemDir, "uiderrors.txt");
8661        return fname;
8662    }
8663
8664    static void reportSettingsProblem(int priority, String msg) {
8665        logCriticalInfo(priority, msg);
8666    }
8667
8668    public static void logCriticalInfo(int priority, String msg) {
8669        Slog.println(priority, TAG, msg);
8670        EventLogTags.writePmCriticalInfo(msg);
8671        try {
8672            File fname = getSettingsProblemFile();
8673            FileOutputStream out = new FileOutputStream(fname, true);
8674            PrintWriter pw = new FastPrintWriter(out);
8675            SimpleDateFormat formatter = new SimpleDateFormat();
8676            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8677            pw.println(dateString + ": " + msg);
8678            pw.close();
8679            FileUtils.setPermissions(
8680                    fname.toString(),
8681                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8682                    -1, -1);
8683        } catch (java.io.IOException e) {
8684        }
8685    }
8686
8687    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8688        if (srcFile.isDirectory()) {
8689            final File baseFile = new File(pkg.baseCodePath);
8690            long maxModifiedTime = baseFile.lastModified();
8691            if (pkg.splitCodePaths != null) {
8692                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8693                    final File splitFile = new File(pkg.splitCodePaths[i]);
8694                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8695                }
8696            }
8697            return maxModifiedTime;
8698        }
8699        return srcFile.lastModified();
8700    }
8701
8702    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8703            final int policyFlags) throws PackageManagerException {
8704        // When upgrading from pre-N MR1, verify the package time stamp using the package
8705        // directory and not the APK file.
8706        final long lastModifiedTime = mIsPreNMR1Upgrade
8707                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8708        if (ps != null
8709                && ps.codePath.equals(srcFile)
8710                && ps.timeStamp == lastModifiedTime
8711                && !isCompatSignatureUpdateNeeded(pkg)
8712                && !isRecoverSignatureUpdateNeeded(pkg)) {
8713            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8714            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8715            ArraySet<PublicKey> signingKs;
8716            synchronized (mPackages) {
8717                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8718            }
8719            if (ps.signatures.mSignatures != null
8720                    && ps.signatures.mSignatures.length != 0
8721                    && signingKs != null) {
8722                // Optimization: reuse the existing cached certificates
8723                // if the package appears to be unchanged.
8724                pkg.mSignatures = ps.signatures.mSignatures;
8725                pkg.mSigningKeys = signingKs;
8726                return;
8727            }
8728
8729            Slog.w(TAG, "PackageSetting for " + ps.name
8730                    + " is missing signatures.  Collecting certs again to recover them.");
8731        } else {
8732            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8733        }
8734
8735        try {
8736            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8737            PackageParser.collectCertificates(pkg, policyFlags);
8738        } catch (PackageParserException e) {
8739            throw PackageManagerException.from(e);
8740        } finally {
8741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8742        }
8743    }
8744
8745    /**
8746     *  Traces a package scan.
8747     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8748     */
8749    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8750            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8751        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8752        try {
8753            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8754        } finally {
8755            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8756        }
8757    }
8758
8759    /**
8760     *  Scans a package and returns the newly parsed package.
8761     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8762     */
8763    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8764            long currentTime, UserHandle user) throws PackageManagerException {
8765        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8766        PackageParser pp = new PackageParser();
8767        pp.setSeparateProcesses(mSeparateProcesses);
8768        pp.setOnlyCoreApps(mOnlyCore);
8769        pp.setDisplayMetrics(mMetrics);
8770        pp.setCallback(mPackageParserCallback);
8771
8772        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8773            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8774        }
8775
8776        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8777        final PackageParser.Package pkg;
8778        try {
8779            pkg = pp.parsePackage(scanFile, parseFlags);
8780        } catch (PackageParserException e) {
8781            throw PackageManagerException.from(e);
8782        } finally {
8783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8784        }
8785
8786        // Static shared libraries have synthetic package names
8787        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8788            renameStaticSharedLibraryPackage(pkg);
8789        }
8790
8791        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8792    }
8793
8794    /**
8795     *  Scans a package and returns the newly parsed package.
8796     *  @throws PackageManagerException on a parse error.
8797     */
8798    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8799            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8800            throws PackageManagerException {
8801        // If the package has children and this is the first dive in the function
8802        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8803        // packages (parent and children) would be successfully scanned before the
8804        // actual scan since scanning mutates internal state and we want to atomically
8805        // install the package and its children.
8806        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8807            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8808                scanFlags |= SCAN_CHECK_ONLY;
8809            }
8810        } else {
8811            scanFlags &= ~SCAN_CHECK_ONLY;
8812        }
8813
8814        // Scan the parent
8815        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8816                scanFlags, currentTime, user);
8817
8818        // Scan the children
8819        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8820        for (int i = 0; i < childCount; i++) {
8821            PackageParser.Package childPackage = pkg.childPackages.get(i);
8822            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8823                    currentTime, user);
8824        }
8825
8826
8827        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8828            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8829        }
8830
8831        return scannedPkg;
8832    }
8833
8834    /**
8835     *  Scans a package and returns the newly parsed package.
8836     *  @throws PackageManagerException on a parse error.
8837     */
8838    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8839            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8840            throws PackageManagerException {
8841        PackageSetting ps = null;
8842        PackageSetting updatedPkg;
8843        // reader
8844        synchronized (mPackages) {
8845            // Look to see if we already know about this package.
8846            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8847            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8848                // This package has been renamed to its original name.  Let's
8849                // use that.
8850                ps = mSettings.getPackageLPr(oldName);
8851            }
8852            // If there was no original package, see one for the real package name.
8853            if (ps == null) {
8854                ps = mSettings.getPackageLPr(pkg.packageName);
8855            }
8856            // Check to see if this package could be hiding/updating a system
8857            // package.  Must look for it either under the original or real
8858            // package name depending on our state.
8859            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8860            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8861
8862            // If this is a package we don't know about on the system partition, we
8863            // may need to remove disabled child packages on the system partition
8864            // or may need to not add child packages if the parent apk is updated
8865            // on the data partition and no longer defines this child package.
8866            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8867                // If this is a parent package for an updated system app and this system
8868                // app got an OTA update which no longer defines some of the child packages
8869                // we have to prune them from the disabled system packages.
8870                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8871                if (disabledPs != null) {
8872                    final int scannedChildCount = (pkg.childPackages != null)
8873                            ? pkg.childPackages.size() : 0;
8874                    final int disabledChildCount = disabledPs.childPackageNames != null
8875                            ? disabledPs.childPackageNames.size() : 0;
8876                    for (int i = 0; i < disabledChildCount; i++) {
8877                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8878                        boolean disabledPackageAvailable = false;
8879                        for (int j = 0; j < scannedChildCount; j++) {
8880                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8881                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8882                                disabledPackageAvailable = true;
8883                                break;
8884                            }
8885                         }
8886                         if (!disabledPackageAvailable) {
8887                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8888                         }
8889                    }
8890                }
8891            }
8892        }
8893
8894        boolean updatedPkgBetter = false;
8895        // First check if this is a system package that may involve an update
8896        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8897            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8898            // it needs to drop FLAG_PRIVILEGED.
8899            if (locationIsPrivileged(scanFile)) {
8900                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8901            } else {
8902                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8903            }
8904
8905            if (ps != null && !ps.codePath.equals(scanFile)) {
8906                // The path has changed from what was last scanned...  check the
8907                // version of the new path against what we have stored to determine
8908                // what to do.
8909                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8910                if (pkg.mVersionCode <= ps.versionCode) {
8911                    // The system package has been updated and the code path does not match
8912                    // Ignore entry. Skip it.
8913                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8914                            + " ignored: updated version " + ps.versionCode
8915                            + " better than this " + pkg.mVersionCode);
8916                    if (!updatedPkg.codePath.equals(scanFile)) {
8917                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8918                                + ps.name + " changing from " + updatedPkg.codePathString
8919                                + " to " + scanFile);
8920                        updatedPkg.codePath = scanFile;
8921                        updatedPkg.codePathString = scanFile.toString();
8922                        updatedPkg.resourcePath = scanFile;
8923                        updatedPkg.resourcePathString = scanFile.toString();
8924                    }
8925                    updatedPkg.pkg = pkg;
8926                    updatedPkg.versionCode = pkg.mVersionCode;
8927
8928                    // Update the disabled system child packages to point to the package too.
8929                    final int childCount = updatedPkg.childPackageNames != null
8930                            ? updatedPkg.childPackageNames.size() : 0;
8931                    for (int i = 0; i < childCount; i++) {
8932                        String childPackageName = updatedPkg.childPackageNames.get(i);
8933                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8934                                childPackageName);
8935                        if (updatedChildPkg != null) {
8936                            updatedChildPkg.pkg = pkg;
8937                            updatedChildPkg.versionCode = pkg.mVersionCode;
8938                        }
8939                    }
8940
8941                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8942                            + scanFile + " ignored: updated version " + ps.versionCode
8943                            + " better than this " + pkg.mVersionCode);
8944                } else {
8945                    // The current app on the system partition is better than
8946                    // what we have updated to on the data partition; switch
8947                    // back to the system partition version.
8948                    // At this point, its safely assumed that package installation for
8949                    // apps in system partition will go through. If not there won't be a working
8950                    // version of the app
8951                    // writer
8952                    synchronized (mPackages) {
8953                        // Just remove the loaded entries from package lists.
8954                        mPackages.remove(ps.name);
8955                    }
8956
8957                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8958                            + " reverting from " + ps.codePathString
8959                            + ": new version " + pkg.mVersionCode
8960                            + " better than installed " + ps.versionCode);
8961
8962                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8963                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8964                    synchronized (mInstallLock) {
8965                        args.cleanUpResourcesLI();
8966                    }
8967                    synchronized (mPackages) {
8968                        mSettings.enableSystemPackageLPw(ps.name);
8969                    }
8970                    updatedPkgBetter = true;
8971                }
8972            }
8973        }
8974
8975        if (updatedPkg != null) {
8976            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8977            // initially
8978            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8979
8980            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8981            // flag set initially
8982            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8983                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8984            }
8985        }
8986
8987        // Verify certificates against what was last scanned
8988        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8989
8990        /*
8991         * A new system app appeared, but we already had a non-system one of the
8992         * same name installed earlier.
8993         */
8994        boolean shouldHideSystemApp = false;
8995        if (updatedPkg == null && ps != null
8996                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8997            /*
8998             * Check to make sure the signatures match first. If they don't,
8999             * wipe the installed application and its data.
9000             */
9001            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9002                    != PackageManager.SIGNATURE_MATCH) {
9003                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9004                        + " signatures don't match existing userdata copy; removing");
9005                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9006                        "scanPackageInternalLI")) {
9007                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9008                }
9009                ps = null;
9010            } else {
9011                /*
9012                 * If the newly-added system app is an older version than the
9013                 * already installed version, hide it. It will be scanned later
9014                 * and re-added like an update.
9015                 */
9016                if (pkg.mVersionCode <= ps.versionCode) {
9017                    shouldHideSystemApp = true;
9018                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9019                            + " but new version " + pkg.mVersionCode + " better than installed "
9020                            + ps.versionCode + "; hiding system");
9021                } else {
9022                    /*
9023                     * The newly found system app is a newer version that the
9024                     * one previously installed. Simply remove the
9025                     * already-installed application and replace it with our own
9026                     * while keeping the application data.
9027                     */
9028                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9029                            + " reverting from " + ps.codePathString + ": new version "
9030                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9031                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9032                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9033                    synchronized (mInstallLock) {
9034                        args.cleanUpResourcesLI();
9035                    }
9036                }
9037            }
9038        }
9039
9040        // The apk is forward locked (not public) if its code and resources
9041        // are kept in different files. (except for app in either system or
9042        // vendor path).
9043        // TODO grab this value from PackageSettings
9044        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9045            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9046                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9047            }
9048        }
9049
9050        // TODO: extend to support forward-locked splits
9051        String resourcePath = null;
9052        String baseResourcePath = null;
9053        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9054            if (ps != null && ps.resourcePathString != null) {
9055                resourcePath = ps.resourcePathString;
9056                baseResourcePath = ps.resourcePathString;
9057            } else {
9058                // Should not happen at all. Just log an error.
9059                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9060            }
9061        } else {
9062            resourcePath = pkg.codePath;
9063            baseResourcePath = pkg.baseCodePath;
9064        }
9065
9066        // Set application objects path explicitly.
9067        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9068        pkg.setApplicationInfoCodePath(pkg.codePath);
9069        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9070        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9071        pkg.setApplicationInfoResourcePath(resourcePath);
9072        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9073        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9074
9075        final int userId = ((user == null) ? 0 : user.getIdentifier());
9076        if (ps != null && ps.getInstantApp(userId)) {
9077            scanFlags |= SCAN_AS_INSTANT_APP;
9078        }
9079
9080        // Note that we invoke the following method only if we are about to unpack an application
9081        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9082                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9083
9084        /*
9085         * If the system app should be overridden by a previously installed
9086         * data, hide the system app now and let the /data/app scan pick it up
9087         * again.
9088         */
9089        if (shouldHideSystemApp) {
9090            synchronized (mPackages) {
9091                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9092            }
9093        }
9094
9095        return scannedPkg;
9096    }
9097
9098    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9099        // Derive the new package synthetic package name
9100        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9101                + pkg.staticSharedLibVersion);
9102    }
9103
9104    private static String fixProcessName(String defProcessName,
9105            String processName) {
9106        if (processName == null) {
9107            return defProcessName;
9108        }
9109        return processName;
9110    }
9111
9112    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9113            throws PackageManagerException {
9114        if (pkgSetting.signatures.mSignatures != null) {
9115            // Already existing package. Make sure signatures match
9116            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9117                    == PackageManager.SIGNATURE_MATCH;
9118            if (!match) {
9119                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9120                        == PackageManager.SIGNATURE_MATCH;
9121            }
9122            if (!match) {
9123                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9124                        == PackageManager.SIGNATURE_MATCH;
9125            }
9126            if (!match) {
9127                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9128                        + pkg.packageName + " signatures do not match the "
9129                        + "previously installed version; ignoring!");
9130            }
9131        }
9132
9133        // Check for shared user signatures
9134        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9135            // Already existing package. Make sure signatures match
9136            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9137                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9138            if (!match) {
9139                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9140                        == PackageManager.SIGNATURE_MATCH;
9141            }
9142            if (!match) {
9143                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9144                        == PackageManager.SIGNATURE_MATCH;
9145            }
9146            if (!match) {
9147                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9148                        "Package " + pkg.packageName
9149                        + " has no signatures that match those in shared user "
9150                        + pkgSetting.sharedUser.name + "; ignoring!");
9151            }
9152        }
9153    }
9154
9155    /**
9156     * Enforces that only the system UID or root's UID can call a method exposed
9157     * via Binder.
9158     *
9159     * @param message used as message if SecurityException is thrown
9160     * @throws SecurityException if the caller is not system or root
9161     */
9162    private static final void enforceSystemOrRoot(String message) {
9163        final int uid = Binder.getCallingUid();
9164        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9165            throw new SecurityException(message);
9166        }
9167    }
9168
9169    @Override
9170    public void performFstrimIfNeeded() {
9171        enforceSystemOrRoot("Only the system can request fstrim");
9172
9173        // Before everything else, see whether we need to fstrim.
9174        try {
9175            IStorageManager sm = PackageHelper.getStorageManager();
9176            if (sm != null) {
9177                boolean doTrim = false;
9178                final long interval = android.provider.Settings.Global.getLong(
9179                        mContext.getContentResolver(),
9180                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9181                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9182                if (interval > 0) {
9183                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9184                    if (timeSinceLast > interval) {
9185                        doTrim = true;
9186                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9187                                + "; running immediately");
9188                    }
9189                }
9190                if (doTrim) {
9191                    final boolean dexOptDialogShown;
9192                    synchronized (mPackages) {
9193                        dexOptDialogShown = mDexOptDialogShown;
9194                    }
9195                    if (!isFirstBoot() && dexOptDialogShown) {
9196                        try {
9197                            ActivityManager.getService().showBootMessage(
9198                                    mContext.getResources().getString(
9199                                            R.string.android_upgrading_fstrim), true);
9200                        } catch (RemoteException e) {
9201                        }
9202                    }
9203                    sm.runMaintenance();
9204                }
9205            } else {
9206                Slog.e(TAG, "storageManager service unavailable!");
9207            }
9208        } catch (RemoteException e) {
9209            // Can't happen; StorageManagerService is local
9210        }
9211    }
9212
9213    @Override
9214    public void updatePackagesIfNeeded() {
9215        enforceSystemOrRoot("Only the system can request package update");
9216
9217        // We need to re-extract after an OTA.
9218        boolean causeUpgrade = isUpgrade();
9219
9220        // First boot or factory reset.
9221        // Note: we also handle devices that are upgrading to N right now as if it is their
9222        //       first boot, as they do not have profile data.
9223        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9224
9225        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9226        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9227
9228        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9229            return;
9230        }
9231
9232        List<PackageParser.Package> pkgs;
9233        synchronized (mPackages) {
9234            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9235        }
9236
9237        final long startTime = System.nanoTime();
9238        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9239                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9240                    false /* bootComplete */);
9241
9242        final int elapsedTimeSeconds =
9243                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9244
9245        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9246        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9247        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9248        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9249        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9250    }
9251
9252    /**
9253     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9254     * containing statistics about the invocation. The array consists of three elements,
9255     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9256     * and {@code numberOfPackagesFailed}.
9257     */
9258    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9259            String compilerFilter, boolean bootComplete) {
9260
9261        int numberOfPackagesVisited = 0;
9262        int numberOfPackagesOptimized = 0;
9263        int numberOfPackagesSkipped = 0;
9264        int numberOfPackagesFailed = 0;
9265        final int numberOfPackagesToDexopt = pkgs.size();
9266
9267        for (PackageParser.Package pkg : pkgs) {
9268            numberOfPackagesVisited++;
9269
9270            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9271                if (DEBUG_DEXOPT) {
9272                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9273                }
9274                numberOfPackagesSkipped++;
9275                continue;
9276            }
9277
9278            if (DEBUG_DEXOPT) {
9279                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9280                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9281            }
9282
9283            if (showDialog) {
9284                try {
9285                    ActivityManager.getService().showBootMessage(
9286                            mContext.getResources().getString(R.string.android_upgrading_apk,
9287                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9288                } catch (RemoteException e) {
9289                }
9290                synchronized (mPackages) {
9291                    mDexOptDialogShown = true;
9292                }
9293            }
9294
9295            // If the OTA updates a system app which was previously preopted to a non-preopted state
9296            // the app might end up being verified at runtime. That's because by default the apps
9297            // are verify-profile but for preopted apps there's no profile.
9298            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9299            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9300            // filter (by default 'quicken').
9301            // Note that at this stage unused apps are already filtered.
9302            if (isSystemApp(pkg) &&
9303                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9304                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9305                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9306            }
9307
9308            // checkProfiles is false to avoid merging profiles during boot which
9309            // might interfere with background compilation (b/28612421).
9310            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9311            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9312            // trade-off worth doing to save boot time work.
9313            int dexOptStatus = performDexOptTraced(pkg.packageName,
9314                    false /* checkProfiles */,
9315                    compilerFilter,
9316                    false /* force */,
9317                    bootComplete);
9318            switch (dexOptStatus) {
9319                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9320                    numberOfPackagesOptimized++;
9321                    break;
9322                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9323                    numberOfPackagesSkipped++;
9324                    break;
9325                case PackageDexOptimizer.DEX_OPT_FAILED:
9326                    numberOfPackagesFailed++;
9327                    break;
9328                default:
9329                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9330                    break;
9331            }
9332        }
9333
9334        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9335                numberOfPackagesFailed };
9336    }
9337
9338    @Override
9339    public void notifyPackageUse(String packageName, int reason) {
9340        synchronized (mPackages) {
9341            final int callingUid = Binder.getCallingUid();
9342            final int callingUserId = UserHandle.getUserId(callingUid);
9343            if (getInstantAppPackageName(callingUid) != null) {
9344                if (!isCallerSameApp(packageName, callingUid)) {
9345                    return;
9346                }
9347            } else {
9348                if (isInstantApp(packageName, callingUserId)) {
9349                    return;
9350                }
9351            }
9352            final PackageParser.Package p = mPackages.get(packageName);
9353            if (p == null) {
9354                return;
9355            }
9356            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9357        }
9358    }
9359
9360    @Override
9361    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9362        int userId = UserHandle.getCallingUserId();
9363        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9364        if (ai == null) {
9365            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9366                + loadingPackageName + ", user=" + userId);
9367            return;
9368        }
9369        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9370    }
9371
9372    @Override
9373    public boolean performDexOpt(String packageName,
9374            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9375        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9376            return false;
9377        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9378            return false;
9379        }
9380        int dexoptStatus = performDexOptWithStatus(
9381              packageName, checkProfiles, compileReason, force, bootComplete);
9382        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9383    }
9384
9385    /**
9386     * Perform dexopt on the given package and return one of following result:
9387     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9388     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9389     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9390     */
9391    /* package */ int performDexOptWithStatus(String packageName,
9392            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9393        return performDexOptTraced(packageName, checkProfiles,
9394                getCompilerFilterForReason(compileReason), force, bootComplete);
9395    }
9396
9397    @Override
9398    public boolean performDexOptMode(String packageName,
9399            boolean checkProfiles, String targetCompilerFilter, boolean force,
9400            boolean bootComplete) {
9401        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9402            return false;
9403        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9404            return false;
9405        }
9406        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9407                targetCompilerFilter, force, bootComplete);
9408        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9409    }
9410
9411    private int performDexOptTraced(String packageName,
9412                boolean checkProfiles, String targetCompilerFilter, boolean force,
9413                boolean bootComplete) {
9414        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9415        try {
9416            return performDexOptInternal(packageName, checkProfiles,
9417                    targetCompilerFilter, force, bootComplete);
9418        } finally {
9419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9420        }
9421    }
9422
9423    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9424    // if the package can now be considered up to date for the given filter.
9425    private int performDexOptInternal(String packageName,
9426                boolean checkProfiles, String targetCompilerFilter, boolean force,
9427                boolean bootComplete) {
9428        PackageParser.Package p;
9429        synchronized (mPackages) {
9430            p = mPackages.get(packageName);
9431            if (p == null) {
9432                // Package could not be found. Report failure.
9433                return PackageDexOptimizer.DEX_OPT_FAILED;
9434            }
9435            mPackageUsage.maybeWriteAsync(mPackages);
9436            mCompilerStats.maybeWriteAsync();
9437        }
9438        long callingId = Binder.clearCallingIdentity();
9439        try {
9440            synchronized (mInstallLock) {
9441                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9442                        targetCompilerFilter, force, bootComplete);
9443            }
9444        } finally {
9445            Binder.restoreCallingIdentity(callingId);
9446        }
9447    }
9448
9449    public ArraySet<String> getOptimizablePackages() {
9450        ArraySet<String> pkgs = new ArraySet<String>();
9451        synchronized (mPackages) {
9452            for (PackageParser.Package p : mPackages.values()) {
9453                if (PackageDexOptimizer.canOptimizePackage(p)) {
9454                    pkgs.add(p.packageName);
9455                }
9456            }
9457        }
9458        return pkgs;
9459    }
9460
9461    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9462            boolean checkProfiles, String targetCompilerFilter,
9463            boolean force, boolean bootComplete) {
9464        // Select the dex optimizer based on the force parameter.
9465        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9466        //       allocate an object here.
9467        PackageDexOptimizer pdo = force
9468                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9469                : mPackageDexOptimizer;
9470
9471        // Dexopt all dependencies first. Note: we ignore the return value and march on
9472        // on errors.
9473        // Note that we are going to call performDexOpt on those libraries as many times as
9474        // they are referenced in packages. When we do a batch of performDexOpt (for example
9475        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9476        // and the first package that uses the library will dexopt it. The
9477        // others will see that the compiled code for the library is up to date.
9478        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9479        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9480        if (!deps.isEmpty()) {
9481            for (PackageParser.Package depPackage : deps) {
9482                // TODO: Analyze and investigate if we (should) profile libraries.
9483                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9484                        false /* checkProfiles */,
9485                        targetCompilerFilter,
9486                        getOrCreateCompilerPackageStats(depPackage),
9487                        true /* isUsedByOtherApps */,
9488                        bootComplete);
9489            }
9490        }
9491        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9492                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9493                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9494    }
9495
9496    // Performs dexopt on the used secondary dex files belonging to the given package.
9497    // Returns true if all dex files were process successfully (which could mean either dexopt or
9498    // skip). Returns false if any of the files caused errors.
9499    @Override
9500    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9501            boolean force) {
9502        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9503            return false;
9504        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9505            return false;
9506        }
9507        mDexManager.reconcileSecondaryDexFiles(packageName);
9508        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9509    }
9510
9511    public boolean performDexOptSecondary(String packageName, int compileReason,
9512            boolean force) {
9513        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9514    }
9515
9516    /**
9517     * Reconcile the information we have about the secondary dex files belonging to
9518     * {@code packagName} and the actual dex files. For all dex files that were
9519     * deleted, update the internal records and delete the generated oat files.
9520     */
9521    @Override
9522    public void reconcileSecondaryDexFiles(String packageName) {
9523        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9524            return;
9525        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9526            return;
9527        }
9528        mDexManager.reconcileSecondaryDexFiles(packageName);
9529    }
9530
9531    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9532    // a reference there.
9533    /*package*/ DexManager getDexManager() {
9534        return mDexManager;
9535    }
9536
9537    /**
9538     * Execute the background dexopt job immediately.
9539     */
9540    @Override
9541    public boolean runBackgroundDexoptJob() {
9542        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9543            return false;
9544        }
9545        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9546    }
9547
9548    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9549        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9550                || p.usesStaticLibraries != null) {
9551            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9552            Set<String> collectedNames = new HashSet<>();
9553            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9554
9555            retValue.remove(p);
9556
9557            return retValue;
9558        } else {
9559            return Collections.emptyList();
9560        }
9561    }
9562
9563    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9564            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9565        if (!collectedNames.contains(p.packageName)) {
9566            collectedNames.add(p.packageName);
9567            collected.add(p);
9568
9569            if (p.usesLibraries != null) {
9570                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9571                        null, collected, collectedNames);
9572            }
9573            if (p.usesOptionalLibraries != null) {
9574                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9575                        null, collected, collectedNames);
9576            }
9577            if (p.usesStaticLibraries != null) {
9578                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9579                        p.usesStaticLibrariesVersions, collected, collectedNames);
9580            }
9581        }
9582    }
9583
9584    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9585            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9586        final int libNameCount = libs.size();
9587        for (int i = 0; i < libNameCount; i++) {
9588            String libName = libs.get(i);
9589            int version = (versions != null && versions.length == libNameCount)
9590                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9591            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9592            if (libPkg != null) {
9593                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9594            }
9595        }
9596    }
9597
9598    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9599        synchronized (mPackages) {
9600            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9601            if (libEntry != null) {
9602                return mPackages.get(libEntry.apk);
9603            }
9604            return null;
9605        }
9606    }
9607
9608    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9609        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9610        if (versionedLib == null) {
9611            return null;
9612        }
9613        return versionedLib.get(version);
9614    }
9615
9616    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9617        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9618                pkg.staticSharedLibName);
9619        if (versionedLib == null) {
9620            return null;
9621        }
9622        int previousLibVersion = -1;
9623        final int versionCount = versionedLib.size();
9624        for (int i = 0; i < versionCount; i++) {
9625            final int libVersion = versionedLib.keyAt(i);
9626            if (libVersion < pkg.staticSharedLibVersion) {
9627                previousLibVersion = Math.max(previousLibVersion, libVersion);
9628            }
9629        }
9630        if (previousLibVersion >= 0) {
9631            return versionedLib.get(previousLibVersion);
9632        }
9633        return null;
9634    }
9635
9636    public void shutdown() {
9637        mPackageUsage.writeNow(mPackages);
9638        mCompilerStats.writeNow();
9639    }
9640
9641    @Override
9642    public void dumpProfiles(String packageName) {
9643        PackageParser.Package pkg;
9644        synchronized (mPackages) {
9645            pkg = mPackages.get(packageName);
9646            if (pkg == null) {
9647                throw new IllegalArgumentException("Unknown package: " + packageName);
9648            }
9649        }
9650        /* Only the shell, root, or the app user should be able to dump profiles. */
9651        int callingUid = Binder.getCallingUid();
9652        if (callingUid != Process.SHELL_UID &&
9653            callingUid != Process.ROOT_UID &&
9654            callingUid != pkg.applicationInfo.uid) {
9655            throw new SecurityException("dumpProfiles");
9656        }
9657
9658        synchronized (mInstallLock) {
9659            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9660            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9661            try {
9662                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9663                String codePaths = TextUtils.join(";", allCodePaths);
9664                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9665            } catch (InstallerException e) {
9666                Slog.w(TAG, "Failed to dump profiles", e);
9667            }
9668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9669        }
9670    }
9671
9672    @Override
9673    public void forceDexOpt(String packageName) {
9674        enforceSystemOrRoot("forceDexOpt");
9675
9676        PackageParser.Package pkg;
9677        synchronized (mPackages) {
9678            pkg = mPackages.get(packageName);
9679            if (pkg == null) {
9680                throw new IllegalArgumentException("Unknown package: " + packageName);
9681            }
9682        }
9683
9684        synchronized (mInstallLock) {
9685            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9686
9687            // Whoever is calling forceDexOpt wants a compiled package.
9688            // Don't use profiles since that may cause compilation to be skipped.
9689            final int res = performDexOptInternalWithDependenciesLI(pkg,
9690                    false /* checkProfiles */, getDefaultCompilerFilter(),
9691                    true /* force */,
9692                    true /* bootComplete */);
9693
9694            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9695            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9696                throw new IllegalStateException("Failed to dexopt: " + res);
9697            }
9698        }
9699    }
9700
9701    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9702        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9703            Slog.w(TAG, "Unable to update from " + oldPkg.name
9704                    + " to " + newPkg.packageName
9705                    + ": old package not in system partition");
9706            return false;
9707        } else if (mPackages.get(oldPkg.name) != null) {
9708            Slog.w(TAG, "Unable to update from " + oldPkg.name
9709                    + " to " + newPkg.packageName
9710                    + ": old package still exists");
9711            return false;
9712        }
9713        return true;
9714    }
9715
9716    void removeCodePathLI(File codePath) {
9717        if (codePath.isDirectory()) {
9718            try {
9719                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9720            } catch (InstallerException e) {
9721                Slog.w(TAG, "Failed to remove code path", e);
9722            }
9723        } else {
9724            codePath.delete();
9725        }
9726    }
9727
9728    private int[] resolveUserIds(int userId) {
9729        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9730    }
9731
9732    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9733        if (pkg == null) {
9734            Slog.wtf(TAG, "Package was null!", new Throwable());
9735            return;
9736        }
9737        clearAppDataLeafLIF(pkg, userId, flags);
9738        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9739        for (int i = 0; i < childCount; i++) {
9740            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9741        }
9742    }
9743
9744    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9745        final PackageSetting ps;
9746        synchronized (mPackages) {
9747            ps = mSettings.mPackages.get(pkg.packageName);
9748        }
9749        for (int realUserId : resolveUserIds(userId)) {
9750            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9751            try {
9752                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9753                        ceDataInode);
9754            } catch (InstallerException e) {
9755                Slog.w(TAG, String.valueOf(e));
9756            }
9757        }
9758    }
9759
9760    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9761        if (pkg == null) {
9762            Slog.wtf(TAG, "Package was null!", new Throwable());
9763            return;
9764        }
9765        destroyAppDataLeafLIF(pkg, userId, flags);
9766        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9767        for (int i = 0; i < childCount; i++) {
9768            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9769        }
9770    }
9771
9772    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9773        final PackageSetting ps;
9774        synchronized (mPackages) {
9775            ps = mSettings.mPackages.get(pkg.packageName);
9776        }
9777        for (int realUserId : resolveUserIds(userId)) {
9778            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9779            try {
9780                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9781                        ceDataInode);
9782            } catch (InstallerException e) {
9783                Slog.w(TAG, String.valueOf(e));
9784            }
9785            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9786        }
9787    }
9788
9789    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9790        if (pkg == null) {
9791            Slog.wtf(TAG, "Package was null!", new Throwable());
9792            return;
9793        }
9794        destroyAppProfilesLeafLIF(pkg);
9795        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9796        for (int i = 0; i < childCount; i++) {
9797            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9798        }
9799    }
9800
9801    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9802        try {
9803            mInstaller.destroyAppProfiles(pkg.packageName);
9804        } catch (InstallerException e) {
9805            Slog.w(TAG, String.valueOf(e));
9806        }
9807    }
9808
9809    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9810        if (pkg == null) {
9811            Slog.wtf(TAG, "Package was null!", new Throwable());
9812            return;
9813        }
9814        clearAppProfilesLeafLIF(pkg);
9815        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9816        for (int i = 0; i < childCount; i++) {
9817            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9818        }
9819    }
9820
9821    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9822        try {
9823            mInstaller.clearAppProfiles(pkg.packageName);
9824        } catch (InstallerException e) {
9825            Slog.w(TAG, String.valueOf(e));
9826        }
9827    }
9828
9829    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9830            long lastUpdateTime) {
9831        // Set parent install/update time
9832        PackageSetting ps = (PackageSetting) pkg.mExtras;
9833        if (ps != null) {
9834            ps.firstInstallTime = firstInstallTime;
9835            ps.lastUpdateTime = lastUpdateTime;
9836        }
9837        // Set children install/update time
9838        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9839        for (int i = 0; i < childCount; i++) {
9840            PackageParser.Package childPkg = pkg.childPackages.get(i);
9841            ps = (PackageSetting) childPkg.mExtras;
9842            if (ps != null) {
9843                ps.firstInstallTime = firstInstallTime;
9844                ps.lastUpdateTime = lastUpdateTime;
9845            }
9846        }
9847    }
9848
9849    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9850            PackageParser.Package changingLib) {
9851        if (file.path != null) {
9852            usesLibraryFiles.add(file.path);
9853            return;
9854        }
9855        PackageParser.Package p = mPackages.get(file.apk);
9856        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9857            // If we are doing this while in the middle of updating a library apk,
9858            // then we need to make sure to use that new apk for determining the
9859            // dependencies here.  (We haven't yet finished committing the new apk
9860            // to the package manager state.)
9861            if (p == null || p.packageName.equals(changingLib.packageName)) {
9862                p = changingLib;
9863            }
9864        }
9865        if (p != null) {
9866            usesLibraryFiles.addAll(p.getAllCodePaths());
9867            if (p.usesLibraryFiles != null) {
9868                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9869            }
9870        }
9871    }
9872
9873    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9874            PackageParser.Package changingLib) throws PackageManagerException {
9875        if (pkg == null) {
9876            return;
9877        }
9878        ArraySet<String> usesLibraryFiles = null;
9879        if (pkg.usesLibraries != null) {
9880            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9881                    null, null, pkg.packageName, changingLib, true, null);
9882        }
9883        if (pkg.usesStaticLibraries != null) {
9884            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9885                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9886                    pkg.packageName, changingLib, true, usesLibraryFiles);
9887        }
9888        if (pkg.usesOptionalLibraries != null) {
9889            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9890                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9891        }
9892        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9893            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9894        } else {
9895            pkg.usesLibraryFiles = null;
9896        }
9897    }
9898
9899    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9900            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9901            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9902            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9903            throws PackageManagerException {
9904        final int libCount = requestedLibraries.size();
9905        for (int i = 0; i < libCount; i++) {
9906            final String libName = requestedLibraries.get(i);
9907            final int libVersion = requiredVersions != null ? requiredVersions[i]
9908                    : SharedLibraryInfo.VERSION_UNDEFINED;
9909            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9910            if (libEntry == null) {
9911                if (required) {
9912                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9913                            "Package " + packageName + " requires unavailable shared library "
9914                                    + libName + "; failing!");
9915                } else if (DEBUG_SHARED_LIBRARIES) {
9916                    Slog.i(TAG, "Package " + packageName
9917                            + " desires unavailable shared library "
9918                            + libName + "; ignoring!");
9919                }
9920            } else {
9921                if (requiredVersions != null && requiredCertDigests != null) {
9922                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9923                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9924                            "Package " + packageName + " requires unavailable static shared"
9925                                    + " library " + libName + " version "
9926                                    + libEntry.info.getVersion() + "; failing!");
9927                    }
9928
9929                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9930                    if (libPkg == null) {
9931                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9932                                "Package " + packageName + " requires unavailable static shared"
9933                                        + " library; failing!");
9934                    }
9935
9936                    String expectedCertDigest = requiredCertDigests[i];
9937                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9938                                libPkg.mSignatures[0]);
9939                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9940                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9941                                "Package " + packageName + " requires differently signed" +
9942                                        " static shared library; failing!");
9943                    }
9944                }
9945
9946                if (outUsedLibraries == null) {
9947                    outUsedLibraries = new ArraySet<>();
9948                }
9949                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9950            }
9951        }
9952        return outUsedLibraries;
9953    }
9954
9955    private static boolean hasString(List<String> list, List<String> which) {
9956        if (list == null) {
9957            return false;
9958        }
9959        for (int i=list.size()-1; i>=0; i--) {
9960            for (int j=which.size()-1; j>=0; j--) {
9961                if (which.get(j).equals(list.get(i))) {
9962                    return true;
9963                }
9964            }
9965        }
9966        return false;
9967    }
9968
9969    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9970            PackageParser.Package changingPkg) {
9971        ArrayList<PackageParser.Package> res = null;
9972        for (PackageParser.Package pkg : mPackages.values()) {
9973            if (changingPkg != null
9974                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9975                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9976                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9977                            changingPkg.staticSharedLibName)) {
9978                return null;
9979            }
9980            if (res == null) {
9981                res = new ArrayList<>();
9982            }
9983            res.add(pkg);
9984            try {
9985                updateSharedLibrariesLPr(pkg, changingPkg);
9986            } catch (PackageManagerException e) {
9987                // If a system app update or an app and a required lib missing we
9988                // delete the package and for updated system apps keep the data as
9989                // it is better for the user to reinstall than to be in an limbo
9990                // state. Also libs disappearing under an app should never happen
9991                // - just in case.
9992                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9993                    final int flags = pkg.isUpdatedSystemApp()
9994                            ? PackageManager.DELETE_KEEP_DATA : 0;
9995                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9996                            flags , null, true, null);
9997                }
9998                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9999            }
10000        }
10001        return res;
10002    }
10003
10004    /**
10005     * Derive the value of the {@code cpuAbiOverride} based on the provided
10006     * value and an optional stored value from the package settings.
10007     */
10008    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10009        String cpuAbiOverride = null;
10010
10011        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10012            cpuAbiOverride = null;
10013        } else if (abiOverride != null) {
10014            cpuAbiOverride = abiOverride;
10015        } else if (settings != null) {
10016            cpuAbiOverride = settings.cpuAbiOverrideString;
10017        }
10018
10019        return cpuAbiOverride;
10020    }
10021
10022    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10023            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10024                    throws PackageManagerException {
10025        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10026        // If the package has children and this is the first dive in the function
10027        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10028        // whether all packages (parent and children) would be successfully scanned
10029        // before the actual scan since scanning mutates internal state and we want
10030        // to atomically install the package and its children.
10031        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10032            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10033                scanFlags |= SCAN_CHECK_ONLY;
10034            }
10035        } else {
10036            scanFlags &= ~SCAN_CHECK_ONLY;
10037        }
10038
10039        final PackageParser.Package scannedPkg;
10040        try {
10041            // Scan the parent
10042            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10043            // Scan the children
10044            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10045            for (int i = 0; i < childCount; i++) {
10046                PackageParser.Package childPkg = pkg.childPackages.get(i);
10047                scanPackageLI(childPkg, policyFlags,
10048                        scanFlags, currentTime, user);
10049            }
10050        } finally {
10051            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10052        }
10053
10054        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10055            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10056        }
10057
10058        return scannedPkg;
10059    }
10060
10061    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10062            int scanFlags, long currentTime, @Nullable UserHandle user)
10063                    throws PackageManagerException {
10064        boolean success = false;
10065        try {
10066            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10067                    currentTime, user);
10068            success = true;
10069            return res;
10070        } finally {
10071            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10072                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10073                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10074                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10075                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10076            }
10077        }
10078    }
10079
10080    /**
10081     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10082     */
10083    private static boolean apkHasCode(String fileName) {
10084        StrictJarFile jarFile = null;
10085        try {
10086            jarFile = new StrictJarFile(fileName,
10087                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10088            return jarFile.findEntry("classes.dex") != null;
10089        } catch (IOException ignore) {
10090        } finally {
10091            try {
10092                if (jarFile != null) {
10093                    jarFile.close();
10094                }
10095            } catch (IOException ignore) {}
10096        }
10097        return false;
10098    }
10099
10100    /**
10101     * Enforces code policy for the package. This ensures that if an APK has
10102     * declared hasCode="true" in its manifest that the APK actually contains
10103     * code.
10104     *
10105     * @throws PackageManagerException If bytecode could not be found when it should exist
10106     */
10107    private static void assertCodePolicy(PackageParser.Package pkg)
10108            throws PackageManagerException {
10109        final boolean shouldHaveCode =
10110                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10111        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10112            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10113                    "Package " + pkg.baseCodePath + " code is missing");
10114        }
10115
10116        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10117            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10118                final boolean splitShouldHaveCode =
10119                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10120                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10121                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10122                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10123                }
10124            }
10125        }
10126    }
10127
10128    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10129            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10130                    throws PackageManagerException {
10131        if (DEBUG_PACKAGE_SCANNING) {
10132            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10133                Log.d(TAG, "Scanning package " + pkg.packageName);
10134        }
10135
10136        applyPolicy(pkg, policyFlags);
10137
10138        assertPackageIsValid(pkg, policyFlags, scanFlags);
10139
10140        // Initialize package source and resource directories
10141        final File scanFile = new File(pkg.codePath);
10142        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10143        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10144
10145        SharedUserSetting suid = null;
10146        PackageSetting pkgSetting = null;
10147
10148        // Getting the package setting may have a side-effect, so if we
10149        // are only checking if scan would succeed, stash a copy of the
10150        // old setting to restore at the end.
10151        PackageSetting nonMutatedPs = null;
10152
10153        // We keep references to the derived CPU Abis from settings in oder to reuse
10154        // them in the case where we're not upgrading or booting for the first time.
10155        String primaryCpuAbiFromSettings = null;
10156        String secondaryCpuAbiFromSettings = null;
10157
10158        // writer
10159        synchronized (mPackages) {
10160            if (pkg.mSharedUserId != null) {
10161                // SIDE EFFECTS; may potentially allocate a new shared user
10162                suid = mSettings.getSharedUserLPw(
10163                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10164                if (DEBUG_PACKAGE_SCANNING) {
10165                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10166                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10167                                + "): packages=" + suid.packages);
10168                }
10169            }
10170
10171            // Check if we are renaming from an original package name.
10172            PackageSetting origPackage = null;
10173            String realName = null;
10174            if (pkg.mOriginalPackages != null) {
10175                // This package may need to be renamed to a previously
10176                // installed name.  Let's check on that...
10177                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10178                if (pkg.mOriginalPackages.contains(renamed)) {
10179                    // This package had originally been installed as the
10180                    // original name, and we have already taken care of
10181                    // transitioning to the new one.  Just update the new
10182                    // one to continue using the old name.
10183                    realName = pkg.mRealPackage;
10184                    if (!pkg.packageName.equals(renamed)) {
10185                        // Callers into this function may have already taken
10186                        // care of renaming the package; only do it here if
10187                        // it is not already done.
10188                        pkg.setPackageName(renamed);
10189                    }
10190                } else {
10191                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10192                        if ((origPackage = mSettings.getPackageLPr(
10193                                pkg.mOriginalPackages.get(i))) != null) {
10194                            // We do have the package already installed under its
10195                            // original name...  should we use it?
10196                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10197                                // New package is not compatible with original.
10198                                origPackage = null;
10199                                continue;
10200                            } else if (origPackage.sharedUser != null) {
10201                                // Make sure uid is compatible between packages.
10202                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10203                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10204                                            + " to " + pkg.packageName + ": old uid "
10205                                            + origPackage.sharedUser.name
10206                                            + " differs from " + pkg.mSharedUserId);
10207                                    origPackage = null;
10208                                    continue;
10209                                }
10210                                // TODO: Add case when shared user id is added [b/28144775]
10211                            } else {
10212                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10213                                        + pkg.packageName + " to old name " + origPackage.name);
10214                            }
10215                            break;
10216                        }
10217                    }
10218                }
10219            }
10220
10221            if (mTransferedPackages.contains(pkg.packageName)) {
10222                Slog.w(TAG, "Package " + pkg.packageName
10223                        + " was transferred to another, but its .apk remains");
10224            }
10225
10226            // See comments in nonMutatedPs declaration
10227            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10228                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10229                if (foundPs != null) {
10230                    nonMutatedPs = new PackageSetting(foundPs);
10231                }
10232            }
10233
10234            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10235                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10236                if (foundPs != null) {
10237                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10238                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10239                }
10240            }
10241
10242            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10243            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10244                PackageManagerService.reportSettingsProblem(Log.WARN,
10245                        "Package " + pkg.packageName + " shared user changed from "
10246                                + (pkgSetting.sharedUser != null
10247                                        ? pkgSetting.sharedUser.name : "<nothing>")
10248                                + " to "
10249                                + (suid != null ? suid.name : "<nothing>")
10250                                + "; replacing with new");
10251                pkgSetting = null;
10252            }
10253            final PackageSetting oldPkgSetting =
10254                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10255            final PackageSetting disabledPkgSetting =
10256                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10257
10258            String[] usesStaticLibraries = null;
10259            if (pkg.usesStaticLibraries != null) {
10260                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10261                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10262            }
10263
10264            if (pkgSetting == null) {
10265                final String parentPackageName = (pkg.parentPackage != null)
10266                        ? pkg.parentPackage.packageName : null;
10267                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10268                // REMOVE SharedUserSetting from method; update in a separate call
10269                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10270                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10271                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10272                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10273                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10274                        true /*allowInstall*/, instantApp, parentPackageName,
10275                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10276                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10277                // SIDE EFFECTS; updates system state; move elsewhere
10278                if (origPackage != null) {
10279                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10280                }
10281                mSettings.addUserToSettingLPw(pkgSetting);
10282            } else {
10283                // REMOVE SharedUserSetting from method; update in a separate call.
10284                //
10285                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10286                // secondaryCpuAbi are not known at this point so we always update them
10287                // to null here, only to reset them at a later point.
10288                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10289                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10290                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10291                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10292                        UserManagerService.getInstance(), usesStaticLibraries,
10293                        pkg.usesStaticLibrariesVersions);
10294            }
10295            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10296            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10297
10298            // SIDE EFFECTS; modifies system state; move elsewhere
10299            if (pkgSetting.origPackage != null) {
10300                // If we are first transitioning from an original package,
10301                // fix up the new package's name now.  We need to do this after
10302                // looking up the package under its new name, so getPackageLP
10303                // can take care of fiddling things correctly.
10304                pkg.setPackageName(origPackage.name);
10305
10306                // File a report about this.
10307                String msg = "New package " + pkgSetting.realName
10308                        + " renamed to replace old package " + pkgSetting.name;
10309                reportSettingsProblem(Log.WARN, msg);
10310
10311                // Make a note of it.
10312                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10313                    mTransferedPackages.add(origPackage.name);
10314                }
10315
10316                // No longer need to retain this.
10317                pkgSetting.origPackage = null;
10318            }
10319
10320            // SIDE EFFECTS; modifies system state; move elsewhere
10321            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10322                // Make a note of it.
10323                mTransferedPackages.add(pkg.packageName);
10324            }
10325
10326            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10327                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10328            }
10329
10330            if ((scanFlags & SCAN_BOOTING) == 0
10331                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10332                // Check all shared libraries and map to their actual file path.
10333                // We only do this here for apps not on a system dir, because those
10334                // are the only ones that can fail an install due to this.  We
10335                // will take care of the system apps by updating all of their
10336                // library paths after the scan is done. Also during the initial
10337                // scan don't update any libs as we do this wholesale after all
10338                // apps are scanned to avoid dependency based scanning.
10339                updateSharedLibrariesLPr(pkg, null);
10340            }
10341
10342            if (mFoundPolicyFile) {
10343                SELinuxMMAC.assignSeInfoValue(pkg);
10344            }
10345            pkg.applicationInfo.uid = pkgSetting.appId;
10346            pkg.mExtras = pkgSetting;
10347
10348
10349            // Static shared libs have same package with different versions where
10350            // we internally use a synthetic package name to allow multiple versions
10351            // of the same package, therefore we need to compare signatures against
10352            // the package setting for the latest library version.
10353            PackageSetting signatureCheckPs = pkgSetting;
10354            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10355                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10356                if (libraryEntry != null) {
10357                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10358                }
10359            }
10360
10361            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10362                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10363                    // We just determined the app is signed correctly, so bring
10364                    // over the latest parsed certs.
10365                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10366                } else {
10367                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10368                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10369                                "Package " + pkg.packageName + " upgrade keys do not match the "
10370                                + "previously installed version");
10371                    } else {
10372                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10373                        String msg = "System package " + pkg.packageName
10374                                + " signature changed; retaining data.";
10375                        reportSettingsProblem(Log.WARN, msg);
10376                    }
10377                }
10378            } else {
10379                try {
10380                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10381                    verifySignaturesLP(signatureCheckPs, pkg);
10382                    // We just determined the app is signed correctly, so bring
10383                    // over the latest parsed certs.
10384                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10385                } catch (PackageManagerException e) {
10386                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10387                        throw e;
10388                    }
10389                    // The signature has changed, but this package is in the system
10390                    // image...  let's recover!
10391                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10392                    // However...  if this package is part of a shared user, but it
10393                    // doesn't match the signature of the shared user, let's fail.
10394                    // What this means is that you can't change the signatures
10395                    // associated with an overall shared user, which doesn't seem all
10396                    // that unreasonable.
10397                    if (signatureCheckPs.sharedUser != null) {
10398                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10399                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10400                            throw new PackageManagerException(
10401                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10402                                    "Signature mismatch for shared user: "
10403                                            + pkgSetting.sharedUser);
10404                        }
10405                    }
10406                    // File a report about this.
10407                    String msg = "System package " + pkg.packageName
10408                            + " signature changed; retaining data.";
10409                    reportSettingsProblem(Log.WARN, msg);
10410                }
10411            }
10412
10413            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10414                // This package wants to adopt ownership of permissions from
10415                // another package.
10416                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10417                    final String origName = pkg.mAdoptPermissions.get(i);
10418                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10419                    if (orig != null) {
10420                        if (verifyPackageUpdateLPr(orig, pkg)) {
10421                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10422                                    + pkg.packageName);
10423                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10424                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10425                        }
10426                    }
10427                }
10428            }
10429        }
10430
10431        pkg.applicationInfo.processName = fixProcessName(
10432                pkg.applicationInfo.packageName,
10433                pkg.applicationInfo.processName);
10434
10435        if (pkg != mPlatformPackage) {
10436            // Get all of our default paths setup
10437            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10438        }
10439
10440        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10441
10442        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10443            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10444                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10445                final boolean extractNativeLibs = !pkg.isLibrary();
10446                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10447                        mAppLib32InstallDir);
10448                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10449
10450                // Some system apps still use directory structure for native libraries
10451                // in which case we might end up not detecting abi solely based on apk
10452                // structure. Try to detect abi based on directory structure.
10453                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10454                        pkg.applicationInfo.primaryCpuAbi == null) {
10455                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10456                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10457                }
10458            } else {
10459                // This is not a first boot or an upgrade, don't bother deriving the
10460                // ABI during the scan. Instead, trust the value that was stored in the
10461                // package setting.
10462                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10463                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10464
10465                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10466
10467                if (DEBUG_ABI_SELECTION) {
10468                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10469                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10470                        pkg.applicationInfo.secondaryCpuAbi);
10471                }
10472            }
10473        } else {
10474            if ((scanFlags & SCAN_MOVE) != 0) {
10475                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10476                // but we already have this packages package info in the PackageSetting. We just
10477                // use that and derive the native library path based on the new codepath.
10478                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10479                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10480            }
10481
10482            // Set native library paths again. For moves, the path will be updated based on the
10483            // ABIs we've determined above. For non-moves, the path will be updated based on the
10484            // ABIs we determined during compilation, but the path will depend on the final
10485            // package path (after the rename away from the stage path).
10486            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10487        }
10488
10489        // This is a special case for the "system" package, where the ABI is
10490        // dictated by the zygote configuration (and init.rc). We should keep track
10491        // of this ABI so that we can deal with "normal" applications that run under
10492        // the same UID correctly.
10493        if (mPlatformPackage == pkg) {
10494            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10495                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10496        }
10497
10498        // If there's a mismatch between the abi-override in the package setting
10499        // and the abiOverride specified for the install. Warn about this because we
10500        // would've already compiled the app without taking the package setting into
10501        // account.
10502        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10503            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10504                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10505                        " for package " + pkg.packageName);
10506            }
10507        }
10508
10509        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10510        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10511        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10512
10513        // Copy the derived override back to the parsed package, so that we can
10514        // update the package settings accordingly.
10515        pkg.cpuAbiOverride = cpuAbiOverride;
10516
10517        if (DEBUG_ABI_SELECTION) {
10518            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10519                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10520                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10521        }
10522
10523        // Push the derived path down into PackageSettings so we know what to
10524        // clean up at uninstall time.
10525        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10526
10527        if (DEBUG_ABI_SELECTION) {
10528            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10529                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10530                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10531        }
10532
10533        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10534        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10535            // We don't do this here during boot because we can do it all
10536            // at once after scanning all existing packages.
10537            //
10538            // We also do this *before* we perform dexopt on this package, so that
10539            // we can avoid redundant dexopts, and also to make sure we've got the
10540            // code and package path correct.
10541            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10542        }
10543
10544        if (mFactoryTest && pkg.requestedPermissions.contains(
10545                android.Manifest.permission.FACTORY_TEST)) {
10546            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10547        }
10548
10549        if (isSystemApp(pkg)) {
10550            pkgSetting.isOrphaned = true;
10551        }
10552
10553        // Take care of first install / last update times.
10554        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10555        if (currentTime != 0) {
10556            if (pkgSetting.firstInstallTime == 0) {
10557                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10558            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10559                pkgSetting.lastUpdateTime = currentTime;
10560            }
10561        } else if (pkgSetting.firstInstallTime == 0) {
10562            // We need *something*.  Take time time stamp of the file.
10563            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10564        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10565            if (scanFileTime != pkgSetting.timeStamp) {
10566                // A package on the system image has changed; consider this
10567                // to be an update.
10568                pkgSetting.lastUpdateTime = scanFileTime;
10569            }
10570        }
10571        pkgSetting.setTimeStamp(scanFileTime);
10572
10573        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10574            if (nonMutatedPs != null) {
10575                synchronized (mPackages) {
10576                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10577                }
10578            }
10579        } else {
10580            final int userId = user == null ? 0 : user.getIdentifier();
10581            // Modify state for the given package setting
10582            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10583                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10584            if (pkgSetting.getInstantApp(userId)) {
10585                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10586            }
10587        }
10588        return pkg;
10589    }
10590
10591    /**
10592     * Applies policy to the parsed package based upon the given policy flags.
10593     * Ensures the package is in a good state.
10594     * <p>
10595     * Implementation detail: This method must NOT have any side effect. It would
10596     * ideally be static, but, it requires locks to read system state.
10597     */
10598    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10599        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10600            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10601            if (pkg.applicationInfo.isDirectBootAware()) {
10602                // we're direct boot aware; set for all components
10603                for (PackageParser.Service s : pkg.services) {
10604                    s.info.encryptionAware = s.info.directBootAware = true;
10605                }
10606                for (PackageParser.Provider p : pkg.providers) {
10607                    p.info.encryptionAware = p.info.directBootAware = true;
10608                }
10609                for (PackageParser.Activity a : pkg.activities) {
10610                    a.info.encryptionAware = a.info.directBootAware = true;
10611                }
10612                for (PackageParser.Activity r : pkg.receivers) {
10613                    r.info.encryptionAware = r.info.directBootAware = true;
10614                }
10615            }
10616        } else {
10617            // Only allow system apps to be flagged as core apps.
10618            pkg.coreApp = false;
10619            // clear flags not applicable to regular apps
10620            pkg.applicationInfo.privateFlags &=
10621                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10622            pkg.applicationInfo.privateFlags &=
10623                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10624        }
10625        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10626
10627        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10628            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10629        }
10630
10631        if (!isSystemApp(pkg)) {
10632            // Only system apps can use these features.
10633            pkg.mOriginalPackages = null;
10634            pkg.mRealPackage = null;
10635            pkg.mAdoptPermissions = null;
10636        }
10637    }
10638
10639    /**
10640     * Asserts the parsed package is valid according to the given policy. If the
10641     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10642     * <p>
10643     * Implementation detail: This method must NOT have any side effects. It would
10644     * ideally be static, but, it requires locks to read system state.
10645     *
10646     * @throws PackageManagerException If the package fails any of the validation checks
10647     */
10648    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10649            throws PackageManagerException {
10650        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10651            assertCodePolicy(pkg);
10652        }
10653
10654        if (pkg.applicationInfo.getCodePath() == null ||
10655                pkg.applicationInfo.getResourcePath() == null) {
10656            // Bail out. The resource and code paths haven't been set.
10657            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10658                    "Code and resource paths haven't been set correctly");
10659        }
10660
10661        // Make sure we're not adding any bogus keyset info
10662        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10663        ksms.assertScannedPackageValid(pkg);
10664
10665        synchronized (mPackages) {
10666            // The special "android" package can only be defined once
10667            if (pkg.packageName.equals("android")) {
10668                if (mAndroidApplication != null) {
10669                    Slog.w(TAG, "*************************************************");
10670                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10671                    Slog.w(TAG, " codePath=" + pkg.codePath);
10672                    Slog.w(TAG, "*************************************************");
10673                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10674                            "Core android package being redefined.  Skipping.");
10675                }
10676            }
10677
10678            // A package name must be unique; don't allow duplicates
10679            if (mPackages.containsKey(pkg.packageName)) {
10680                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10681                        "Application package " + pkg.packageName
10682                        + " already installed.  Skipping duplicate.");
10683            }
10684
10685            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10686                // Static libs have a synthetic package name containing the version
10687                // but we still want the base name to be unique.
10688                if (mPackages.containsKey(pkg.manifestPackageName)) {
10689                    throw new PackageManagerException(
10690                            "Duplicate static shared lib provider package");
10691                }
10692
10693                // Static shared libraries should have at least O target SDK
10694                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10695                    throw new PackageManagerException(
10696                            "Packages declaring static-shared libs must target O SDK or higher");
10697                }
10698
10699                // Package declaring static a shared lib cannot be instant apps
10700                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10701                    throw new PackageManagerException(
10702                            "Packages declaring static-shared libs cannot be instant apps");
10703                }
10704
10705                // Package declaring static a shared lib cannot be renamed since the package
10706                // name is synthetic and apps can't code around package manager internals.
10707                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10708                    throw new PackageManagerException(
10709                            "Packages declaring static-shared libs cannot be renamed");
10710                }
10711
10712                // Package declaring static a shared lib cannot declare child packages
10713                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10714                    throw new PackageManagerException(
10715                            "Packages declaring static-shared libs cannot have child packages");
10716                }
10717
10718                // Package declaring static a shared lib cannot declare dynamic libs
10719                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10720                    throw new PackageManagerException(
10721                            "Packages declaring static-shared libs cannot declare dynamic libs");
10722                }
10723
10724                // Package declaring static a shared lib cannot declare shared users
10725                if (pkg.mSharedUserId != null) {
10726                    throw new PackageManagerException(
10727                            "Packages declaring static-shared libs cannot declare shared users");
10728                }
10729
10730                // Static shared libs cannot declare activities
10731                if (!pkg.activities.isEmpty()) {
10732                    throw new PackageManagerException(
10733                            "Static shared libs cannot declare activities");
10734                }
10735
10736                // Static shared libs cannot declare services
10737                if (!pkg.services.isEmpty()) {
10738                    throw new PackageManagerException(
10739                            "Static shared libs cannot declare services");
10740                }
10741
10742                // Static shared libs cannot declare providers
10743                if (!pkg.providers.isEmpty()) {
10744                    throw new PackageManagerException(
10745                            "Static shared libs cannot declare content providers");
10746                }
10747
10748                // Static shared libs cannot declare receivers
10749                if (!pkg.receivers.isEmpty()) {
10750                    throw new PackageManagerException(
10751                            "Static shared libs cannot declare broadcast receivers");
10752                }
10753
10754                // Static shared libs cannot declare permission groups
10755                if (!pkg.permissionGroups.isEmpty()) {
10756                    throw new PackageManagerException(
10757                            "Static shared libs cannot declare permission groups");
10758                }
10759
10760                // Static shared libs cannot declare permissions
10761                if (!pkg.permissions.isEmpty()) {
10762                    throw new PackageManagerException(
10763                            "Static shared libs cannot declare permissions");
10764                }
10765
10766                // Static shared libs cannot declare protected broadcasts
10767                if (pkg.protectedBroadcasts != null) {
10768                    throw new PackageManagerException(
10769                            "Static shared libs cannot declare protected broadcasts");
10770                }
10771
10772                // Static shared libs cannot be overlay targets
10773                if (pkg.mOverlayTarget != null) {
10774                    throw new PackageManagerException(
10775                            "Static shared libs cannot be overlay targets");
10776                }
10777
10778                // The version codes must be ordered as lib versions
10779                int minVersionCode = Integer.MIN_VALUE;
10780                int maxVersionCode = Integer.MAX_VALUE;
10781
10782                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10783                        pkg.staticSharedLibName);
10784                if (versionedLib != null) {
10785                    final int versionCount = versionedLib.size();
10786                    for (int i = 0; i < versionCount; i++) {
10787                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10788                        final int libVersionCode = libInfo.getDeclaringPackage()
10789                                .getVersionCode();
10790                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10791                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10792                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10793                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10794                        } else {
10795                            minVersionCode = maxVersionCode = libVersionCode;
10796                            break;
10797                        }
10798                    }
10799                }
10800                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10801                    throw new PackageManagerException("Static shared"
10802                            + " lib version codes must be ordered as lib versions");
10803                }
10804            }
10805
10806            // Only privileged apps and updated privileged apps can add child packages.
10807            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10808                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10809                    throw new PackageManagerException("Only privileged apps can add child "
10810                            + "packages. Ignoring package " + pkg.packageName);
10811                }
10812                final int childCount = pkg.childPackages.size();
10813                for (int i = 0; i < childCount; i++) {
10814                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10815                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10816                            childPkg.packageName)) {
10817                        throw new PackageManagerException("Can't override child of "
10818                                + "another disabled app. Ignoring package " + pkg.packageName);
10819                    }
10820                }
10821            }
10822
10823            // If we're only installing presumed-existing packages, require that the
10824            // scanned APK is both already known and at the path previously established
10825            // for it.  Previously unknown packages we pick up normally, but if we have an
10826            // a priori expectation about this package's install presence, enforce it.
10827            // With a singular exception for new system packages. When an OTA contains
10828            // a new system package, we allow the codepath to change from a system location
10829            // to the user-installed location. If we don't allow this change, any newer,
10830            // user-installed version of the application will be ignored.
10831            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10832                if (mExpectingBetter.containsKey(pkg.packageName)) {
10833                    logCriticalInfo(Log.WARN,
10834                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10835                } else {
10836                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10837                    if (known != null) {
10838                        if (DEBUG_PACKAGE_SCANNING) {
10839                            Log.d(TAG, "Examining " + pkg.codePath
10840                                    + " and requiring known paths " + known.codePathString
10841                                    + " & " + known.resourcePathString);
10842                        }
10843                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10844                                || !pkg.applicationInfo.getResourcePath().equals(
10845                                        known.resourcePathString)) {
10846                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10847                                    "Application package " + pkg.packageName
10848                                    + " found at " + pkg.applicationInfo.getCodePath()
10849                                    + " but expected at " + known.codePathString
10850                                    + "; ignoring.");
10851                        }
10852                    }
10853                }
10854            }
10855
10856            // Verify that this new package doesn't have any content providers
10857            // that conflict with existing packages.  Only do this if the
10858            // package isn't already installed, since we don't want to break
10859            // things that are installed.
10860            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10861                final int N = pkg.providers.size();
10862                int i;
10863                for (i=0; i<N; i++) {
10864                    PackageParser.Provider p = pkg.providers.get(i);
10865                    if (p.info.authority != null) {
10866                        String names[] = p.info.authority.split(";");
10867                        for (int j = 0; j < names.length; j++) {
10868                            if (mProvidersByAuthority.containsKey(names[j])) {
10869                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10870                                final String otherPackageName =
10871                                        ((other != null && other.getComponentName() != null) ?
10872                                                other.getComponentName().getPackageName() : "?");
10873                                throw new PackageManagerException(
10874                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10875                                        "Can't install because provider name " + names[j]
10876                                                + " (in package " + pkg.applicationInfo.packageName
10877                                                + ") is already used by " + otherPackageName);
10878                            }
10879                        }
10880                    }
10881                }
10882            }
10883        }
10884    }
10885
10886    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10887            int type, String declaringPackageName, int declaringVersionCode) {
10888        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10889        if (versionedLib == null) {
10890            versionedLib = new SparseArray<>();
10891            mSharedLibraries.put(name, versionedLib);
10892            if (type == SharedLibraryInfo.TYPE_STATIC) {
10893                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10894            }
10895        } else if (versionedLib.indexOfKey(version) >= 0) {
10896            return false;
10897        }
10898        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10899                version, type, declaringPackageName, declaringVersionCode);
10900        versionedLib.put(version, libEntry);
10901        return true;
10902    }
10903
10904    private boolean removeSharedLibraryLPw(String name, int version) {
10905        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10906        if (versionedLib == null) {
10907            return false;
10908        }
10909        final int libIdx = versionedLib.indexOfKey(version);
10910        if (libIdx < 0) {
10911            return false;
10912        }
10913        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10914        versionedLib.remove(version);
10915        if (versionedLib.size() <= 0) {
10916            mSharedLibraries.remove(name);
10917            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10918                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10919                        .getPackageName());
10920            }
10921        }
10922        return true;
10923    }
10924
10925    /**
10926     * Adds a scanned package to the system. When this method is finished, the package will
10927     * be available for query, resolution, etc...
10928     */
10929    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10930            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10931        final String pkgName = pkg.packageName;
10932        if (mCustomResolverComponentName != null &&
10933                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10934            setUpCustomResolverActivity(pkg);
10935        }
10936
10937        if (pkg.packageName.equals("android")) {
10938            synchronized (mPackages) {
10939                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10940                    // Set up information for our fall-back user intent resolution activity.
10941                    mPlatformPackage = pkg;
10942                    pkg.mVersionCode = mSdkVersion;
10943                    mAndroidApplication = pkg.applicationInfo;
10944                    if (!mResolverReplaced) {
10945                        mResolveActivity.applicationInfo = mAndroidApplication;
10946                        mResolveActivity.name = ResolverActivity.class.getName();
10947                        mResolveActivity.packageName = mAndroidApplication.packageName;
10948                        mResolveActivity.processName = "system:ui";
10949                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10950                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10951                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10952                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10953                        mResolveActivity.exported = true;
10954                        mResolveActivity.enabled = true;
10955                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10956                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10957                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10958                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10959                                | ActivityInfo.CONFIG_ORIENTATION
10960                                | ActivityInfo.CONFIG_KEYBOARD
10961                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10962                        mResolveInfo.activityInfo = mResolveActivity;
10963                        mResolveInfo.priority = 0;
10964                        mResolveInfo.preferredOrder = 0;
10965                        mResolveInfo.match = 0;
10966                        mResolveComponentName = new ComponentName(
10967                                mAndroidApplication.packageName, mResolveActivity.name);
10968                    }
10969                }
10970            }
10971        }
10972
10973        ArrayList<PackageParser.Package> clientLibPkgs = null;
10974        // writer
10975        synchronized (mPackages) {
10976            boolean hasStaticSharedLibs = false;
10977
10978            // Any app can add new static shared libraries
10979            if (pkg.staticSharedLibName != null) {
10980                // Static shared libs don't allow renaming as they have synthetic package
10981                // names to allow install of multiple versions, so use name from manifest.
10982                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10983                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10984                        pkg.manifestPackageName, pkg.mVersionCode)) {
10985                    hasStaticSharedLibs = true;
10986                } else {
10987                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10988                                + pkg.staticSharedLibName + " already exists; skipping");
10989                }
10990                // Static shared libs cannot be updated once installed since they
10991                // use synthetic package name which includes the version code, so
10992                // not need to update other packages's shared lib dependencies.
10993            }
10994
10995            if (!hasStaticSharedLibs
10996                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10997                // Only system apps can add new dynamic shared libraries.
10998                if (pkg.libraryNames != null) {
10999                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11000                        String name = pkg.libraryNames.get(i);
11001                        boolean allowed = false;
11002                        if (pkg.isUpdatedSystemApp()) {
11003                            // New library entries can only be added through the
11004                            // system image.  This is important to get rid of a lot
11005                            // of nasty edge cases: for example if we allowed a non-
11006                            // system update of the app to add a library, then uninstalling
11007                            // the update would make the library go away, and assumptions
11008                            // we made such as through app install filtering would now
11009                            // have allowed apps on the device which aren't compatible
11010                            // with it.  Better to just have the restriction here, be
11011                            // conservative, and create many fewer cases that can negatively
11012                            // impact the user experience.
11013                            final PackageSetting sysPs = mSettings
11014                                    .getDisabledSystemPkgLPr(pkg.packageName);
11015                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11016                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11017                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11018                                        allowed = true;
11019                                        break;
11020                                    }
11021                                }
11022                            }
11023                        } else {
11024                            allowed = true;
11025                        }
11026                        if (allowed) {
11027                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11028                                    SharedLibraryInfo.VERSION_UNDEFINED,
11029                                    SharedLibraryInfo.TYPE_DYNAMIC,
11030                                    pkg.packageName, pkg.mVersionCode)) {
11031                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11032                                        + name + " already exists; skipping");
11033                            }
11034                        } else {
11035                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11036                                    + name + " that is not declared on system image; skipping");
11037                        }
11038                    }
11039
11040                    if ((scanFlags & SCAN_BOOTING) == 0) {
11041                        // If we are not booting, we need to update any applications
11042                        // that are clients of our shared library.  If we are booting,
11043                        // this will all be done once the scan is complete.
11044                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11045                    }
11046                }
11047            }
11048        }
11049
11050        if ((scanFlags & SCAN_BOOTING) != 0) {
11051            // No apps can run during boot scan, so they don't need to be frozen
11052        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11053            // Caller asked to not kill app, so it's probably not frozen
11054        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11055            // Caller asked us to ignore frozen check for some reason; they
11056            // probably didn't know the package name
11057        } else {
11058            // We're doing major surgery on this package, so it better be frozen
11059            // right now to keep it from launching
11060            checkPackageFrozen(pkgName);
11061        }
11062
11063        // Also need to kill any apps that are dependent on the library.
11064        if (clientLibPkgs != null) {
11065            for (int i=0; i<clientLibPkgs.size(); i++) {
11066                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11067                killApplication(clientPkg.applicationInfo.packageName,
11068                        clientPkg.applicationInfo.uid, "update lib");
11069            }
11070        }
11071
11072        // writer
11073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11074
11075        synchronized (mPackages) {
11076            // We don't expect installation to fail beyond this point
11077
11078            // Add the new setting to mSettings
11079            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11080            // Add the new setting to mPackages
11081            mPackages.put(pkg.applicationInfo.packageName, pkg);
11082            // Make sure we don't accidentally delete its data.
11083            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11084            while (iter.hasNext()) {
11085                PackageCleanItem item = iter.next();
11086                if (pkgName.equals(item.packageName)) {
11087                    iter.remove();
11088                }
11089            }
11090
11091            // Add the package's KeySets to the global KeySetManagerService
11092            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11093            ksms.addScannedPackageLPw(pkg);
11094
11095            int N = pkg.providers.size();
11096            StringBuilder r = null;
11097            int i;
11098            for (i=0; i<N; i++) {
11099                PackageParser.Provider p = pkg.providers.get(i);
11100                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11101                        p.info.processName);
11102                mProviders.addProvider(p);
11103                p.syncable = p.info.isSyncable;
11104                if (p.info.authority != null) {
11105                    String names[] = p.info.authority.split(";");
11106                    p.info.authority = null;
11107                    for (int j = 0; j < names.length; j++) {
11108                        if (j == 1 && p.syncable) {
11109                            // We only want the first authority for a provider to possibly be
11110                            // syncable, so if we already added this provider using a different
11111                            // authority clear the syncable flag. We copy the provider before
11112                            // changing it because the mProviders object contains a reference
11113                            // to a provider that we don't want to change.
11114                            // Only do this for the second authority since the resulting provider
11115                            // object can be the same for all future authorities for this provider.
11116                            p = new PackageParser.Provider(p);
11117                            p.syncable = false;
11118                        }
11119                        if (!mProvidersByAuthority.containsKey(names[j])) {
11120                            mProvidersByAuthority.put(names[j], p);
11121                            if (p.info.authority == null) {
11122                                p.info.authority = names[j];
11123                            } else {
11124                                p.info.authority = p.info.authority + ";" + names[j];
11125                            }
11126                            if (DEBUG_PACKAGE_SCANNING) {
11127                                if (chatty)
11128                                    Log.d(TAG, "Registered content provider: " + names[j]
11129                                            + ", className = " + p.info.name + ", isSyncable = "
11130                                            + p.info.isSyncable);
11131                            }
11132                        } else {
11133                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11134                            Slog.w(TAG, "Skipping provider name " + names[j] +
11135                                    " (in package " + pkg.applicationInfo.packageName +
11136                                    "): name already used by "
11137                                    + ((other != null && other.getComponentName() != null)
11138                                            ? other.getComponentName().getPackageName() : "?"));
11139                        }
11140                    }
11141                }
11142                if (chatty) {
11143                    if (r == null) {
11144                        r = new StringBuilder(256);
11145                    } else {
11146                        r.append(' ');
11147                    }
11148                    r.append(p.info.name);
11149                }
11150            }
11151            if (r != null) {
11152                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11153            }
11154
11155            N = pkg.services.size();
11156            r = null;
11157            for (i=0; i<N; i++) {
11158                PackageParser.Service s = pkg.services.get(i);
11159                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11160                        s.info.processName);
11161                mServices.addService(s);
11162                if (chatty) {
11163                    if (r == null) {
11164                        r = new StringBuilder(256);
11165                    } else {
11166                        r.append(' ');
11167                    }
11168                    r.append(s.info.name);
11169                }
11170            }
11171            if (r != null) {
11172                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11173            }
11174
11175            N = pkg.receivers.size();
11176            r = null;
11177            for (i=0; i<N; i++) {
11178                PackageParser.Activity a = pkg.receivers.get(i);
11179                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11180                        a.info.processName);
11181                mReceivers.addActivity(a, "receiver");
11182                if (chatty) {
11183                    if (r == null) {
11184                        r = new StringBuilder(256);
11185                    } else {
11186                        r.append(' ');
11187                    }
11188                    r.append(a.info.name);
11189                }
11190            }
11191            if (r != null) {
11192                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11193            }
11194
11195            N = pkg.activities.size();
11196            r = null;
11197            for (i=0; i<N; i++) {
11198                PackageParser.Activity a = pkg.activities.get(i);
11199                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11200                        a.info.processName);
11201                mActivities.addActivity(a, "activity");
11202                if (chatty) {
11203                    if (r == null) {
11204                        r = new StringBuilder(256);
11205                    } else {
11206                        r.append(' ');
11207                    }
11208                    r.append(a.info.name);
11209                }
11210            }
11211            if (r != null) {
11212                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11213            }
11214
11215            N = pkg.permissionGroups.size();
11216            r = null;
11217            for (i=0; i<N; i++) {
11218                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11219                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11220                final String curPackageName = cur == null ? null : cur.info.packageName;
11221                // Dont allow ephemeral apps to define new permission groups.
11222                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11223                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11224                            + pg.info.packageName
11225                            + " ignored: instant apps cannot define new permission groups.");
11226                    continue;
11227                }
11228                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11229                if (cur == null || isPackageUpdate) {
11230                    mPermissionGroups.put(pg.info.name, pg);
11231                    if (chatty) {
11232                        if (r == null) {
11233                            r = new StringBuilder(256);
11234                        } else {
11235                            r.append(' ');
11236                        }
11237                        if (isPackageUpdate) {
11238                            r.append("UPD:");
11239                        }
11240                        r.append(pg.info.name);
11241                    }
11242                } else {
11243                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11244                            + pg.info.packageName + " ignored: original from "
11245                            + cur.info.packageName);
11246                    if (chatty) {
11247                        if (r == null) {
11248                            r = new StringBuilder(256);
11249                        } else {
11250                            r.append(' ');
11251                        }
11252                        r.append("DUP:");
11253                        r.append(pg.info.name);
11254                    }
11255                }
11256            }
11257            if (r != null) {
11258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11259            }
11260
11261            N = pkg.permissions.size();
11262            r = null;
11263            for (i=0; i<N; i++) {
11264                PackageParser.Permission p = pkg.permissions.get(i);
11265
11266                // Dont allow ephemeral apps to define new permissions.
11267                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11268                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11269                            + p.info.packageName
11270                            + " ignored: instant apps cannot define new permissions.");
11271                    continue;
11272                }
11273
11274                // Assume by default that we did not install this permission into the system.
11275                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11276
11277                // Now that permission groups have a special meaning, we ignore permission
11278                // groups for legacy apps to prevent unexpected behavior. In particular,
11279                // permissions for one app being granted to someone just because they happen
11280                // to be in a group defined by another app (before this had no implications).
11281                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11282                    p.group = mPermissionGroups.get(p.info.group);
11283                    // Warn for a permission in an unknown group.
11284                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11285                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11286                                + p.info.packageName + " in an unknown group " + p.info.group);
11287                    }
11288                }
11289
11290                ArrayMap<String, BasePermission> permissionMap =
11291                        p.tree ? mSettings.mPermissionTrees
11292                                : mSettings.mPermissions;
11293                BasePermission bp = permissionMap.get(p.info.name);
11294
11295                // Allow system apps to redefine non-system permissions
11296                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11297                    final boolean currentOwnerIsSystem = (bp.perm != null
11298                            && isSystemApp(bp.perm.owner));
11299                    if (isSystemApp(p.owner)) {
11300                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11301                            // It's a built-in permission and no owner, take ownership now
11302                            bp.packageSetting = pkgSetting;
11303                            bp.perm = p;
11304                            bp.uid = pkg.applicationInfo.uid;
11305                            bp.sourcePackage = p.info.packageName;
11306                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11307                        } else if (!currentOwnerIsSystem) {
11308                            String msg = "New decl " + p.owner + " of permission  "
11309                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11310                            reportSettingsProblem(Log.WARN, msg);
11311                            bp = null;
11312                        }
11313                    }
11314                }
11315
11316                if (bp == null) {
11317                    bp = new BasePermission(p.info.name, p.info.packageName,
11318                            BasePermission.TYPE_NORMAL);
11319                    permissionMap.put(p.info.name, bp);
11320                }
11321
11322                if (bp.perm == null) {
11323                    if (bp.sourcePackage == null
11324                            || bp.sourcePackage.equals(p.info.packageName)) {
11325                        BasePermission tree = findPermissionTreeLP(p.info.name);
11326                        if (tree == null
11327                                || tree.sourcePackage.equals(p.info.packageName)) {
11328                            bp.packageSetting = pkgSetting;
11329                            bp.perm = p;
11330                            bp.uid = pkg.applicationInfo.uid;
11331                            bp.sourcePackage = p.info.packageName;
11332                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11333                            if (chatty) {
11334                                if (r == null) {
11335                                    r = new StringBuilder(256);
11336                                } else {
11337                                    r.append(' ');
11338                                }
11339                                r.append(p.info.name);
11340                            }
11341                        } else {
11342                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11343                                    + p.info.packageName + " ignored: base tree "
11344                                    + tree.name + " is from package "
11345                                    + tree.sourcePackage);
11346                        }
11347                    } else {
11348                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11349                                + p.info.packageName + " ignored: original from "
11350                                + bp.sourcePackage);
11351                    }
11352                } else if (chatty) {
11353                    if (r == null) {
11354                        r = new StringBuilder(256);
11355                    } else {
11356                        r.append(' ');
11357                    }
11358                    r.append("DUP:");
11359                    r.append(p.info.name);
11360                }
11361                if (bp.perm == p) {
11362                    bp.protectionLevel = p.info.protectionLevel;
11363                }
11364            }
11365
11366            if (r != null) {
11367                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11368            }
11369
11370            N = pkg.instrumentation.size();
11371            r = null;
11372            for (i=0; i<N; i++) {
11373                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11374                a.info.packageName = pkg.applicationInfo.packageName;
11375                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11376                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11377                a.info.splitNames = pkg.splitNames;
11378                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11379                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11380                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11381                a.info.dataDir = pkg.applicationInfo.dataDir;
11382                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11383                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11384                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11385                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11386                mInstrumentation.put(a.getComponentName(), a);
11387                if (chatty) {
11388                    if (r == null) {
11389                        r = new StringBuilder(256);
11390                    } else {
11391                        r.append(' ');
11392                    }
11393                    r.append(a.info.name);
11394                }
11395            }
11396            if (r != null) {
11397                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11398            }
11399
11400            if (pkg.protectedBroadcasts != null) {
11401                N = pkg.protectedBroadcasts.size();
11402                for (i=0; i<N; i++) {
11403                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11404                }
11405            }
11406        }
11407
11408        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11409    }
11410
11411    /**
11412     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11413     * is derived purely on the basis of the contents of {@code scanFile} and
11414     * {@code cpuAbiOverride}.
11415     *
11416     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11417     */
11418    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11419                                 String cpuAbiOverride, boolean extractLibs,
11420                                 File appLib32InstallDir)
11421            throws PackageManagerException {
11422        // Give ourselves some initial paths; we'll come back for another
11423        // pass once we've determined ABI below.
11424        setNativeLibraryPaths(pkg, appLib32InstallDir);
11425
11426        // We would never need to extract libs for forward-locked and external packages,
11427        // since the container service will do it for us. We shouldn't attempt to
11428        // extract libs from system app when it was not updated.
11429        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11430                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11431            extractLibs = false;
11432        }
11433
11434        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11435        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11436
11437        NativeLibraryHelper.Handle handle = null;
11438        try {
11439            handle = NativeLibraryHelper.Handle.create(pkg);
11440            // TODO(multiArch): This can be null for apps that didn't go through the
11441            // usual installation process. We can calculate it again, like we
11442            // do during install time.
11443            //
11444            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11445            // unnecessary.
11446            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11447
11448            // Null out the abis so that they can be recalculated.
11449            pkg.applicationInfo.primaryCpuAbi = null;
11450            pkg.applicationInfo.secondaryCpuAbi = null;
11451            if (isMultiArch(pkg.applicationInfo)) {
11452                // Warn if we've set an abiOverride for multi-lib packages..
11453                // By definition, we need to copy both 32 and 64 bit libraries for
11454                // such packages.
11455                if (pkg.cpuAbiOverride != null
11456                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11457                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11458                }
11459
11460                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11461                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11462                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11463                    if (extractLibs) {
11464                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11465                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11466                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11467                                useIsaSpecificSubdirs);
11468                    } else {
11469                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11470                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11471                    }
11472                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11473                }
11474
11475                // Shared library native code should be in the APK zip aligned
11476                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11477                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11478                            "Shared library native lib extraction not supported");
11479                }
11480
11481                maybeThrowExceptionForMultiArchCopy(
11482                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11483
11484                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11485                    if (extractLibs) {
11486                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11487                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11488                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11489                                useIsaSpecificSubdirs);
11490                    } else {
11491                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11492                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11493                    }
11494                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11495                }
11496
11497                maybeThrowExceptionForMultiArchCopy(
11498                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11499
11500                if (abi64 >= 0) {
11501                    // Shared library native libs should be in the APK zip aligned
11502                    if (extractLibs && pkg.isLibrary()) {
11503                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11504                                "Shared library native lib extraction not supported");
11505                    }
11506                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11507                }
11508
11509                if (abi32 >= 0) {
11510                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11511                    if (abi64 >= 0) {
11512                        if (pkg.use32bitAbi) {
11513                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11514                            pkg.applicationInfo.primaryCpuAbi = abi;
11515                        } else {
11516                            pkg.applicationInfo.secondaryCpuAbi = abi;
11517                        }
11518                    } else {
11519                        pkg.applicationInfo.primaryCpuAbi = abi;
11520                    }
11521                }
11522            } else {
11523                String[] abiList = (cpuAbiOverride != null) ?
11524                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11525
11526                // Enable gross and lame hacks for apps that are built with old
11527                // SDK tools. We must scan their APKs for renderscript bitcode and
11528                // not launch them if it's present. Don't bother checking on devices
11529                // that don't have 64 bit support.
11530                boolean needsRenderScriptOverride = false;
11531                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11532                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11533                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11534                    needsRenderScriptOverride = true;
11535                }
11536
11537                final int copyRet;
11538                if (extractLibs) {
11539                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11540                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11541                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11542                } else {
11543                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11544                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11545                }
11546                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11547
11548                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11549                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11550                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11551                }
11552
11553                if (copyRet >= 0) {
11554                    // Shared libraries that have native libs must be multi-architecture
11555                    if (pkg.isLibrary()) {
11556                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11557                                "Shared library with native libs must be multiarch");
11558                    }
11559                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11560                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11561                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11562                } else if (needsRenderScriptOverride) {
11563                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11564                }
11565            }
11566        } catch (IOException ioe) {
11567            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11568        } finally {
11569            IoUtils.closeQuietly(handle);
11570        }
11571
11572        // Now that we've calculated the ABIs and determined if it's an internal app,
11573        // we will go ahead and populate the nativeLibraryPath.
11574        setNativeLibraryPaths(pkg, appLib32InstallDir);
11575    }
11576
11577    /**
11578     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11579     * i.e, so that all packages can be run inside a single process if required.
11580     *
11581     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11582     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11583     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11584     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11585     * updating a package that belongs to a shared user.
11586     *
11587     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11588     * adds unnecessary complexity.
11589     */
11590    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11591            PackageParser.Package scannedPackage) {
11592        String requiredInstructionSet = null;
11593        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11594            requiredInstructionSet = VMRuntime.getInstructionSet(
11595                     scannedPackage.applicationInfo.primaryCpuAbi);
11596        }
11597
11598        PackageSetting requirer = null;
11599        for (PackageSetting ps : packagesForUser) {
11600            // If packagesForUser contains scannedPackage, we skip it. This will happen
11601            // when scannedPackage is an update of an existing package. Without this check,
11602            // we will never be able to change the ABI of any package belonging to a shared
11603            // user, even if it's compatible with other packages.
11604            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11605                if (ps.primaryCpuAbiString == null) {
11606                    continue;
11607                }
11608
11609                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11610                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11611                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11612                    // this but there's not much we can do.
11613                    String errorMessage = "Instruction set mismatch, "
11614                            + ((requirer == null) ? "[caller]" : requirer)
11615                            + " requires " + requiredInstructionSet + " whereas " + ps
11616                            + " requires " + instructionSet;
11617                    Slog.w(TAG, errorMessage);
11618                }
11619
11620                if (requiredInstructionSet == null) {
11621                    requiredInstructionSet = instructionSet;
11622                    requirer = ps;
11623                }
11624            }
11625        }
11626
11627        if (requiredInstructionSet != null) {
11628            String adjustedAbi;
11629            if (requirer != null) {
11630                // requirer != null implies that either scannedPackage was null or that scannedPackage
11631                // did not require an ABI, in which case we have to adjust scannedPackage to match
11632                // the ABI of the set (which is the same as requirer's ABI)
11633                adjustedAbi = requirer.primaryCpuAbiString;
11634                if (scannedPackage != null) {
11635                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11636                }
11637            } else {
11638                // requirer == null implies that we're updating all ABIs in the set to
11639                // match scannedPackage.
11640                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11641            }
11642
11643            for (PackageSetting ps : packagesForUser) {
11644                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11645                    if (ps.primaryCpuAbiString != null) {
11646                        continue;
11647                    }
11648
11649                    ps.primaryCpuAbiString = adjustedAbi;
11650                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11651                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11652                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11653                        if (DEBUG_ABI_SELECTION) {
11654                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11655                                    + " (requirer="
11656                                    + (requirer != null ? requirer.pkg : "null")
11657                                    + ", scannedPackage="
11658                                    + (scannedPackage != null ? scannedPackage : "null")
11659                                    + ")");
11660                        }
11661                        try {
11662                            mInstaller.rmdex(ps.codePathString,
11663                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11664                        } catch (InstallerException ignored) {
11665                        }
11666                    }
11667                }
11668            }
11669        }
11670    }
11671
11672    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11673        synchronized (mPackages) {
11674            mResolverReplaced = true;
11675            // Set up information for custom user intent resolution activity.
11676            mResolveActivity.applicationInfo = pkg.applicationInfo;
11677            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11678            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11679            mResolveActivity.processName = pkg.applicationInfo.packageName;
11680            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11681            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11682                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11683            mResolveActivity.theme = 0;
11684            mResolveActivity.exported = true;
11685            mResolveActivity.enabled = true;
11686            mResolveInfo.activityInfo = mResolveActivity;
11687            mResolveInfo.priority = 0;
11688            mResolveInfo.preferredOrder = 0;
11689            mResolveInfo.match = 0;
11690            mResolveComponentName = mCustomResolverComponentName;
11691            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11692                    mResolveComponentName);
11693        }
11694    }
11695
11696    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11697        if (installerActivity == null) {
11698            if (DEBUG_EPHEMERAL) {
11699                Slog.d(TAG, "Clear ephemeral installer activity");
11700            }
11701            mInstantAppInstallerActivity = null;
11702            return;
11703        }
11704
11705        if (DEBUG_EPHEMERAL) {
11706            Slog.d(TAG, "Set ephemeral installer activity: "
11707                    + installerActivity.getComponentName());
11708        }
11709        // Set up information for ephemeral installer activity
11710        mInstantAppInstallerActivity = installerActivity;
11711        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11712                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11713        mInstantAppInstallerActivity.exported = true;
11714        mInstantAppInstallerActivity.enabled = true;
11715        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11716        mInstantAppInstallerInfo.priority = 0;
11717        mInstantAppInstallerInfo.preferredOrder = 1;
11718        mInstantAppInstallerInfo.isDefault = true;
11719        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11720                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11721    }
11722
11723    private static String calculateBundledApkRoot(final String codePathString) {
11724        final File codePath = new File(codePathString);
11725        final File codeRoot;
11726        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11727            codeRoot = Environment.getRootDirectory();
11728        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11729            codeRoot = Environment.getOemDirectory();
11730        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11731            codeRoot = Environment.getVendorDirectory();
11732        } else {
11733            // Unrecognized code path; take its top real segment as the apk root:
11734            // e.g. /something/app/blah.apk => /something
11735            try {
11736                File f = codePath.getCanonicalFile();
11737                File parent = f.getParentFile();    // non-null because codePath is a file
11738                File tmp;
11739                while ((tmp = parent.getParentFile()) != null) {
11740                    f = parent;
11741                    parent = tmp;
11742                }
11743                codeRoot = f;
11744                Slog.w(TAG, "Unrecognized code path "
11745                        + codePath + " - using " + codeRoot);
11746            } catch (IOException e) {
11747                // Can't canonicalize the code path -- shenanigans?
11748                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11749                return Environment.getRootDirectory().getPath();
11750            }
11751        }
11752        return codeRoot.getPath();
11753    }
11754
11755    /**
11756     * Derive and set the location of native libraries for the given package,
11757     * which varies depending on where and how the package was installed.
11758     */
11759    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11760        final ApplicationInfo info = pkg.applicationInfo;
11761        final String codePath = pkg.codePath;
11762        final File codeFile = new File(codePath);
11763        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11764        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11765
11766        info.nativeLibraryRootDir = null;
11767        info.nativeLibraryRootRequiresIsa = false;
11768        info.nativeLibraryDir = null;
11769        info.secondaryNativeLibraryDir = null;
11770
11771        if (isApkFile(codeFile)) {
11772            // Monolithic install
11773            if (bundledApp) {
11774                // If "/system/lib64/apkname" exists, assume that is the per-package
11775                // native library directory to use; otherwise use "/system/lib/apkname".
11776                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11777                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11778                        getPrimaryInstructionSet(info));
11779
11780                // This is a bundled system app so choose the path based on the ABI.
11781                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11782                // is just the default path.
11783                final String apkName = deriveCodePathName(codePath);
11784                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11785                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11786                        apkName).getAbsolutePath();
11787
11788                if (info.secondaryCpuAbi != null) {
11789                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11790                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11791                            secondaryLibDir, apkName).getAbsolutePath();
11792                }
11793            } else if (asecApp) {
11794                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11795                        .getAbsolutePath();
11796            } else {
11797                final String apkName = deriveCodePathName(codePath);
11798                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11799                        .getAbsolutePath();
11800            }
11801
11802            info.nativeLibraryRootRequiresIsa = false;
11803            info.nativeLibraryDir = info.nativeLibraryRootDir;
11804        } else {
11805            // Cluster install
11806            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11807            info.nativeLibraryRootRequiresIsa = true;
11808
11809            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11810                    getPrimaryInstructionSet(info)).getAbsolutePath();
11811
11812            if (info.secondaryCpuAbi != null) {
11813                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11814                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11815            }
11816        }
11817    }
11818
11819    /**
11820     * Calculate the abis and roots for a bundled app. These can uniquely
11821     * be determined from the contents of the system partition, i.e whether
11822     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11823     * of this information, and instead assume that the system was built
11824     * sensibly.
11825     */
11826    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11827                                           PackageSetting pkgSetting) {
11828        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11829
11830        // If "/system/lib64/apkname" exists, assume that is the per-package
11831        // native library directory to use; otherwise use "/system/lib/apkname".
11832        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11833        setBundledAppAbi(pkg, apkRoot, apkName);
11834        // pkgSetting might be null during rescan following uninstall of updates
11835        // to a bundled app, so accommodate that possibility.  The settings in
11836        // that case will be established later from the parsed package.
11837        //
11838        // If the settings aren't null, sync them up with what we've just derived.
11839        // note that apkRoot isn't stored in the package settings.
11840        if (pkgSetting != null) {
11841            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11842            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11843        }
11844    }
11845
11846    /**
11847     * Deduces the ABI of a bundled app and sets the relevant fields on the
11848     * parsed pkg object.
11849     *
11850     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11851     *        under which system libraries are installed.
11852     * @param apkName the name of the installed package.
11853     */
11854    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11855        final File codeFile = new File(pkg.codePath);
11856
11857        final boolean has64BitLibs;
11858        final boolean has32BitLibs;
11859        if (isApkFile(codeFile)) {
11860            // Monolithic install
11861            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11862            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11863        } else {
11864            // Cluster install
11865            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11866            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11867                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11868                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11869                has64BitLibs = (new File(rootDir, isa)).exists();
11870            } else {
11871                has64BitLibs = false;
11872            }
11873            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11874                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11875                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11876                has32BitLibs = (new File(rootDir, isa)).exists();
11877            } else {
11878                has32BitLibs = false;
11879            }
11880        }
11881
11882        if (has64BitLibs && !has32BitLibs) {
11883            // The package has 64 bit libs, but not 32 bit libs. Its primary
11884            // ABI should be 64 bit. We can safely assume here that the bundled
11885            // native libraries correspond to the most preferred ABI in the list.
11886
11887            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11888            pkg.applicationInfo.secondaryCpuAbi = null;
11889        } else if (has32BitLibs && !has64BitLibs) {
11890            // The package has 32 bit libs but not 64 bit libs. Its primary
11891            // ABI should be 32 bit.
11892
11893            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11894            pkg.applicationInfo.secondaryCpuAbi = null;
11895        } else if (has32BitLibs && has64BitLibs) {
11896            // The application has both 64 and 32 bit bundled libraries. We check
11897            // here that the app declares multiArch support, and warn if it doesn't.
11898            //
11899            // We will be lenient here and record both ABIs. The primary will be the
11900            // ABI that's higher on the list, i.e, a device that's configured to prefer
11901            // 64 bit apps will see a 64 bit primary ABI,
11902
11903            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11904                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11905            }
11906
11907            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11908                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11909                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11910            } else {
11911                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11912                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11913            }
11914        } else {
11915            pkg.applicationInfo.primaryCpuAbi = null;
11916            pkg.applicationInfo.secondaryCpuAbi = null;
11917        }
11918    }
11919
11920    private void killApplication(String pkgName, int appId, String reason) {
11921        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11922    }
11923
11924    private void killApplication(String pkgName, int appId, int userId, String reason) {
11925        // Request the ActivityManager to kill the process(only for existing packages)
11926        // so that we do not end up in a confused state while the user is still using the older
11927        // version of the application while the new one gets installed.
11928        final long token = Binder.clearCallingIdentity();
11929        try {
11930            IActivityManager am = ActivityManager.getService();
11931            if (am != null) {
11932                try {
11933                    am.killApplication(pkgName, appId, userId, reason);
11934                } catch (RemoteException e) {
11935                }
11936            }
11937        } finally {
11938            Binder.restoreCallingIdentity(token);
11939        }
11940    }
11941
11942    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11943        // Remove the parent package setting
11944        PackageSetting ps = (PackageSetting) pkg.mExtras;
11945        if (ps != null) {
11946            removePackageLI(ps, chatty);
11947        }
11948        // Remove the child package setting
11949        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11950        for (int i = 0; i < childCount; i++) {
11951            PackageParser.Package childPkg = pkg.childPackages.get(i);
11952            ps = (PackageSetting) childPkg.mExtras;
11953            if (ps != null) {
11954                removePackageLI(ps, chatty);
11955            }
11956        }
11957    }
11958
11959    void removePackageLI(PackageSetting ps, boolean chatty) {
11960        if (DEBUG_INSTALL) {
11961            if (chatty)
11962                Log.d(TAG, "Removing package " + ps.name);
11963        }
11964
11965        // writer
11966        synchronized (mPackages) {
11967            mPackages.remove(ps.name);
11968            final PackageParser.Package pkg = ps.pkg;
11969            if (pkg != null) {
11970                cleanPackageDataStructuresLILPw(pkg, chatty);
11971            }
11972        }
11973    }
11974
11975    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11976        if (DEBUG_INSTALL) {
11977            if (chatty)
11978                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11979        }
11980
11981        // writer
11982        synchronized (mPackages) {
11983            // Remove the parent package
11984            mPackages.remove(pkg.applicationInfo.packageName);
11985            cleanPackageDataStructuresLILPw(pkg, chatty);
11986
11987            // Remove the child packages
11988            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11989            for (int i = 0; i < childCount; i++) {
11990                PackageParser.Package childPkg = pkg.childPackages.get(i);
11991                mPackages.remove(childPkg.applicationInfo.packageName);
11992                cleanPackageDataStructuresLILPw(childPkg, chatty);
11993            }
11994        }
11995    }
11996
11997    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11998        int N = pkg.providers.size();
11999        StringBuilder r = null;
12000        int i;
12001        for (i=0; i<N; i++) {
12002            PackageParser.Provider p = pkg.providers.get(i);
12003            mProviders.removeProvider(p);
12004            if (p.info.authority == null) {
12005
12006                /* There was another ContentProvider with this authority when
12007                 * this app was installed so this authority is null,
12008                 * Ignore it as we don't have to unregister the provider.
12009                 */
12010                continue;
12011            }
12012            String names[] = p.info.authority.split(";");
12013            for (int j = 0; j < names.length; j++) {
12014                if (mProvidersByAuthority.get(names[j]) == p) {
12015                    mProvidersByAuthority.remove(names[j]);
12016                    if (DEBUG_REMOVE) {
12017                        if (chatty)
12018                            Log.d(TAG, "Unregistered content provider: " + names[j]
12019                                    + ", className = " + p.info.name + ", isSyncable = "
12020                                    + p.info.isSyncable);
12021                    }
12022                }
12023            }
12024            if (DEBUG_REMOVE && chatty) {
12025                if (r == null) {
12026                    r = new StringBuilder(256);
12027                } else {
12028                    r.append(' ');
12029                }
12030                r.append(p.info.name);
12031            }
12032        }
12033        if (r != null) {
12034            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12035        }
12036
12037        N = pkg.services.size();
12038        r = null;
12039        for (i=0; i<N; i++) {
12040            PackageParser.Service s = pkg.services.get(i);
12041            mServices.removeService(s);
12042            if (chatty) {
12043                if (r == null) {
12044                    r = new StringBuilder(256);
12045                } else {
12046                    r.append(' ');
12047                }
12048                r.append(s.info.name);
12049            }
12050        }
12051        if (r != null) {
12052            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12053        }
12054
12055        N = pkg.receivers.size();
12056        r = null;
12057        for (i=0; i<N; i++) {
12058            PackageParser.Activity a = pkg.receivers.get(i);
12059            mReceivers.removeActivity(a, "receiver");
12060            if (DEBUG_REMOVE && chatty) {
12061                if (r == null) {
12062                    r = new StringBuilder(256);
12063                } else {
12064                    r.append(' ');
12065                }
12066                r.append(a.info.name);
12067            }
12068        }
12069        if (r != null) {
12070            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12071        }
12072
12073        N = pkg.activities.size();
12074        r = null;
12075        for (i=0; i<N; i++) {
12076            PackageParser.Activity a = pkg.activities.get(i);
12077            mActivities.removeActivity(a, "activity");
12078            if (DEBUG_REMOVE && chatty) {
12079                if (r == null) {
12080                    r = new StringBuilder(256);
12081                } else {
12082                    r.append(' ');
12083                }
12084                r.append(a.info.name);
12085            }
12086        }
12087        if (r != null) {
12088            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12089        }
12090
12091        N = pkg.permissions.size();
12092        r = null;
12093        for (i=0; i<N; i++) {
12094            PackageParser.Permission p = pkg.permissions.get(i);
12095            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12096            if (bp == null) {
12097                bp = mSettings.mPermissionTrees.get(p.info.name);
12098            }
12099            if (bp != null && bp.perm == p) {
12100                bp.perm = null;
12101                if (DEBUG_REMOVE && chatty) {
12102                    if (r == null) {
12103                        r = new StringBuilder(256);
12104                    } else {
12105                        r.append(' ');
12106                    }
12107                    r.append(p.info.name);
12108                }
12109            }
12110            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12111                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12112                if (appOpPkgs != null) {
12113                    appOpPkgs.remove(pkg.packageName);
12114                }
12115            }
12116        }
12117        if (r != null) {
12118            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12119        }
12120
12121        N = pkg.requestedPermissions.size();
12122        r = null;
12123        for (i=0; i<N; i++) {
12124            String perm = pkg.requestedPermissions.get(i);
12125            BasePermission bp = mSettings.mPermissions.get(perm);
12126            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12127                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12128                if (appOpPkgs != null) {
12129                    appOpPkgs.remove(pkg.packageName);
12130                    if (appOpPkgs.isEmpty()) {
12131                        mAppOpPermissionPackages.remove(perm);
12132                    }
12133                }
12134            }
12135        }
12136        if (r != null) {
12137            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12138        }
12139
12140        N = pkg.instrumentation.size();
12141        r = null;
12142        for (i=0; i<N; i++) {
12143            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12144            mInstrumentation.remove(a.getComponentName());
12145            if (DEBUG_REMOVE && chatty) {
12146                if (r == null) {
12147                    r = new StringBuilder(256);
12148                } else {
12149                    r.append(' ');
12150                }
12151                r.append(a.info.name);
12152            }
12153        }
12154        if (r != null) {
12155            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12156        }
12157
12158        r = null;
12159        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12160            // Only system apps can hold shared libraries.
12161            if (pkg.libraryNames != null) {
12162                for (i = 0; i < pkg.libraryNames.size(); i++) {
12163                    String name = pkg.libraryNames.get(i);
12164                    if (removeSharedLibraryLPw(name, 0)) {
12165                        if (DEBUG_REMOVE && chatty) {
12166                            if (r == null) {
12167                                r = new StringBuilder(256);
12168                            } else {
12169                                r.append(' ');
12170                            }
12171                            r.append(name);
12172                        }
12173                    }
12174                }
12175            }
12176        }
12177
12178        r = null;
12179
12180        // Any package can hold static shared libraries.
12181        if (pkg.staticSharedLibName != null) {
12182            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12183                if (DEBUG_REMOVE && chatty) {
12184                    if (r == null) {
12185                        r = new StringBuilder(256);
12186                    } else {
12187                        r.append(' ');
12188                    }
12189                    r.append(pkg.staticSharedLibName);
12190                }
12191            }
12192        }
12193
12194        if (r != null) {
12195            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12196        }
12197    }
12198
12199    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12200        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12201            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12202                return true;
12203            }
12204        }
12205        return false;
12206    }
12207
12208    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12209    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12210    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12211
12212    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12213        // Update the parent permissions
12214        updatePermissionsLPw(pkg.packageName, pkg, flags);
12215        // Update the child permissions
12216        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12217        for (int i = 0; i < childCount; i++) {
12218            PackageParser.Package childPkg = pkg.childPackages.get(i);
12219            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12220        }
12221    }
12222
12223    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12224            int flags) {
12225        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12226        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12227    }
12228
12229    private void updatePermissionsLPw(String changingPkg,
12230            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12231        // Make sure there are no dangling permission trees.
12232        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12233        while (it.hasNext()) {
12234            final BasePermission bp = it.next();
12235            if (bp.packageSetting == null) {
12236                // We may not yet have parsed the package, so just see if
12237                // we still know about its settings.
12238                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12239            }
12240            if (bp.packageSetting == null) {
12241                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12242                        + " from package " + bp.sourcePackage);
12243                it.remove();
12244            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12245                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12246                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12247                            + " from package " + bp.sourcePackage);
12248                    flags |= UPDATE_PERMISSIONS_ALL;
12249                    it.remove();
12250                }
12251            }
12252        }
12253
12254        // Make sure all dynamic permissions have been assigned to a package,
12255        // and make sure there are no dangling permissions.
12256        it = mSettings.mPermissions.values().iterator();
12257        while (it.hasNext()) {
12258            final BasePermission bp = it.next();
12259            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12260                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12261                        + bp.name + " pkg=" + bp.sourcePackage
12262                        + " info=" + bp.pendingInfo);
12263                if (bp.packageSetting == null && bp.pendingInfo != null) {
12264                    final BasePermission tree = findPermissionTreeLP(bp.name);
12265                    if (tree != null && tree.perm != null) {
12266                        bp.packageSetting = tree.packageSetting;
12267                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12268                                new PermissionInfo(bp.pendingInfo));
12269                        bp.perm.info.packageName = tree.perm.info.packageName;
12270                        bp.perm.info.name = bp.name;
12271                        bp.uid = tree.uid;
12272                    }
12273                }
12274            }
12275            if (bp.packageSetting == null) {
12276                // We may not yet have parsed the package, so just see if
12277                // we still know about its settings.
12278                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12279            }
12280            if (bp.packageSetting == null) {
12281                Slog.w(TAG, "Removing dangling permission: " + bp.name
12282                        + " from package " + bp.sourcePackage);
12283                it.remove();
12284            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12285                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12286                    Slog.i(TAG, "Removing old permission: " + bp.name
12287                            + " from package " + bp.sourcePackage);
12288                    flags |= UPDATE_PERMISSIONS_ALL;
12289                    it.remove();
12290                }
12291            }
12292        }
12293
12294        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12295        // Now update the permissions for all packages, in particular
12296        // replace the granted permissions of the system packages.
12297        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12298            for (PackageParser.Package pkg : mPackages.values()) {
12299                if (pkg != pkgInfo) {
12300                    // Only replace for packages on requested volume
12301                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12302                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12303                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12304                    grantPermissionsLPw(pkg, replace, changingPkg);
12305                }
12306            }
12307        }
12308
12309        if (pkgInfo != null) {
12310            // Only replace for packages on requested volume
12311            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12312            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12313                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12314            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12315        }
12316        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12317    }
12318
12319    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12320            String packageOfInterest) {
12321        // IMPORTANT: There are two types of permissions: install and runtime.
12322        // Install time permissions are granted when the app is installed to
12323        // all device users and users added in the future. Runtime permissions
12324        // are granted at runtime explicitly to specific users. Normal and signature
12325        // protected permissions are install time permissions. Dangerous permissions
12326        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12327        // otherwise they are runtime permissions. This function does not manage
12328        // runtime permissions except for the case an app targeting Lollipop MR1
12329        // being upgraded to target a newer SDK, in which case dangerous permissions
12330        // are transformed from install time to runtime ones.
12331
12332        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12333        if (ps == null) {
12334            return;
12335        }
12336
12337        PermissionsState permissionsState = ps.getPermissionsState();
12338        PermissionsState origPermissions = permissionsState;
12339
12340        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12341
12342        boolean runtimePermissionsRevoked = false;
12343        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12344
12345        boolean changedInstallPermission = false;
12346
12347        if (replace) {
12348            ps.installPermissionsFixed = false;
12349            if (!ps.isSharedUser()) {
12350                origPermissions = new PermissionsState(permissionsState);
12351                permissionsState.reset();
12352            } else {
12353                // We need to know only about runtime permission changes since the
12354                // calling code always writes the install permissions state but
12355                // the runtime ones are written only if changed. The only cases of
12356                // changed runtime permissions here are promotion of an install to
12357                // runtime and revocation of a runtime from a shared user.
12358                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12359                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12360                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12361                    runtimePermissionsRevoked = true;
12362                }
12363            }
12364        }
12365
12366        permissionsState.setGlobalGids(mGlobalGids);
12367
12368        final int N = pkg.requestedPermissions.size();
12369        for (int i=0; i<N; i++) {
12370            final String name = pkg.requestedPermissions.get(i);
12371            final BasePermission bp = mSettings.mPermissions.get(name);
12372            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12373                    >= Build.VERSION_CODES.M;
12374
12375            if (DEBUG_INSTALL) {
12376                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12377            }
12378
12379            if (bp == null || bp.packageSetting == null) {
12380                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12381                    if (DEBUG_PERMISSIONS) {
12382                        Slog.i(TAG, "Unknown permission " + name
12383                                + " in package " + pkg.packageName);
12384                    }
12385                }
12386                continue;
12387            }
12388
12389
12390            // Limit ephemeral apps to ephemeral allowed permissions.
12391            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12392                if (DEBUG_PERMISSIONS) {
12393                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12394                            + pkg.packageName);
12395                }
12396                continue;
12397            }
12398
12399            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12400                if (DEBUG_PERMISSIONS) {
12401                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12402                            + pkg.packageName);
12403                }
12404                continue;
12405            }
12406
12407            final String perm = bp.name;
12408            boolean allowedSig = false;
12409            int grant = GRANT_DENIED;
12410
12411            // Keep track of app op permissions.
12412            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12413                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12414                if (pkgs == null) {
12415                    pkgs = new ArraySet<>();
12416                    mAppOpPermissionPackages.put(bp.name, pkgs);
12417                }
12418                pkgs.add(pkg.packageName);
12419            }
12420
12421            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12422            switch (level) {
12423                case PermissionInfo.PROTECTION_NORMAL: {
12424                    // For all apps normal permissions are install time ones.
12425                    grant = GRANT_INSTALL;
12426                } break;
12427
12428                case PermissionInfo.PROTECTION_DANGEROUS: {
12429                    // If a permission review is required for legacy apps we represent
12430                    // their permissions as always granted runtime ones since we need
12431                    // to keep the review required permission flag per user while an
12432                    // install permission's state is shared across all users.
12433                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12434                        // For legacy apps dangerous permissions are install time ones.
12435                        grant = GRANT_INSTALL;
12436                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12437                        // For legacy apps that became modern, install becomes runtime.
12438                        grant = GRANT_UPGRADE;
12439                    } else if (mPromoteSystemApps
12440                            && isSystemApp(ps)
12441                            && mExistingSystemPackages.contains(ps.name)) {
12442                        // For legacy system apps, install becomes runtime.
12443                        // We cannot check hasInstallPermission() for system apps since those
12444                        // permissions were granted implicitly and not persisted pre-M.
12445                        grant = GRANT_UPGRADE;
12446                    } else {
12447                        // For modern apps keep runtime permissions unchanged.
12448                        grant = GRANT_RUNTIME;
12449                    }
12450                } break;
12451
12452                case PermissionInfo.PROTECTION_SIGNATURE: {
12453                    // For all apps signature permissions are install time ones.
12454                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12455                    if (allowedSig) {
12456                        grant = GRANT_INSTALL;
12457                    }
12458                } break;
12459            }
12460
12461            if (DEBUG_PERMISSIONS) {
12462                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12463            }
12464
12465            if (grant != GRANT_DENIED) {
12466                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12467                    // If this is an existing, non-system package, then
12468                    // we can't add any new permissions to it.
12469                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12470                        // Except...  if this is a permission that was added
12471                        // to the platform (note: need to only do this when
12472                        // updating the platform).
12473                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12474                            grant = GRANT_DENIED;
12475                        }
12476                    }
12477                }
12478
12479                switch (grant) {
12480                    case GRANT_INSTALL: {
12481                        // Revoke this as runtime permission to handle the case of
12482                        // a runtime permission being downgraded to an install one.
12483                        // Also in permission review mode we keep dangerous permissions
12484                        // for legacy apps
12485                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12486                            if (origPermissions.getRuntimePermissionState(
12487                                    bp.name, userId) != null) {
12488                                // Revoke the runtime permission and clear the flags.
12489                                origPermissions.revokeRuntimePermission(bp, userId);
12490                                origPermissions.updatePermissionFlags(bp, userId,
12491                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12492                                // If we revoked a permission permission, we have to write.
12493                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12494                                        changedRuntimePermissionUserIds, userId);
12495                            }
12496                        }
12497                        // Grant an install permission.
12498                        if (permissionsState.grantInstallPermission(bp) !=
12499                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12500                            changedInstallPermission = true;
12501                        }
12502                    } break;
12503
12504                    case GRANT_RUNTIME: {
12505                        // Grant previously granted runtime permissions.
12506                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12507                            PermissionState permissionState = origPermissions
12508                                    .getRuntimePermissionState(bp.name, userId);
12509                            int flags = permissionState != null
12510                                    ? permissionState.getFlags() : 0;
12511                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12512                                // Don't propagate the permission in a permission review mode if
12513                                // the former was revoked, i.e. marked to not propagate on upgrade.
12514                                // Note that in a permission review mode install permissions are
12515                                // represented as constantly granted runtime ones since we need to
12516                                // keep a per user state associated with the permission. Also the
12517                                // revoke on upgrade flag is no longer applicable and is reset.
12518                                final boolean revokeOnUpgrade = (flags & PackageManager
12519                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12520                                if (revokeOnUpgrade) {
12521                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12522                                    // Since we changed the flags, we have to write.
12523                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12524                                            changedRuntimePermissionUserIds, userId);
12525                                }
12526                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12527                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12528                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12529                                        // If we cannot put the permission as it was,
12530                                        // we have to write.
12531                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12532                                                changedRuntimePermissionUserIds, userId);
12533                                    }
12534                                }
12535
12536                                // If the app supports runtime permissions no need for a review.
12537                                if (mPermissionReviewRequired
12538                                        && appSupportsRuntimePermissions
12539                                        && (flags & PackageManager
12540                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12541                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12542                                    // Since we changed the flags, we have to write.
12543                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12544                                            changedRuntimePermissionUserIds, userId);
12545                                }
12546                            } else if (mPermissionReviewRequired
12547                                    && !appSupportsRuntimePermissions) {
12548                                // For legacy apps that need a permission review, every new
12549                                // runtime permission is granted but it is pending a review.
12550                                // We also need to review only platform defined runtime
12551                                // permissions as these are the only ones the platform knows
12552                                // how to disable the API to simulate revocation as legacy
12553                                // apps don't expect to run with revoked permissions.
12554                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12555                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12556                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12557                                        // We changed the flags, hence have to write.
12558                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12559                                                changedRuntimePermissionUserIds, userId);
12560                                    }
12561                                }
12562                                if (permissionsState.grantRuntimePermission(bp, userId)
12563                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12564                                    // We changed the permission, hence have to write.
12565                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12566                                            changedRuntimePermissionUserIds, userId);
12567                                }
12568                            }
12569                            // Propagate the permission flags.
12570                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12571                        }
12572                    } break;
12573
12574                    case GRANT_UPGRADE: {
12575                        // Grant runtime permissions for a previously held install permission.
12576                        PermissionState permissionState = origPermissions
12577                                .getInstallPermissionState(bp.name);
12578                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12579
12580                        if (origPermissions.revokeInstallPermission(bp)
12581                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12582                            // We will be transferring the permission flags, so clear them.
12583                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12584                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12585                            changedInstallPermission = true;
12586                        }
12587
12588                        // If the permission is not to be promoted to runtime we ignore it and
12589                        // also its other flags as they are not applicable to install permissions.
12590                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12591                            for (int userId : currentUserIds) {
12592                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12593                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12594                                    // Transfer the permission flags.
12595                                    permissionsState.updatePermissionFlags(bp, userId,
12596                                            flags, flags);
12597                                    // If we granted the permission, we have to write.
12598                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12599                                            changedRuntimePermissionUserIds, userId);
12600                                }
12601                            }
12602                        }
12603                    } break;
12604
12605                    default: {
12606                        if (packageOfInterest == null
12607                                || packageOfInterest.equals(pkg.packageName)) {
12608                            if (DEBUG_PERMISSIONS) {
12609                                Slog.i(TAG, "Not granting permission " + perm
12610                                        + " to package " + pkg.packageName
12611                                        + " because it was previously installed without");
12612                            }
12613                        }
12614                    } break;
12615                }
12616            } else {
12617                if (permissionsState.revokeInstallPermission(bp) !=
12618                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12619                    // Also drop the permission flags.
12620                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12621                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12622                    changedInstallPermission = true;
12623                    Slog.i(TAG, "Un-granting permission " + perm
12624                            + " from package " + pkg.packageName
12625                            + " (protectionLevel=" + bp.protectionLevel
12626                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12627                            + ")");
12628                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12629                    // Don't print warning for app op permissions, since it is fine for them
12630                    // not to be granted, there is a UI for the user to decide.
12631                    if (DEBUG_PERMISSIONS
12632                            && (packageOfInterest == null
12633                                    || packageOfInterest.equals(pkg.packageName))) {
12634                        Slog.i(TAG, "Not granting permission " + perm
12635                                + " to package " + pkg.packageName
12636                                + " (protectionLevel=" + bp.protectionLevel
12637                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12638                                + ")");
12639                    }
12640                }
12641            }
12642        }
12643
12644        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12645                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12646            // This is the first that we have heard about this package, so the
12647            // permissions we have now selected are fixed until explicitly
12648            // changed.
12649            ps.installPermissionsFixed = true;
12650        }
12651
12652        // Persist the runtime permissions state for users with changes. If permissions
12653        // were revoked because no app in the shared user declares them we have to
12654        // write synchronously to avoid losing runtime permissions state.
12655        for (int userId : changedRuntimePermissionUserIds) {
12656            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12657        }
12658    }
12659
12660    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12661        boolean allowed = false;
12662        final int NP = PackageParser.NEW_PERMISSIONS.length;
12663        for (int ip=0; ip<NP; ip++) {
12664            final PackageParser.NewPermissionInfo npi
12665                    = PackageParser.NEW_PERMISSIONS[ip];
12666            if (npi.name.equals(perm)
12667                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12668                allowed = true;
12669                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12670                        + pkg.packageName);
12671                break;
12672            }
12673        }
12674        return allowed;
12675    }
12676
12677    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12678            BasePermission bp, PermissionsState origPermissions) {
12679        boolean privilegedPermission = (bp.protectionLevel
12680                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12681        boolean privappPermissionsDisable =
12682                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12683        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12684        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12685        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12686                && !platformPackage && platformPermission) {
12687            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12688                    .getPrivAppPermissions(pkg.packageName);
12689            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12690            if (!whitelisted) {
12691                Slog.w(TAG, "Privileged permission " + perm + " for package "
12692                        + pkg.packageName + " - not in privapp-permissions whitelist");
12693                // Only report violations for apps on system image
12694                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12695                    if (mPrivappPermissionsViolations == null) {
12696                        mPrivappPermissionsViolations = new ArraySet<>();
12697                    }
12698                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12699                }
12700                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12701                    return false;
12702                }
12703            }
12704        }
12705        boolean allowed = (compareSignatures(
12706                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12707                        == PackageManager.SIGNATURE_MATCH)
12708                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12709                        == PackageManager.SIGNATURE_MATCH);
12710        if (!allowed && privilegedPermission) {
12711            if (isSystemApp(pkg)) {
12712                // For updated system applications, a system permission
12713                // is granted only if it had been defined by the original application.
12714                if (pkg.isUpdatedSystemApp()) {
12715                    final PackageSetting sysPs = mSettings
12716                            .getDisabledSystemPkgLPr(pkg.packageName);
12717                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12718                        // If the original was granted this permission, we take
12719                        // that grant decision as read and propagate it to the
12720                        // update.
12721                        if (sysPs.isPrivileged()) {
12722                            allowed = true;
12723                        }
12724                    } else {
12725                        // The system apk may have been updated with an older
12726                        // version of the one on the data partition, but which
12727                        // granted a new system permission that it didn't have
12728                        // before.  In this case we do want to allow the app to
12729                        // now get the new permission if the ancestral apk is
12730                        // privileged to get it.
12731                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12732                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12733                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12734                                    allowed = true;
12735                                    break;
12736                                }
12737                            }
12738                        }
12739                        // Also if a privileged parent package on the system image or any of
12740                        // its children requested a privileged permission, the updated child
12741                        // packages can also get the permission.
12742                        if (pkg.parentPackage != null) {
12743                            final PackageSetting disabledSysParentPs = mSettings
12744                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12745                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12746                                    && disabledSysParentPs.isPrivileged()) {
12747                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12748                                    allowed = true;
12749                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12750                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12751                                    for (int i = 0; i < count; i++) {
12752                                        PackageParser.Package disabledSysChildPkg =
12753                                                disabledSysParentPs.pkg.childPackages.get(i);
12754                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12755                                                perm)) {
12756                                            allowed = true;
12757                                            break;
12758                                        }
12759                                    }
12760                                }
12761                            }
12762                        }
12763                    }
12764                } else {
12765                    allowed = isPrivilegedApp(pkg);
12766                }
12767            }
12768        }
12769        if (!allowed) {
12770            if (!allowed && (bp.protectionLevel
12771                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12772                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12773                // If this was a previously normal/dangerous permission that got moved
12774                // to a system permission as part of the runtime permission redesign, then
12775                // we still want to blindly grant it to old apps.
12776                allowed = true;
12777            }
12778            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12779                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12780                // If this permission is to be granted to the system installer and
12781                // this app is an installer, then it gets the permission.
12782                allowed = true;
12783            }
12784            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12785                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12786                // If this permission is to be granted to the system verifier and
12787                // this app is a verifier, then it gets the permission.
12788                allowed = true;
12789            }
12790            if (!allowed && (bp.protectionLevel
12791                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12792                    && isSystemApp(pkg)) {
12793                // Any pre-installed system app is allowed to get this permission.
12794                allowed = true;
12795            }
12796            if (!allowed && (bp.protectionLevel
12797                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12798                // For development permissions, a development permission
12799                // is granted only if it was already granted.
12800                allowed = origPermissions.hasInstallPermission(perm);
12801            }
12802            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12803                    && pkg.packageName.equals(mSetupWizardPackage)) {
12804                // If this permission is to be granted to the system setup wizard and
12805                // this app is a setup wizard, then it gets the permission.
12806                allowed = true;
12807            }
12808        }
12809        return allowed;
12810    }
12811
12812    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12813        final int permCount = pkg.requestedPermissions.size();
12814        for (int j = 0; j < permCount; j++) {
12815            String requestedPermission = pkg.requestedPermissions.get(j);
12816            if (permission.equals(requestedPermission)) {
12817                return true;
12818            }
12819        }
12820        return false;
12821    }
12822
12823    final class ActivityIntentResolver
12824            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12825        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12826                boolean defaultOnly, int userId) {
12827            if (!sUserManager.exists(userId)) return null;
12828            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12829            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12830        }
12831
12832        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12833                int userId) {
12834            if (!sUserManager.exists(userId)) return null;
12835            mFlags = flags;
12836            return super.queryIntent(intent, resolvedType,
12837                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12838                    userId);
12839        }
12840
12841        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12842                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12843            if (!sUserManager.exists(userId)) return null;
12844            if (packageActivities == null) {
12845                return null;
12846            }
12847            mFlags = flags;
12848            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12849            final int N = packageActivities.size();
12850            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12851                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12852
12853            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12854            for (int i = 0; i < N; ++i) {
12855                intentFilters = packageActivities.get(i).intents;
12856                if (intentFilters != null && intentFilters.size() > 0) {
12857                    PackageParser.ActivityIntentInfo[] array =
12858                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12859                    intentFilters.toArray(array);
12860                    listCut.add(array);
12861                }
12862            }
12863            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12864        }
12865
12866        /**
12867         * Finds a privileged activity that matches the specified activity names.
12868         */
12869        private PackageParser.Activity findMatchingActivity(
12870                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12871            for (PackageParser.Activity sysActivity : activityList) {
12872                if (sysActivity.info.name.equals(activityInfo.name)) {
12873                    return sysActivity;
12874                }
12875                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12876                    return sysActivity;
12877                }
12878                if (sysActivity.info.targetActivity != null) {
12879                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12880                        return sysActivity;
12881                    }
12882                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12883                        return sysActivity;
12884                    }
12885                }
12886            }
12887            return null;
12888        }
12889
12890        public class IterGenerator<E> {
12891            public Iterator<E> generate(ActivityIntentInfo info) {
12892                return null;
12893            }
12894        }
12895
12896        public class ActionIterGenerator extends IterGenerator<String> {
12897            @Override
12898            public Iterator<String> generate(ActivityIntentInfo info) {
12899                return info.actionsIterator();
12900            }
12901        }
12902
12903        public class CategoriesIterGenerator extends IterGenerator<String> {
12904            @Override
12905            public Iterator<String> generate(ActivityIntentInfo info) {
12906                return info.categoriesIterator();
12907            }
12908        }
12909
12910        public class SchemesIterGenerator extends IterGenerator<String> {
12911            @Override
12912            public Iterator<String> generate(ActivityIntentInfo info) {
12913                return info.schemesIterator();
12914            }
12915        }
12916
12917        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12918            @Override
12919            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12920                return info.authoritiesIterator();
12921            }
12922        }
12923
12924        /**
12925         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12926         * MODIFIED. Do not pass in a list that should not be changed.
12927         */
12928        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12929                IterGenerator<T> generator, Iterator<T> searchIterator) {
12930            // loop through the set of actions; every one must be found in the intent filter
12931            while (searchIterator.hasNext()) {
12932                // we must have at least one filter in the list to consider a match
12933                if (intentList.size() == 0) {
12934                    break;
12935                }
12936
12937                final T searchAction = searchIterator.next();
12938
12939                // loop through the set of intent filters
12940                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12941                while (intentIter.hasNext()) {
12942                    final ActivityIntentInfo intentInfo = intentIter.next();
12943                    boolean selectionFound = false;
12944
12945                    // loop through the intent filter's selection criteria; at least one
12946                    // of them must match the searched criteria
12947                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12948                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12949                        final T intentSelection = intentSelectionIter.next();
12950                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12951                            selectionFound = true;
12952                            break;
12953                        }
12954                    }
12955
12956                    // the selection criteria wasn't found in this filter's set; this filter
12957                    // is not a potential match
12958                    if (!selectionFound) {
12959                        intentIter.remove();
12960                    }
12961                }
12962            }
12963        }
12964
12965        private boolean isProtectedAction(ActivityIntentInfo filter) {
12966            final Iterator<String> actionsIter = filter.actionsIterator();
12967            while (actionsIter != null && actionsIter.hasNext()) {
12968                final String filterAction = actionsIter.next();
12969                if (PROTECTED_ACTIONS.contains(filterAction)) {
12970                    return true;
12971                }
12972            }
12973            return false;
12974        }
12975
12976        /**
12977         * Adjusts the priority of the given intent filter according to policy.
12978         * <p>
12979         * <ul>
12980         * <li>The priority for non privileged applications is capped to '0'</li>
12981         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12982         * <li>The priority for unbundled updates to privileged applications is capped to the
12983         *      priority defined on the system partition</li>
12984         * </ul>
12985         * <p>
12986         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12987         * allowed to obtain any priority on any action.
12988         */
12989        private void adjustPriority(
12990                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12991            // nothing to do; priority is fine as-is
12992            if (intent.getPriority() <= 0) {
12993                return;
12994            }
12995
12996            final ActivityInfo activityInfo = intent.activity.info;
12997            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12998
12999            final boolean privilegedApp =
13000                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13001            if (!privilegedApp) {
13002                // non-privileged applications can never define a priority >0
13003                if (DEBUG_FILTERS) {
13004                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13005                            + " package: " + applicationInfo.packageName
13006                            + " activity: " + intent.activity.className
13007                            + " origPrio: " + intent.getPriority());
13008                }
13009                intent.setPriority(0);
13010                return;
13011            }
13012
13013            if (systemActivities == null) {
13014                // the system package is not disabled; we're parsing the system partition
13015                if (isProtectedAction(intent)) {
13016                    if (mDeferProtectedFilters) {
13017                        // We can't deal with these just yet. No component should ever obtain a
13018                        // >0 priority for a protected actions, with ONE exception -- the setup
13019                        // wizard. The setup wizard, however, cannot be known until we're able to
13020                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13021                        // until all intent filters have been processed. Chicken, meet egg.
13022                        // Let the filter temporarily have a high priority and rectify the
13023                        // priorities after all system packages have been scanned.
13024                        mProtectedFilters.add(intent);
13025                        if (DEBUG_FILTERS) {
13026                            Slog.i(TAG, "Protected action; save for later;"
13027                                    + " package: " + applicationInfo.packageName
13028                                    + " activity: " + intent.activity.className
13029                                    + " origPrio: " + intent.getPriority());
13030                        }
13031                        return;
13032                    } else {
13033                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13034                            Slog.i(TAG, "No setup wizard;"
13035                                + " All protected intents capped to priority 0");
13036                        }
13037                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13038                            if (DEBUG_FILTERS) {
13039                                Slog.i(TAG, "Found setup wizard;"
13040                                    + " allow priority " + intent.getPriority() + ";"
13041                                    + " package: " + intent.activity.info.packageName
13042                                    + " activity: " + intent.activity.className
13043                                    + " priority: " + intent.getPriority());
13044                            }
13045                            // setup wizard gets whatever it wants
13046                            return;
13047                        }
13048                        if (DEBUG_FILTERS) {
13049                            Slog.i(TAG, "Protected action; cap priority to 0;"
13050                                    + " package: " + intent.activity.info.packageName
13051                                    + " activity: " + intent.activity.className
13052                                    + " origPrio: " + intent.getPriority());
13053                        }
13054                        intent.setPriority(0);
13055                        return;
13056                    }
13057                }
13058                // privileged apps on the system image get whatever priority they request
13059                return;
13060            }
13061
13062            // privileged app unbundled update ... try to find the same activity
13063            final PackageParser.Activity foundActivity =
13064                    findMatchingActivity(systemActivities, activityInfo);
13065            if (foundActivity == null) {
13066                // this is a new activity; it cannot obtain >0 priority
13067                if (DEBUG_FILTERS) {
13068                    Slog.i(TAG, "New activity; cap priority to 0;"
13069                            + " package: " + applicationInfo.packageName
13070                            + " activity: " + intent.activity.className
13071                            + " origPrio: " + intent.getPriority());
13072                }
13073                intent.setPriority(0);
13074                return;
13075            }
13076
13077            // found activity, now check for filter equivalence
13078
13079            // a shallow copy is enough; we modify the list, not its contents
13080            final List<ActivityIntentInfo> intentListCopy =
13081                    new ArrayList<>(foundActivity.intents);
13082            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13083
13084            // find matching action subsets
13085            final Iterator<String> actionsIterator = intent.actionsIterator();
13086            if (actionsIterator != null) {
13087                getIntentListSubset(
13088                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13089                if (intentListCopy.size() == 0) {
13090                    // no more intents to match; we're not equivalent
13091                    if (DEBUG_FILTERS) {
13092                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13093                                + " package: " + applicationInfo.packageName
13094                                + " activity: " + intent.activity.className
13095                                + " origPrio: " + intent.getPriority());
13096                    }
13097                    intent.setPriority(0);
13098                    return;
13099                }
13100            }
13101
13102            // find matching category subsets
13103            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13104            if (categoriesIterator != null) {
13105                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13106                        categoriesIterator);
13107                if (intentListCopy.size() == 0) {
13108                    // no more intents to match; we're not equivalent
13109                    if (DEBUG_FILTERS) {
13110                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13111                                + " package: " + applicationInfo.packageName
13112                                + " activity: " + intent.activity.className
13113                                + " origPrio: " + intent.getPriority());
13114                    }
13115                    intent.setPriority(0);
13116                    return;
13117                }
13118            }
13119
13120            // find matching schemes subsets
13121            final Iterator<String> schemesIterator = intent.schemesIterator();
13122            if (schemesIterator != null) {
13123                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13124                        schemesIterator);
13125                if (intentListCopy.size() == 0) {
13126                    // no more intents to match; we're not equivalent
13127                    if (DEBUG_FILTERS) {
13128                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13129                                + " package: " + applicationInfo.packageName
13130                                + " activity: " + intent.activity.className
13131                                + " origPrio: " + intent.getPriority());
13132                    }
13133                    intent.setPriority(0);
13134                    return;
13135                }
13136            }
13137
13138            // find matching authorities subsets
13139            final Iterator<IntentFilter.AuthorityEntry>
13140                    authoritiesIterator = intent.authoritiesIterator();
13141            if (authoritiesIterator != null) {
13142                getIntentListSubset(intentListCopy,
13143                        new AuthoritiesIterGenerator(),
13144                        authoritiesIterator);
13145                if (intentListCopy.size() == 0) {
13146                    // no more intents to match; we're not equivalent
13147                    if (DEBUG_FILTERS) {
13148                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13149                                + " package: " + applicationInfo.packageName
13150                                + " activity: " + intent.activity.className
13151                                + " origPrio: " + intent.getPriority());
13152                    }
13153                    intent.setPriority(0);
13154                    return;
13155                }
13156            }
13157
13158            // we found matching filter(s); app gets the max priority of all intents
13159            int cappedPriority = 0;
13160            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13161                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13162            }
13163            if (intent.getPriority() > cappedPriority) {
13164                if (DEBUG_FILTERS) {
13165                    Slog.i(TAG, "Found matching filter(s);"
13166                            + " cap priority to " + cappedPriority + ";"
13167                            + " package: " + applicationInfo.packageName
13168                            + " activity: " + intent.activity.className
13169                            + " origPrio: " + intent.getPriority());
13170                }
13171                intent.setPriority(cappedPriority);
13172                return;
13173            }
13174            // all this for nothing; the requested priority was <= what was on the system
13175        }
13176
13177        public final void addActivity(PackageParser.Activity a, String type) {
13178            mActivities.put(a.getComponentName(), a);
13179            if (DEBUG_SHOW_INFO)
13180                Log.v(
13181                TAG, "  " + type + " " +
13182                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13183            if (DEBUG_SHOW_INFO)
13184                Log.v(TAG, "    Class=" + a.info.name);
13185            final int NI = a.intents.size();
13186            for (int j=0; j<NI; j++) {
13187                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13188                if ("activity".equals(type)) {
13189                    final PackageSetting ps =
13190                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13191                    final List<PackageParser.Activity> systemActivities =
13192                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13193                    adjustPriority(systemActivities, intent);
13194                }
13195                if (DEBUG_SHOW_INFO) {
13196                    Log.v(TAG, "    IntentFilter:");
13197                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13198                }
13199                if (!intent.debugCheck()) {
13200                    Log.w(TAG, "==> For Activity " + a.info.name);
13201                }
13202                addFilter(intent);
13203            }
13204        }
13205
13206        public final void removeActivity(PackageParser.Activity a, String type) {
13207            mActivities.remove(a.getComponentName());
13208            if (DEBUG_SHOW_INFO) {
13209                Log.v(TAG, "  " + type + " "
13210                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13211                                : a.info.name) + ":");
13212                Log.v(TAG, "    Class=" + a.info.name);
13213            }
13214            final int NI = a.intents.size();
13215            for (int j=0; j<NI; j++) {
13216                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13217                if (DEBUG_SHOW_INFO) {
13218                    Log.v(TAG, "    IntentFilter:");
13219                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13220                }
13221                removeFilter(intent);
13222            }
13223        }
13224
13225        @Override
13226        protected boolean allowFilterResult(
13227                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13228            ActivityInfo filterAi = filter.activity.info;
13229            for (int i=dest.size()-1; i>=0; i--) {
13230                ActivityInfo destAi = dest.get(i).activityInfo;
13231                if (destAi.name == filterAi.name
13232                        && destAi.packageName == filterAi.packageName) {
13233                    return false;
13234                }
13235            }
13236            return true;
13237        }
13238
13239        @Override
13240        protected ActivityIntentInfo[] newArray(int size) {
13241            return new ActivityIntentInfo[size];
13242        }
13243
13244        @Override
13245        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13246            if (!sUserManager.exists(userId)) return true;
13247            PackageParser.Package p = filter.activity.owner;
13248            if (p != null) {
13249                PackageSetting ps = (PackageSetting)p.mExtras;
13250                if (ps != null) {
13251                    // System apps are never considered stopped for purposes of
13252                    // filtering, because there may be no way for the user to
13253                    // actually re-launch them.
13254                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13255                            && ps.getStopped(userId);
13256                }
13257            }
13258            return false;
13259        }
13260
13261        @Override
13262        protected boolean isPackageForFilter(String packageName,
13263                PackageParser.ActivityIntentInfo info) {
13264            return packageName.equals(info.activity.owner.packageName);
13265        }
13266
13267        @Override
13268        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13269                int match, int userId) {
13270            if (!sUserManager.exists(userId)) return null;
13271            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13272                return null;
13273            }
13274            final PackageParser.Activity activity = info.activity;
13275            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13276            if (ps == null) {
13277                return null;
13278            }
13279            final PackageUserState userState = ps.readUserState(userId);
13280            ActivityInfo ai =
13281                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13282            if (ai == null) {
13283                return null;
13284            }
13285            final boolean matchExplicitlyVisibleOnly =
13286                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13287            final boolean matchVisibleToInstantApp =
13288                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13289            final boolean componentVisible =
13290                    matchVisibleToInstantApp
13291                    && info.isVisibleToInstantApp()
13292                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13293            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13294            // throw out filters that aren't visible to ephemeral apps
13295            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13296                return null;
13297            }
13298            // throw out instant app filters if we're not explicitly requesting them
13299            if (!matchInstantApp && userState.instantApp) {
13300                return null;
13301            }
13302            // throw out instant app filters if updates are available; will trigger
13303            // instant app resolution
13304            if (userState.instantApp && ps.isUpdateAvailable()) {
13305                return null;
13306            }
13307            final ResolveInfo res = new ResolveInfo();
13308            res.activityInfo = ai;
13309            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13310                res.filter = info;
13311            }
13312            if (info != null) {
13313                res.handleAllWebDataURI = info.handleAllWebDataURI();
13314            }
13315            res.priority = info.getPriority();
13316            res.preferredOrder = activity.owner.mPreferredOrder;
13317            //System.out.println("Result: " + res.activityInfo.className +
13318            //                   " = " + res.priority);
13319            res.match = match;
13320            res.isDefault = info.hasDefault;
13321            res.labelRes = info.labelRes;
13322            res.nonLocalizedLabel = info.nonLocalizedLabel;
13323            if (userNeedsBadging(userId)) {
13324                res.noResourceId = true;
13325            } else {
13326                res.icon = info.icon;
13327            }
13328            res.iconResourceId = info.icon;
13329            res.system = res.activityInfo.applicationInfo.isSystemApp();
13330            res.isInstantAppAvailable = userState.instantApp;
13331            return res;
13332        }
13333
13334        @Override
13335        protected void sortResults(List<ResolveInfo> results) {
13336            Collections.sort(results, mResolvePrioritySorter);
13337        }
13338
13339        @Override
13340        protected void dumpFilter(PrintWriter out, String prefix,
13341                PackageParser.ActivityIntentInfo filter) {
13342            out.print(prefix); out.print(
13343                    Integer.toHexString(System.identityHashCode(filter.activity)));
13344                    out.print(' ');
13345                    filter.activity.printComponentShortName(out);
13346                    out.print(" filter ");
13347                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13348        }
13349
13350        @Override
13351        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13352            return filter.activity;
13353        }
13354
13355        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13356            PackageParser.Activity activity = (PackageParser.Activity)label;
13357            out.print(prefix); out.print(
13358                    Integer.toHexString(System.identityHashCode(activity)));
13359                    out.print(' ');
13360                    activity.printComponentShortName(out);
13361            if (count > 1) {
13362                out.print(" ("); out.print(count); out.print(" filters)");
13363            }
13364            out.println();
13365        }
13366
13367        // Keys are String (activity class name), values are Activity.
13368        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13369                = new ArrayMap<ComponentName, PackageParser.Activity>();
13370        private int mFlags;
13371    }
13372
13373    private final class ServiceIntentResolver
13374            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13375        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13376                boolean defaultOnly, int userId) {
13377            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13378            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13379        }
13380
13381        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13382                int userId) {
13383            if (!sUserManager.exists(userId)) return null;
13384            mFlags = flags;
13385            return super.queryIntent(intent, resolvedType,
13386                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13387                    userId);
13388        }
13389
13390        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13391                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13392            if (!sUserManager.exists(userId)) return null;
13393            if (packageServices == null) {
13394                return null;
13395            }
13396            mFlags = flags;
13397            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13398            final int N = packageServices.size();
13399            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13400                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13401
13402            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13403            for (int i = 0; i < N; ++i) {
13404                intentFilters = packageServices.get(i).intents;
13405                if (intentFilters != null && intentFilters.size() > 0) {
13406                    PackageParser.ServiceIntentInfo[] array =
13407                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13408                    intentFilters.toArray(array);
13409                    listCut.add(array);
13410                }
13411            }
13412            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13413        }
13414
13415        public final void addService(PackageParser.Service s) {
13416            mServices.put(s.getComponentName(), s);
13417            if (DEBUG_SHOW_INFO) {
13418                Log.v(TAG, "  "
13419                        + (s.info.nonLocalizedLabel != null
13420                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13421                Log.v(TAG, "    Class=" + s.info.name);
13422            }
13423            final int NI = s.intents.size();
13424            int j;
13425            for (j=0; j<NI; j++) {
13426                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13427                if (DEBUG_SHOW_INFO) {
13428                    Log.v(TAG, "    IntentFilter:");
13429                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13430                }
13431                if (!intent.debugCheck()) {
13432                    Log.w(TAG, "==> For Service " + s.info.name);
13433                }
13434                addFilter(intent);
13435            }
13436        }
13437
13438        public final void removeService(PackageParser.Service s) {
13439            mServices.remove(s.getComponentName());
13440            if (DEBUG_SHOW_INFO) {
13441                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13442                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13443                Log.v(TAG, "    Class=" + s.info.name);
13444            }
13445            final int NI = s.intents.size();
13446            int j;
13447            for (j=0; j<NI; j++) {
13448                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13449                if (DEBUG_SHOW_INFO) {
13450                    Log.v(TAG, "    IntentFilter:");
13451                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13452                }
13453                removeFilter(intent);
13454            }
13455        }
13456
13457        @Override
13458        protected boolean allowFilterResult(
13459                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13460            ServiceInfo filterSi = filter.service.info;
13461            for (int i=dest.size()-1; i>=0; i--) {
13462                ServiceInfo destAi = dest.get(i).serviceInfo;
13463                if (destAi.name == filterSi.name
13464                        && destAi.packageName == filterSi.packageName) {
13465                    return false;
13466                }
13467            }
13468            return true;
13469        }
13470
13471        @Override
13472        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13473            return new PackageParser.ServiceIntentInfo[size];
13474        }
13475
13476        @Override
13477        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13478            if (!sUserManager.exists(userId)) return true;
13479            PackageParser.Package p = filter.service.owner;
13480            if (p != null) {
13481                PackageSetting ps = (PackageSetting)p.mExtras;
13482                if (ps != null) {
13483                    // System apps are never considered stopped for purposes of
13484                    // filtering, because there may be no way for the user to
13485                    // actually re-launch them.
13486                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13487                            && ps.getStopped(userId);
13488                }
13489            }
13490            return false;
13491        }
13492
13493        @Override
13494        protected boolean isPackageForFilter(String packageName,
13495                PackageParser.ServiceIntentInfo info) {
13496            return packageName.equals(info.service.owner.packageName);
13497        }
13498
13499        @Override
13500        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13501                int match, int userId) {
13502            if (!sUserManager.exists(userId)) return null;
13503            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13504            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13505                return null;
13506            }
13507            final PackageParser.Service service = info.service;
13508            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13509            if (ps == null) {
13510                return null;
13511            }
13512            final PackageUserState userState = ps.readUserState(userId);
13513            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13514                    userState, userId);
13515            if (si == null) {
13516                return null;
13517            }
13518            final boolean matchVisibleToInstantApp =
13519                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13520            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13521            // throw out filters that aren't visible to ephemeral apps
13522            if (matchVisibleToInstantApp
13523                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13524                return null;
13525            }
13526            // throw out ephemeral filters if we're not explicitly requesting them
13527            if (!isInstantApp && userState.instantApp) {
13528                return null;
13529            }
13530            // throw out instant app filters if updates are available; will trigger
13531            // instant app resolution
13532            if (userState.instantApp && ps.isUpdateAvailable()) {
13533                return null;
13534            }
13535            final ResolveInfo res = new ResolveInfo();
13536            res.serviceInfo = si;
13537            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13538                res.filter = filter;
13539            }
13540            res.priority = info.getPriority();
13541            res.preferredOrder = service.owner.mPreferredOrder;
13542            res.match = match;
13543            res.isDefault = info.hasDefault;
13544            res.labelRes = info.labelRes;
13545            res.nonLocalizedLabel = info.nonLocalizedLabel;
13546            res.icon = info.icon;
13547            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13548            return res;
13549        }
13550
13551        @Override
13552        protected void sortResults(List<ResolveInfo> results) {
13553            Collections.sort(results, mResolvePrioritySorter);
13554        }
13555
13556        @Override
13557        protected void dumpFilter(PrintWriter out, String prefix,
13558                PackageParser.ServiceIntentInfo filter) {
13559            out.print(prefix); out.print(
13560                    Integer.toHexString(System.identityHashCode(filter.service)));
13561                    out.print(' ');
13562                    filter.service.printComponentShortName(out);
13563                    out.print(" filter ");
13564                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13565        }
13566
13567        @Override
13568        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13569            return filter.service;
13570        }
13571
13572        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13573            PackageParser.Service service = (PackageParser.Service)label;
13574            out.print(prefix); out.print(
13575                    Integer.toHexString(System.identityHashCode(service)));
13576                    out.print(' ');
13577                    service.printComponentShortName(out);
13578            if (count > 1) {
13579                out.print(" ("); out.print(count); out.print(" filters)");
13580            }
13581            out.println();
13582        }
13583
13584//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13585//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13586//            final List<ResolveInfo> retList = Lists.newArrayList();
13587//            while (i.hasNext()) {
13588//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13589//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13590//                    retList.add(resolveInfo);
13591//                }
13592//            }
13593//            return retList;
13594//        }
13595
13596        // Keys are String (activity class name), values are Activity.
13597        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13598                = new ArrayMap<ComponentName, PackageParser.Service>();
13599        private int mFlags;
13600    }
13601
13602    private final class ProviderIntentResolver
13603            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13604        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13605                boolean defaultOnly, int userId) {
13606            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13607            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13608        }
13609
13610        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13611                int userId) {
13612            if (!sUserManager.exists(userId))
13613                return null;
13614            mFlags = flags;
13615            return super.queryIntent(intent, resolvedType,
13616                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13617                    userId);
13618        }
13619
13620        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13621                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13622            if (!sUserManager.exists(userId))
13623                return null;
13624            if (packageProviders == null) {
13625                return null;
13626            }
13627            mFlags = flags;
13628            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13629            final int N = packageProviders.size();
13630            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13631                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13632
13633            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13634            for (int i = 0; i < N; ++i) {
13635                intentFilters = packageProviders.get(i).intents;
13636                if (intentFilters != null && intentFilters.size() > 0) {
13637                    PackageParser.ProviderIntentInfo[] array =
13638                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13639                    intentFilters.toArray(array);
13640                    listCut.add(array);
13641                }
13642            }
13643            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13644        }
13645
13646        public final void addProvider(PackageParser.Provider p) {
13647            if (mProviders.containsKey(p.getComponentName())) {
13648                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13649                return;
13650            }
13651
13652            mProviders.put(p.getComponentName(), p);
13653            if (DEBUG_SHOW_INFO) {
13654                Log.v(TAG, "  "
13655                        + (p.info.nonLocalizedLabel != null
13656                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13657                Log.v(TAG, "    Class=" + p.info.name);
13658            }
13659            final int NI = p.intents.size();
13660            int j;
13661            for (j = 0; j < NI; j++) {
13662                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13663                if (DEBUG_SHOW_INFO) {
13664                    Log.v(TAG, "    IntentFilter:");
13665                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13666                }
13667                if (!intent.debugCheck()) {
13668                    Log.w(TAG, "==> For Provider " + p.info.name);
13669                }
13670                addFilter(intent);
13671            }
13672        }
13673
13674        public final void removeProvider(PackageParser.Provider p) {
13675            mProviders.remove(p.getComponentName());
13676            if (DEBUG_SHOW_INFO) {
13677                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13678                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13679                Log.v(TAG, "    Class=" + p.info.name);
13680            }
13681            final int NI = p.intents.size();
13682            int j;
13683            for (j = 0; j < NI; j++) {
13684                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13685                if (DEBUG_SHOW_INFO) {
13686                    Log.v(TAG, "    IntentFilter:");
13687                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13688                }
13689                removeFilter(intent);
13690            }
13691        }
13692
13693        @Override
13694        protected boolean allowFilterResult(
13695                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13696            ProviderInfo filterPi = filter.provider.info;
13697            for (int i = dest.size() - 1; i >= 0; i--) {
13698                ProviderInfo destPi = dest.get(i).providerInfo;
13699                if (destPi.name == filterPi.name
13700                        && destPi.packageName == filterPi.packageName) {
13701                    return false;
13702                }
13703            }
13704            return true;
13705        }
13706
13707        @Override
13708        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13709            return new PackageParser.ProviderIntentInfo[size];
13710        }
13711
13712        @Override
13713        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13714            if (!sUserManager.exists(userId))
13715                return true;
13716            PackageParser.Package p = filter.provider.owner;
13717            if (p != null) {
13718                PackageSetting ps = (PackageSetting) p.mExtras;
13719                if (ps != null) {
13720                    // System apps are never considered stopped for purposes of
13721                    // filtering, because there may be no way for the user to
13722                    // actually re-launch them.
13723                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13724                            && ps.getStopped(userId);
13725                }
13726            }
13727            return false;
13728        }
13729
13730        @Override
13731        protected boolean isPackageForFilter(String packageName,
13732                PackageParser.ProviderIntentInfo info) {
13733            return packageName.equals(info.provider.owner.packageName);
13734        }
13735
13736        @Override
13737        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13738                int match, int userId) {
13739            if (!sUserManager.exists(userId))
13740                return null;
13741            final PackageParser.ProviderIntentInfo info = filter;
13742            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13743                return null;
13744            }
13745            final PackageParser.Provider provider = info.provider;
13746            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13747            if (ps == null) {
13748                return null;
13749            }
13750            final PackageUserState userState = ps.readUserState(userId);
13751            final boolean matchVisibleToInstantApp =
13752                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13753            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13754            // throw out filters that aren't visible to instant applications
13755            if (matchVisibleToInstantApp
13756                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13757                return null;
13758            }
13759            // throw out instant application filters if we're not explicitly requesting them
13760            if (!isInstantApp && userState.instantApp) {
13761                return null;
13762            }
13763            // throw out instant application filters if updates are available; will trigger
13764            // instant application resolution
13765            if (userState.instantApp && ps.isUpdateAvailable()) {
13766                return null;
13767            }
13768            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13769                    userState, userId);
13770            if (pi == null) {
13771                return null;
13772            }
13773            final ResolveInfo res = new ResolveInfo();
13774            res.providerInfo = pi;
13775            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13776                res.filter = filter;
13777            }
13778            res.priority = info.getPriority();
13779            res.preferredOrder = provider.owner.mPreferredOrder;
13780            res.match = match;
13781            res.isDefault = info.hasDefault;
13782            res.labelRes = info.labelRes;
13783            res.nonLocalizedLabel = info.nonLocalizedLabel;
13784            res.icon = info.icon;
13785            res.system = res.providerInfo.applicationInfo.isSystemApp();
13786            return res;
13787        }
13788
13789        @Override
13790        protected void sortResults(List<ResolveInfo> results) {
13791            Collections.sort(results, mResolvePrioritySorter);
13792        }
13793
13794        @Override
13795        protected void dumpFilter(PrintWriter out, String prefix,
13796                PackageParser.ProviderIntentInfo filter) {
13797            out.print(prefix);
13798            out.print(
13799                    Integer.toHexString(System.identityHashCode(filter.provider)));
13800            out.print(' ');
13801            filter.provider.printComponentShortName(out);
13802            out.print(" filter ");
13803            out.println(Integer.toHexString(System.identityHashCode(filter)));
13804        }
13805
13806        @Override
13807        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13808            return filter.provider;
13809        }
13810
13811        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13812            PackageParser.Provider provider = (PackageParser.Provider)label;
13813            out.print(prefix); out.print(
13814                    Integer.toHexString(System.identityHashCode(provider)));
13815                    out.print(' ');
13816                    provider.printComponentShortName(out);
13817            if (count > 1) {
13818                out.print(" ("); out.print(count); out.print(" filters)");
13819            }
13820            out.println();
13821        }
13822
13823        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13824                = new ArrayMap<ComponentName, PackageParser.Provider>();
13825        private int mFlags;
13826    }
13827
13828    static final class EphemeralIntentResolver
13829            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13830        /**
13831         * The result that has the highest defined order. Ordering applies on a
13832         * per-package basis. Mapping is from package name to Pair of order and
13833         * EphemeralResolveInfo.
13834         * <p>
13835         * NOTE: This is implemented as a field variable for convenience and efficiency.
13836         * By having a field variable, we're able to track filter ordering as soon as
13837         * a non-zero order is defined. Otherwise, multiple loops across the result set
13838         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13839         * this needs to be contained entirely within {@link #filterResults}.
13840         */
13841        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13842
13843        @Override
13844        protected AuxiliaryResolveInfo[] newArray(int size) {
13845            return new AuxiliaryResolveInfo[size];
13846        }
13847
13848        @Override
13849        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13850            return true;
13851        }
13852
13853        @Override
13854        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13855                int userId) {
13856            if (!sUserManager.exists(userId)) {
13857                return null;
13858            }
13859            final String packageName = responseObj.resolveInfo.getPackageName();
13860            final Integer order = responseObj.getOrder();
13861            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13862                    mOrderResult.get(packageName);
13863            // ordering is enabled and this item's order isn't high enough
13864            if (lastOrderResult != null && lastOrderResult.first >= order) {
13865                return null;
13866            }
13867            final InstantAppResolveInfo res = responseObj.resolveInfo;
13868            if (order > 0) {
13869                // non-zero order, enable ordering
13870                mOrderResult.put(packageName, new Pair<>(order, res));
13871            }
13872            return responseObj;
13873        }
13874
13875        @Override
13876        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13877            // only do work if ordering is enabled [most of the time it won't be]
13878            if (mOrderResult.size() == 0) {
13879                return;
13880            }
13881            int resultSize = results.size();
13882            for (int i = 0; i < resultSize; i++) {
13883                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13884                final String packageName = info.getPackageName();
13885                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13886                if (savedInfo == null) {
13887                    // package doesn't having ordering
13888                    continue;
13889                }
13890                if (savedInfo.second == info) {
13891                    // circled back to the highest ordered item; remove from order list
13892                    mOrderResult.remove(savedInfo);
13893                    if (mOrderResult.size() == 0) {
13894                        // no more ordered items
13895                        break;
13896                    }
13897                    continue;
13898                }
13899                // item has a worse order, remove it from the result list
13900                results.remove(i);
13901                resultSize--;
13902                i--;
13903            }
13904        }
13905    }
13906
13907    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13908            new Comparator<ResolveInfo>() {
13909        public int compare(ResolveInfo r1, ResolveInfo r2) {
13910            int v1 = r1.priority;
13911            int v2 = r2.priority;
13912            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13913            if (v1 != v2) {
13914                return (v1 > v2) ? -1 : 1;
13915            }
13916            v1 = r1.preferredOrder;
13917            v2 = r2.preferredOrder;
13918            if (v1 != v2) {
13919                return (v1 > v2) ? -1 : 1;
13920            }
13921            if (r1.isDefault != r2.isDefault) {
13922                return r1.isDefault ? -1 : 1;
13923            }
13924            v1 = r1.match;
13925            v2 = r2.match;
13926            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13927            if (v1 != v2) {
13928                return (v1 > v2) ? -1 : 1;
13929            }
13930            if (r1.system != r2.system) {
13931                return r1.system ? -1 : 1;
13932            }
13933            if (r1.activityInfo != null) {
13934                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13935            }
13936            if (r1.serviceInfo != null) {
13937                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13938            }
13939            if (r1.providerInfo != null) {
13940                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13941            }
13942            return 0;
13943        }
13944    };
13945
13946    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13947            new Comparator<ProviderInfo>() {
13948        public int compare(ProviderInfo p1, ProviderInfo p2) {
13949            final int v1 = p1.initOrder;
13950            final int v2 = p2.initOrder;
13951            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13952        }
13953    };
13954
13955    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13956            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13957            final int[] userIds) {
13958        mHandler.post(new Runnable() {
13959            @Override
13960            public void run() {
13961                try {
13962                    final IActivityManager am = ActivityManager.getService();
13963                    if (am == null) return;
13964                    final int[] resolvedUserIds;
13965                    if (userIds == null) {
13966                        resolvedUserIds = am.getRunningUserIds();
13967                    } else {
13968                        resolvedUserIds = userIds;
13969                    }
13970                    for (int id : resolvedUserIds) {
13971                        final Intent intent = new Intent(action,
13972                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13973                        if (extras != null) {
13974                            intent.putExtras(extras);
13975                        }
13976                        if (targetPkg != null) {
13977                            intent.setPackage(targetPkg);
13978                        }
13979                        // Modify the UID when posting to other users
13980                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13981                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13982                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13983                            intent.putExtra(Intent.EXTRA_UID, uid);
13984                        }
13985                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13986                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13987                        if (DEBUG_BROADCASTS) {
13988                            RuntimeException here = new RuntimeException("here");
13989                            here.fillInStackTrace();
13990                            Slog.d(TAG, "Sending to user " + id + ": "
13991                                    + intent.toShortString(false, true, false, false)
13992                                    + " " + intent.getExtras(), here);
13993                        }
13994                        am.broadcastIntent(null, intent, null, finishedReceiver,
13995                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13996                                null, finishedReceiver != null, false, id);
13997                    }
13998                } catch (RemoteException ex) {
13999                }
14000            }
14001        });
14002    }
14003
14004    /**
14005     * Check if the external storage media is available. This is true if there
14006     * is a mounted external storage medium or if the external storage is
14007     * emulated.
14008     */
14009    private boolean isExternalMediaAvailable() {
14010        return mMediaMounted || Environment.isExternalStorageEmulated();
14011    }
14012
14013    @Override
14014    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14015        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14016            return null;
14017        }
14018        // writer
14019        synchronized (mPackages) {
14020            if (!isExternalMediaAvailable()) {
14021                // If the external storage is no longer mounted at this point,
14022                // the caller may not have been able to delete all of this
14023                // packages files and can not delete any more.  Bail.
14024                return null;
14025            }
14026            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14027            if (lastPackage != null) {
14028                pkgs.remove(lastPackage);
14029            }
14030            if (pkgs.size() > 0) {
14031                return pkgs.get(0);
14032            }
14033        }
14034        return null;
14035    }
14036
14037    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14038        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14039                userId, andCode ? 1 : 0, packageName);
14040        if (mSystemReady) {
14041            msg.sendToTarget();
14042        } else {
14043            if (mPostSystemReadyMessages == null) {
14044                mPostSystemReadyMessages = new ArrayList<>();
14045            }
14046            mPostSystemReadyMessages.add(msg);
14047        }
14048    }
14049
14050    void startCleaningPackages() {
14051        // reader
14052        if (!isExternalMediaAvailable()) {
14053            return;
14054        }
14055        synchronized (mPackages) {
14056            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14057                return;
14058            }
14059        }
14060        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14061        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14062        IActivityManager am = ActivityManager.getService();
14063        if (am != null) {
14064            int dcsUid = -1;
14065            synchronized (mPackages) {
14066                if (!mDefaultContainerWhitelisted) {
14067                    mDefaultContainerWhitelisted = true;
14068                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14069                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14070                }
14071            }
14072            try {
14073                if (dcsUid > 0) {
14074                    am.backgroundWhitelistUid(dcsUid);
14075                }
14076                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14077                        UserHandle.USER_SYSTEM);
14078            } catch (RemoteException e) {
14079            }
14080        }
14081    }
14082
14083    @Override
14084    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14085            int installFlags, String installerPackageName, int userId) {
14086        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14087
14088        final int callingUid = Binder.getCallingUid();
14089        enforceCrossUserPermission(callingUid, userId,
14090                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14091
14092        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14093            try {
14094                if (observer != null) {
14095                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14096                }
14097            } catch (RemoteException re) {
14098            }
14099            return;
14100        }
14101
14102        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14103            installFlags |= PackageManager.INSTALL_FROM_ADB;
14104
14105        } else {
14106            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14107            // about installerPackageName.
14108
14109            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14110            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14111        }
14112
14113        UserHandle user;
14114        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14115            user = UserHandle.ALL;
14116        } else {
14117            user = new UserHandle(userId);
14118        }
14119
14120        // Only system components can circumvent runtime permissions when installing.
14121        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14122                && mContext.checkCallingOrSelfPermission(Manifest.permission
14123                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14124            throw new SecurityException("You need the "
14125                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14126                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14127        }
14128
14129        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14130                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14131            throw new IllegalArgumentException(
14132                    "New installs into ASEC containers no longer supported");
14133        }
14134
14135        final File originFile = new File(originPath);
14136        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14137
14138        final Message msg = mHandler.obtainMessage(INIT_COPY);
14139        final VerificationInfo verificationInfo = new VerificationInfo(
14140                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14141        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14142                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14143                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14144                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14145        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14146        msg.obj = params;
14147
14148        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14149                System.identityHashCode(msg.obj));
14150        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14151                System.identityHashCode(msg.obj));
14152
14153        mHandler.sendMessage(msg);
14154    }
14155
14156
14157    /**
14158     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14159     * it is acting on behalf on an enterprise or the user).
14160     *
14161     * Note that the ordering of the conditionals in this method is important. The checks we perform
14162     * are as follows, in this order:
14163     *
14164     * 1) If the install is being performed by a system app, we can trust the app to have set the
14165     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14166     *    what it is.
14167     * 2) If the install is being performed by a device or profile owner app, the install reason
14168     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14169     *    set the install reason correctly. If the app targets an older SDK version where install
14170     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14171     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14172     * 3) In all other cases, the install is being performed by a regular app that is neither part
14173     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14174     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14175     *    set to enterprise policy and if so, change it to unknown instead.
14176     */
14177    private int fixUpInstallReason(String installerPackageName, int installerUid,
14178            int installReason) {
14179        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14180                == PERMISSION_GRANTED) {
14181            // If the install is being performed by a system app, we trust that app to have set the
14182            // install reason correctly.
14183            return installReason;
14184        }
14185
14186        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14187            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14188        if (dpm != null) {
14189            ComponentName owner = null;
14190            try {
14191                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14192                if (owner == null) {
14193                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14194                }
14195            } catch (RemoteException e) {
14196            }
14197            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14198                // If the install is being performed by a device or profile owner, the install
14199                // reason should be enterprise policy.
14200                return PackageManager.INSTALL_REASON_POLICY;
14201            }
14202        }
14203
14204        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14205            // If the install is being performed by a regular app (i.e. neither system app nor
14206            // device or profile owner), we have no reason to believe that the app is acting on
14207            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14208            // change it to unknown instead.
14209            return PackageManager.INSTALL_REASON_UNKNOWN;
14210        }
14211
14212        // If the install is being performed by a regular app and the install reason was set to any
14213        // value but enterprise policy, leave the install reason unchanged.
14214        return installReason;
14215    }
14216
14217    void installStage(String packageName, File stagedDir, String stagedCid,
14218            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14219            String installerPackageName, int installerUid, UserHandle user,
14220            Certificate[][] certificates) {
14221        if (DEBUG_EPHEMERAL) {
14222            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14223                Slog.d(TAG, "Ephemeral install of " + packageName);
14224            }
14225        }
14226        final VerificationInfo verificationInfo = new VerificationInfo(
14227                sessionParams.originatingUri, sessionParams.referrerUri,
14228                sessionParams.originatingUid, installerUid);
14229
14230        final OriginInfo origin;
14231        if (stagedDir != null) {
14232            origin = OriginInfo.fromStagedFile(stagedDir);
14233        } else {
14234            origin = OriginInfo.fromStagedContainer(stagedCid);
14235        }
14236
14237        final Message msg = mHandler.obtainMessage(INIT_COPY);
14238        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14239                sessionParams.installReason);
14240        final InstallParams params = new InstallParams(origin, null, observer,
14241                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14242                verificationInfo, user, sessionParams.abiOverride,
14243                sessionParams.grantedRuntimePermissions, certificates, installReason);
14244        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14245        msg.obj = params;
14246
14247        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14248                System.identityHashCode(msg.obj));
14249        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14250                System.identityHashCode(msg.obj));
14251
14252        mHandler.sendMessage(msg);
14253    }
14254
14255    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14256            int userId) {
14257        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14258        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14259
14260        // Send a session commit broadcast
14261        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14262        info.installReason = pkgSetting.getInstallReason(userId);
14263        info.appPackageName = packageName;
14264        sendSessionCommitBroadcast(info, userId);
14265    }
14266
14267    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14268        if (ArrayUtils.isEmpty(userIds)) {
14269            return;
14270        }
14271        Bundle extras = new Bundle(1);
14272        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14273        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14274
14275        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14276                packageName, extras, 0, null, null, userIds);
14277        if (isSystem) {
14278            mHandler.post(() -> {
14279                        for (int userId : userIds) {
14280                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14281                        }
14282                    }
14283            );
14284        }
14285    }
14286
14287    /**
14288     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14289     * automatically without needing an explicit launch.
14290     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14291     */
14292    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14293        // If user is not running, the app didn't miss any broadcast
14294        if (!mUserManagerInternal.isUserRunning(userId)) {
14295            return;
14296        }
14297        final IActivityManager am = ActivityManager.getService();
14298        try {
14299            // Deliver LOCKED_BOOT_COMPLETED first
14300            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14301                    .setPackage(packageName);
14302            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14303            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14304                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14305
14306            // Deliver BOOT_COMPLETED only if user is unlocked
14307            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14308                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14309                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14310                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14311            }
14312        } catch (RemoteException e) {
14313            throw e.rethrowFromSystemServer();
14314        }
14315    }
14316
14317    @Override
14318    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14319            int userId) {
14320        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14321        PackageSetting pkgSetting;
14322        final int callingUid = Binder.getCallingUid();
14323        enforceCrossUserPermission(callingUid, userId,
14324                true /* requireFullPermission */, true /* checkShell */,
14325                "setApplicationHiddenSetting for user " + userId);
14326
14327        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14328            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14329            return false;
14330        }
14331
14332        long callingId = Binder.clearCallingIdentity();
14333        try {
14334            boolean sendAdded = false;
14335            boolean sendRemoved = false;
14336            // writer
14337            synchronized (mPackages) {
14338                pkgSetting = mSettings.mPackages.get(packageName);
14339                if (pkgSetting == null) {
14340                    return false;
14341                }
14342                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14343                    return false;
14344                }
14345                // Do not allow "android" is being disabled
14346                if ("android".equals(packageName)) {
14347                    Slog.w(TAG, "Cannot hide package: android");
14348                    return false;
14349                }
14350                // Cannot hide static shared libs as they are considered
14351                // a part of the using app (emulating static linking). Also
14352                // static libs are installed always on internal storage.
14353                PackageParser.Package pkg = mPackages.get(packageName);
14354                if (pkg != null && pkg.staticSharedLibName != null) {
14355                    Slog.w(TAG, "Cannot hide package: " + packageName
14356                            + " providing static shared library: "
14357                            + pkg.staticSharedLibName);
14358                    return false;
14359                }
14360                // Only allow protected packages to hide themselves.
14361                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14362                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14363                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14364                    return false;
14365                }
14366
14367                if (pkgSetting.getHidden(userId) != hidden) {
14368                    pkgSetting.setHidden(hidden, userId);
14369                    mSettings.writePackageRestrictionsLPr(userId);
14370                    if (hidden) {
14371                        sendRemoved = true;
14372                    } else {
14373                        sendAdded = true;
14374                    }
14375                }
14376            }
14377            if (sendAdded) {
14378                sendPackageAddedForUser(packageName, pkgSetting, userId);
14379                return true;
14380            }
14381            if (sendRemoved) {
14382                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14383                        "hiding pkg");
14384                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14385                return true;
14386            }
14387        } finally {
14388            Binder.restoreCallingIdentity(callingId);
14389        }
14390        return false;
14391    }
14392
14393    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14394            int userId) {
14395        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14396        info.removedPackage = packageName;
14397        info.installerPackageName = pkgSetting.installerPackageName;
14398        info.removedUsers = new int[] {userId};
14399        info.broadcastUsers = new int[] {userId};
14400        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14401        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14402    }
14403
14404    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14405        if (pkgList.length > 0) {
14406            Bundle extras = new Bundle(1);
14407            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14408
14409            sendPackageBroadcast(
14410                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14411                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14412                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14413                    new int[] {userId});
14414        }
14415    }
14416
14417    /**
14418     * Returns true if application is not found or there was an error. Otherwise it returns
14419     * the hidden state of the package for the given user.
14420     */
14421    @Override
14422    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14423        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14424        final int callingUid = Binder.getCallingUid();
14425        enforceCrossUserPermission(callingUid, userId,
14426                true /* requireFullPermission */, false /* checkShell */,
14427                "getApplicationHidden for user " + userId);
14428        PackageSetting ps;
14429        long callingId = Binder.clearCallingIdentity();
14430        try {
14431            // writer
14432            synchronized (mPackages) {
14433                ps = mSettings.mPackages.get(packageName);
14434                if (ps == null) {
14435                    return true;
14436                }
14437                if (filterAppAccessLPr(ps, callingUid, userId)) {
14438                    return true;
14439                }
14440                return ps.getHidden(userId);
14441            }
14442        } finally {
14443            Binder.restoreCallingIdentity(callingId);
14444        }
14445    }
14446
14447    /**
14448     * @hide
14449     */
14450    @Override
14451    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14452            int installReason) {
14453        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14454                null);
14455        PackageSetting pkgSetting;
14456        final int callingUid = Binder.getCallingUid();
14457        enforceCrossUserPermission(callingUid, userId,
14458                true /* requireFullPermission */, true /* checkShell */,
14459                "installExistingPackage for user " + userId);
14460        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14461            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14462        }
14463
14464        long callingId = Binder.clearCallingIdentity();
14465        try {
14466            boolean installed = false;
14467            final boolean instantApp =
14468                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14469            final boolean fullApp =
14470                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14471
14472            // writer
14473            synchronized (mPackages) {
14474                pkgSetting = mSettings.mPackages.get(packageName);
14475                if (pkgSetting == null) {
14476                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14477                }
14478                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14479                    // only allow the existing package to be used if it's installed as a full
14480                    // application for at least one user
14481                    boolean installAllowed = false;
14482                    for (int checkUserId : sUserManager.getUserIds()) {
14483                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14484                        if (installAllowed) {
14485                            break;
14486                        }
14487                    }
14488                    if (!installAllowed) {
14489                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14490                    }
14491                }
14492                if (!pkgSetting.getInstalled(userId)) {
14493                    pkgSetting.setInstalled(true, userId);
14494                    pkgSetting.setHidden(false, userId);
14495                    pkgSetting.setInstallReason(installReason, userId);
14496                    mSettings.writePackageRestrictionsLPr(userId);
14497                    mSettings.writeKernelMappingLPr(pkgSetting);
14498                    installed = true;
14499                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14500                    // upgrade app from instant to full; we don't allow app downgrade
14501                    installed = true;
14502                }
14503                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14504            }
14505
14506            if (installed) {
14507                if (pkgSetting.pkg != null) {
14508                    synchronized (mInstallLock) {
14509                        // We don't need to freeze for a brand new install
14510                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14511                    }
14512                }
14513                sendPackageAddedForUser(packageName, pkgSetting, userId);
14514                synchronized (mPackages) {
14515                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14516                }
14517            }
14518        } finally {
14519            Binder.restoreCallingIdentity(callingId);
14520        }
14521
14522        return PackageManager.INSTALL_SUCCEEDED;
14523    }
14524
14525    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14526            boolean instantApp, boolean fullApp) {
14527        // no state specified; do nothing
14528        if (!instantApp && !fullApp) {
14529            return;
14530        }
14531        if (userId != UserHandle.USER_ALL) {
14532            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14533                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14534            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14535                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14536            }
14537        } else {
14538            for (int currentUserId : sUserManager.getUserIds()) {
14539                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14540                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14541                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14542                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14543                }
14544            }
14545        }
14546    }
14547
14548    boolean isUserRestricted(int userId, String restrictionKey) {
14549        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14550        if (restrictions.getBoolean(restrictionKey, false)) {
14551            Log.w(TAG, "User is restricted: " + restrictionKey);
14552            return true;
14553        }
14554        return false;
14555    }
14556
14557    @Override
14558    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14559            int userId) {
14560        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14561        final int callingUid = Binder.getCallingUid();
14562        enforceCrossUserPermission(callingUid, userId,
14563                true /* requireFullPermission */, true /* checkShell */,
14564                "setPackagesSuspended for user " + userId);
14565
14566        if (ArrayUtils.isEmpty(packageNames)) {
14567            return packageNames;
14568        }
14569
14570        // List of package names for whom the suspended state has changed.
14571        List<String> changedPackages = new ArrayList<>(packageNames.length);
14572        // List of package names for whom the suspended state is not set as requested in this
14573        // method.
14574        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14575        long callingId = Binder.clearCallingIdentity();
14576        try {
14577            for (int i = 0; i < packageNames.length; i++) {
14578                String packageName = packageNames[i];
14579                boolean changed = false;
14580                final int appId;
14581                synchronized (mPackages) {
14582                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14583                    if (pkgSetting == null
14584                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14585                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14586                                + "\". Skipping suspending/un-suspending.");
14587                        unactionedPackages.add(packageName);
14588                        continue;
14589                    }
14590                    appId = pkgSetting.appId;
14591                    if (pkgSetting.getSuspended(userId) != suspended) {
14592                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14593                            unactionedPackages.add(packageName);
14594                            continue;
14595                        }
14596                        pkgSetting.setSuspended(suspended, userId);
14597                        mSettings.writePackageRestrictionsLPr(userId);
14598                        changed = true;
14599                        changedPackages.add(packageName);
14600                    }
14601                }
14602
14603                if (changed && suspended) {
14604                    killApplication(packageName, UserHandle.getUid(userId, appId),
14605                            "suspending package");
14606                }
14607            }
14608        } finally {
14609            Binder.restoreCallingIdentity(callingId);
14610        }
14611
14612        if (!changedPackages.isEmpty()) {
14613            sendPackagesSuspendedForUser(changedPackages.toArray(
14614                    new String[changedPackages.size()]), userId, suspended);
14615        }
14616
14617        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14618    }
14619
14620    @Override
14621    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14622        final int callingUid = Binder.getCallingUid();
14623        enforceCrossUserPermission(callingUid, userId,
14624                true /* requireFullPermission */, false /* checkShell */,
14625                "isPackageSuspendedForUser for user " + userId);
14626        synchronized (mPackages) {
14627            final PackageSetting ps = mSettings.mPackages.get(packageName);
14628            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14629                throw new IllegalArgumentException("Unknown target package: " + packageName);
14630            }
14631            return ps.getSuspended(userId);
14632        }
14633    }
14634
14635    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14636        if (isPackageDeviceAdmin(packageName, userId)) {
14637            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14638                    + "\": has an active device admin");
14639            return false;
14640        }
14641
14642        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14643        if (packageName.equals(activeLauncherPackageName)) {
14644            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14645                    + "\": contains the active launcher");
14646            return false;
14647        }
14648
14649        if (packageName.equals(mRequiredInstallerPackage)) {
14650            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14651                    + "\": required for package installation");
14652            return false;
14653        }
14654
14655        if (packageName.equals(mRequiredUninstallerPackage)) {
14656            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14657                    + "\": required for package uninstallation");
14658            return false;
14659        }
14660
14661        if (packageName.equals(mRequiredVerifierPackage)) {
14662            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14663                    + "\": required for package verification");
14664            return false;
14665        }
14666
14667        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14668            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14669                    + "\": is the default dialer");
14670            return false;
14671        }
14672
14673        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14674            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14675                    + "\": protected package");
14676            return false;
14677        }
14678
14679        // Cannot suspend static shared libs as they are considered
14680        // a part of the using app (emulating static linking). Also
14681        // static libs are installed always on internal storage.
14682        PackageParser.Package pkg = mPackages.get(packageName);
14683        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14684            Slog.w(TAG, "Cannot suspend package: " + packageName
14685                    + " providing static shared library: "
14686                    + pkg.staticSharedLibName);
14687            return false;
14688        }
14689
14690        return true;
14691    }
14692
14693    private String getActiveLauncherPackageName(int userId) {
14694        Intent intent = new Intent(Intent.ACTION_MAIN);
14695        intent.addCategory(Intent.CATEGORY_HOME);
14696        ResolveInfo resolveInfo = resolveIntent(
14697                intent,
14698                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14699                PackageManager.MATCH_DEFAULT_ONLY,
14700                userId);
14701
14702        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14703    }
14704
14705    private String getDefaultDialerPackageName(int userId) {
14706        synchronized (mPackages) {
14707            return mSettings.getDefaultDialerPackageNameLPw(userId);
14708        }
14709    }
14710
14711    @Override
14712    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14713        mContext.enforceCallingOrSelfPermission(
14714                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14715                "Only package verification agents can verify applications");
14716
14717        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14718        final PackageVerificationResponse response = new PackageVerificationResponse(
14719                verificationCode, Binder.getCallingUid());
14720        msg.arg1 = id;
14721        msg.obj = response;
14722        mHandler.sendMessage(msg);
14723    }
14724
14725    @Override
14726    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14727            long millisecondsToDelay) {
14728        mContext.enforceCallingOrSelfPermission(
14729                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14730                "Only package verification agents can extend verification timeouts");
14731
14732        final PackageVerificationState state = mPendingVerification.get(id);
14733        final PackageVerificationResponse response = new PackageVerificationResponse(
14734                verificationCodeAtTimeout, Binder.getCallingUid());
14735
14736        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14737            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14738        }
14739        if (millisecondsToDelay < 0) {
14740            millisecondsToDelay = 0;
14741        }
14742        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14743                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14744            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14745        }
14746
14747        if ((state != null) && !state.timeoutExtended()) {
14748            state.extendTimeout();
14749
14750            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14751            msg.arg1 = id;
14752            msg.obj = response;
14753            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14754        }
14755    }
14756
14757    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14758            int verificationCode, UserHandle user) {
14759        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14760        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14761        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14762        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14763        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14764
14765        mContext.sendBroadcastAsUser(intent, user,
14766                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14767    }
14768
14769    private ComponentName matchComponentForVerifier(String packageName,
14770            List<ResolveInfo> receivers) {
14771        ActivityInfo targetReceiver = null;
14772
14773        final int NR = receivers.size();
14774        for (int i = 0; i < NR; i++) {
14775            final ResolveInfo info = receivers.get(i);
14776            if (info.activityInfo == null) {
14777                continue;
14778            }
14779
14780            if (packageName.equals(info.activityInfo.packageName)) {
14781                targetReceiver = info.activityInfo;
14782                break;
14783            }
14784        }
14785
14786        if (targetReceiver == null) {
14787            return null;
14788        }
14789
14790        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14791    }
14792
14793    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14794            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14795        if (pkgInfo.verifiers.length == 0) {
14796            return null;
14797        }
14798
14799        final int N = pkgInfo.verifiers.length;
14800        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14801        for (int i = 0; i < N; i++) {
14802            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14803
14804            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14805                    receivers);
14806            if (comp == null) {
14807                continue;
14808            }
14809
14810            final int verifierUid = getUidForVerifier(verifierInfo);
14811            if (verifierUid == -1) {
14812                continue;
14813            }
14814
14815            if (DEBUG_VERIFY) {
14816                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14817                        + " with the correct signature");
14818            }
14819            sufficientVerifiers.add(comp);
14820            verificationState.addSufficientVerifier(verifierUid);
14821        }
14822
14823        return sufficientVerifiers;
14824    }
14825
14826    private int getUidForVerifier(VerifierInfo verifierInfo) {
14827        synchronized (mPackages) {
14828            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14829            if (pkg == null) {
14830                return -1;
14831            } else if (pkg.mSignatures.length != 1) {
14832                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14833                        + " has more than one signature; ignoring");
14834                return -1;
14835            }
14836
14837            /*
14838             * If the public key of the package's signature does not match
14839             * our expected public key, then this is a different package and
14840             * we should skip.
14841             */
14842
14843            final byte[] expectedPublicKey;
14844            try {
14845                final Signature verifierSig = pkg.mSignatures[0];
14846                final PublicKey publicKey = verifierSig.getPublicKey();
14847                expectedPublicKey = publicKey.getEncoded();
14848            } catch (CertificateException e) {
14849                return -1;
14850            }
14851
14852            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14853
14854            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14855                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14856                        + " does not have the expected public key; ignoring");
14857                return -1;
14858            }
14859
14860            return pkg.applicationInfo.uid;
14861        }
14862    }
14863
14864    @Override
14865    public void finishPackageInstall(int token, boolean didLaunch) {
14866        enforceSystemOrRoot("Only the system is allowed to finish installs");
14867
14868        if (DEBUG_INSTALL) {
14869            Slog.v(TAG, "BM finishing package install for " + token);
14870        }
14871        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14872
14873        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14874        mHandler.sendMessage(msg);
14875    }
14876
14877    /**
14878     * Get the verification agent timeout.  Used for both the APK verifier and the
14879     * intent filter verifier.
14880     *
14881     * @return verification timeout in milliseconds
14882     */
14883    private long getVerificationTimeout() {
14884        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14885                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14886                DEFAULT_VERIFICATION_TIMEOUT);
14887    }
14888
14889    /**
14890     * Get the default verification agent response code.
14891     *
14892     * @return default verification response code
14893     */
14894    private int getDefaultVerificationResponse(UserHandle user) {
14895        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14896            return PackageManager.VERIFICATION_REJECT;
14897        }
14898        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14899                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14900                DEFAULT_VERIFICATION_RESPONSE);
14901    }
14902
14903    /**
14904     * Check whether or not package verification has been enabled.
14905     *
14906     * @return true if verification should be performed
14907     */
14908    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14909        if (!DEFAULT_VERIFY_ENABLE) {
14910            return false;
14911        }
14912
14913        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14914
14915        // Check if installing from ADB
14916        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14917            // Do not run verification in a test harness environment
14918            if (ActivityManager.isRunningInTestHarness()) {
14919                return false;
14920            }
14921            if (ensureVerifyAppsEnabled) {
14922                return true;
14923            }
14924            // Check if the developer does not want package verification for ADB installs
14925            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14926                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14927                return false;
14928            }
14929        } else {
14930            // only when not installed from ADB, skip verification for instant apps when
14931            // the installer and verifier are the same.
14932            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14933                if (mInstantAppInstallerActivity != null
14934                        && mInstantAppInstallerActivity.packageName.equals(
14935                                mRequiredVerifierPackage)) {
14936                    try {
14937                        mContext.getSystemService(AppOpsManager.class)
14938                                .checkPackage(installerUid, mRequiredVerifierPackage);
14939                        if (DEBUG_VERIFY) {
14940                            Slog.i(TAG, "disable verification for instant app");
14941                        }
14942                        return false;
14943                    } catch (SecurityException ignore) { }
14944                }
14945            }
14946        }
14947
14948        if (ensureVerifyAppsEnabled) {
14949            return true;
14950        }
14951
14952        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14953                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14954    }
14955
14956    @Override
14957    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14958            throws RemoteException {
14959        mContext.enforceCallingOrSelfPermission(
14960                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14961                "Only intentfilter verification agents can verify applications");
14962
14963        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14964        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14965                Binder.getCallingUid(), verificationCode, failedDomains);
14966        msg.arg1 = id;
14967        msg.obj = response;
14968        mHandler.sendMessage(msg);
14969    }
14970
14971    @Override
14972    public int getIntentVerificationStatus(String packageName, int userId) {
14973        final int callingUid = Binder.getCallingUid();
14974        if (getInstantAppPackageName(callingUid) != null) {
14975            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14976        }
14977        synchronized (mPackages) {
14978            final PackageSetting ps = mSettings.mPackages.get(packageName);
14979            if (ps == null
14980                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14981                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14982            }
14983            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14984        }
14985    }
14986
14987    @Override
14988    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14989        mContext.enforceCallingOrSelfPermission(
14990                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14991
14992        boolean result = false;
14993        synchronized (mPackages) {
14994            final PackageSetting ps = mSettings.mPackages.get(packageName);
14995            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14996                return false;
14997            }
14998            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14999        }
15000        if (result) {
15001            scheduleWritePackageRestrictionsLocked(userId);
15002        }
15003        return result;
15004    }
15005
15006    @Override
15007    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15008            String packageName) {
15009        final int callingUid = Binder.getCallingUid();
15010        if (getInstantAppPackageName(callingUid) != null) {
15011            return ParceledListSlice.emptyList();
15012        }
15013        synchronized (mPackages) {
15014            final PackageSetting ps = mSettings.mPackages.get(packageName);
15015            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15016                return ParceledListSlice.emptyList();
15017            }
15018            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15019        }
15020    }
15021
15022    @Override
15023    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15024        if (TextUtils.isEmpty(packageName)) {
15025            return ParceledListSlice.emptyList();
15026        }
15027        final int callingUid = Binder.getCallingUid();
15028        final int callingUserId = UserHandle.getUserId(callingUid);
15029        synchronized (mPackages) {
15030            PackageParser.Package pkg = mPackages.get(packageName);
15031            if (pkg == null || pkg.activities == null) {
15032                return ParceledListSlice.emptyList();
15033            }
15034            if (pkg.mExtras == null) {
15035                return ParceledListSlice.emptyList();
15036            }
15037            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15038            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15039                return ParceledListSlice.emptyList();
15040            }
15041            final int count = pkg.activities.size();
15042            ArrayList<IntentFilter> result = new ArrayList<>();
15043            for (int n=0; n<count; n++) {
15044                PackageParser.Activity activity = pkg.activities.get(n);
15045                if (activity.intents != null && activity.intents.size() > 0) {
15046                    result.addAll(activity.intents);
15047                }
15048            }
15049            return new ParceledListSlice<>(result);
15050        }
15051    }
15052
15053    @Override
15054    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15055        mContext.enforceCallingOrSelfPermission(
15056                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15057
15058        synchronized (mPackages) {
15059            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15060            if (packageName != null) {
15061                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15062                        packageName, userId);
15063            }
15064            return result;
15065        }
15066    }
15067
15068    @Override
15069    public String getDefaultBrowserPackageName(int userId) {
15070        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15071            return null;
15072        }
15073        synchronized (mPackages) {
15074            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15075        }
15076    }
15077
15078    /**
15079     * Get the "allow unknown sources" setting.
15080     *
15081     * @return the current "allow unknown sources" setting
15082     */
15083    private int getUnknownSourcesSettings() {
15084        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15085                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15086                -1);
15087    }
15088
15089    @Override
15090    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15091        final int callingUid = Binder.getCallingUid();
15092        if (getInstantAppPackageName(callingUid) != null) {
15093            return;
15094        }
15095        // writer
15096        synchronized (mPackages) {
15097            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15098            if (targetPackageSetting == null
15099                    || filterAppAccessLPr(
15100                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15101                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15102            }
15103
15104            PackageSetting installerPackageSetting;
15105            if (installerPackageName != null) {
15106                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15107                if (installerPackageSetting == null) {
15108                    throw new IllegalArgumentException("Unknown installer package: "
15109                            + installerPackageName);
15110                }
15111            } else {
15112                installerPackageSetting = null;
15113            }
15114
15115            Signature[] callerSignature;
15116            Object obj = mSettings.getUserIdLPr(callingUid);
15117            if (obj != null) {
15118                if (obj instanceof SharedUserSetting) {
15119                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15120                } else if (obj instanceof PackageSetting) {
15121                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15122                } else {
15123                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15124                }
15125            } else {
15126                throw new SecurityException("Unknown calling UID: " + callingUid);
15127            }
15128
15129            // Verify: can't set installerPackageName to a package that is
15130            // not signed with the same cert as the caller.
15131            if (installerPackageSetting != null) {
15132                if (compareSignatures(callerSignature,
15133                        installerPackageSetting.signatures.mSignatures)
15134                        != PackageManager.SIGNATURE_MATCH) {
15135                    throw new SecurityException(
15136                            "Caller does not have same cert as new installer package "
15137                            + installerPackageName);
15138                }
15139            }
15140
15141            // Verify: if target already has an installer package, it must
15142            // be signed with the same cert as the caller.
15143            if (targetPackageSetting.installerPackageName != null) {
15144                PackageSetting setting = mSettings.mPackages.get(
15145                        targetPackageSetting.installerPackageName);
15146                // If the currently set package isn't valid, then it's always
15147                // okay to change it.
15148                if (setting != null) {
15149                    if (compareSignatures(callerSignature,
15150                            setting.signatures.mSignatures)
15151                            != PackageManager.SIGNATURE_MATCH) {
15152                        throw new SecurityException(
15153                                "Caller does not have same cert as old installer package "
15154                                + targetPackageSetting.installerPackageName);
15155                    }
15156                }
15157            }
15158
15159            // Okay!
15160            targetPackageSetting.installerPackageName = installerPackageName;
15161            if (installerPackageName != null) {
15162                mSettings.mInstallerPackages.add(installerPackageName);
15163            }
15164            scheduleWriteSettingsLocked();
15165        }
15166    }
15167
15168    @Override
15169    public void setApplicationCategoryHint(String packageName, int categoryHint,
15170            String callerPackageName) {
15171        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15172            throw new SecurityException("Instant applications don't have access to this method");
15173        }
15174        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15175                callerPackageName);
15176        synchronized (mPackages) {
15177            PackageSetting ps = mSettings.mPackages.get(packageName);
15178            if (ps == null) {
15179                throw new IllegalArgumentException("Unknown target package " + packageName);
15180            }
15181            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15182                throw new IllegalArgumentException("Unknown target package " + packageName);
15183            }
15184            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15185                throw new IllegalArgumentException("Calling package " + callerPackageName
15186                        + " is not installer for " + packageName);
15187            }
15188
15189            if (ps.categoryHint != categoryHint) {
15190                ps.categoryHint = categoryHint;
15191                scheduleWriteSettingsLocked();
15192            }
15193        }
15194    }
15195
15196    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15197        // Queue up an async operation since the package installation may take a little while.
15198        mHandler.post(new Runnable() {
15199            public void run() {
15200                mHandler.removeCallbacks(this);
15201                 // Result object to be returned
15202                PackageInstalledInfo res = new PackageInstalledInfo();
15203                res.setReturnCode(currentStatus);
15204                res.uid = -1;
15205                res.pkg = null;
15206                res.removedInfo = null;
15207                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15208                    args.doPreInstall(res.returnCode);
15209                    synchronized (mInstallLock) {
15210                        installPackageTracedLI(args, res);
15211                    }
15212                    args.doPostInstall(res.returnCode, res.uid);
15213                }
15214
15215                // A restore should be performed at this point if (a) the install
15216                // succeeded, (b) the operation is not an update, and (c) the new
15217                // package has not opted out of backup participation.
15218                final boolean update = res.removedInfo != null
15219                        && res.removedInfo.removedPackage != null;
15220                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15221                boolean doRestore = !update
15222                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15223
15224                // Set up the post-install work request bookkeeping.  This will be used
15225                // and cleaned up by the post-install event handling regardless of whether
15226                // there's a restore pass performed.  Token values are >= 1.
15227                int token;
15228                if (mNextInstallToken < 0) mNextInstallToken = 1;
15229                token = mNextInstallToken++;
15230
15231                PostInstallData data = new PostInstallData(args, res);
15232                mRunningInstalls.put(token, data);
15233                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15234
15235                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15236                    // Pass responsibility to the Backup Manager.  It will perform a
15237                    // restore if appropriate, then pass responsibility back to the
15238                    // Package Manager to run the post-install observer callbacks
15239                    // and broadcasts.
15240                    IBackupManager bm = IBackupManager.Stub.asInterface(
15241                            ServiceManager.getService(Context.BACKUP_SERVICE));
15242                    if (bm != null) {
15243                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15244                                + " to BM for possible restore");
15245                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15246                        try {
15247                            // TODO: http://b/22388012
15248                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15249                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15250                            } else {
15251                                doRestore = false;
15252                            }
15253                        } catch (RemoteException e) {
15254                            // can't happen; the backup manager is local
15255                        } catch (Exception e) {
15256                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15257                            doRestore = false;
15258                        }
15259                    } else {
15260                        Slog.e(TAG, "Backup Manager not found!");
15261                        doRestore = false;
15262                    }
15263                }
15264
15265                if (!doRestore) {
15266                    // No restore possible, or the Backup Manager was mysteriously not
15267                    // available -- just fire the post-install work request directly.
15268                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15269
15270                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15271
15272                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15273                    mHandler.sendMessage(msg);
15274                }
15275            }
15276        });
15277    }
15278
15279    /**
15280     * Callback from PackageSettings whenever an app is first transitioned out of the
15281     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15282     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15283     * here whether the app is the target of an ongoing install, and only send the
15284     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15285     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15286     * handling.
15287     */
15288    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15289        // Serialize this with the rest of the install-process message chain.  In the
15290        // restore-at-install case, this Runnable will necessarily run before the
15291        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15292        // are coherent.  In the non-restore case, the app has already completed install
15293        // and been launched through some other means, so it is not in a problematic
15294        // state for observers to see the FIRST_LAUNCH signal.
15295        mHandler.post(new Runnable() {
15296            @Override
15297            public void run() {
15298                for (int i = 0; i < mRunningInstalls.size(); i++) {
15299                    final PostInstallData data = mRunningInstalls.valueAt(i);
15300                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15301                        continue;
15302                    }
15303                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15304                        // right package; but is it for the right user?
15305                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15306                            if (userId == data.res.newUsers[uIndex]) {
15307                                if (DEBUG_BACKUP) {
15308                                    Slog.i(TAG, "Package " + pkgName
15309                                            + " being restored so deferring FIRST_LAUNCH");
15310                                }
15311                                return;
15312                            }
15313                        }
15314                    }
15315                }
15316                // didn't find it, so not being restored
15317                if (DEBUG_BACKUP) {
15318                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15319                }
15320                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15321            }
15322        });
15323    }
15324
15325    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15326        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15327                installerPkg, null, userIds);
15328    }
15329
15330    private abstract class HandlerParams {
15331        private static final int MAX_RETRIES = 4;
15332
15333        /**
15334         * Number of times startCopy() has been attempted and had a non-fatal
15335         * error.
15336         */
15337        private int mRetries = 0;
15338
15339        /** User handle for the user requesting the information or installation. */
15340        private final UserHandle mUser;
15341        String traceMethod;
15342        int traceCookie;
15343
15344        HandlerParams(UserHandle user) {
15345            mUser = user;
15346        }
15347
15348        UserHandle getUser() {
15349            return mUser;
15350        }
15351
15352        HandlerParams setTraceMethod(String traceMethod) {
15353            this.traceMethod = traceMethod;
15354            return this;
15355        }
15356
15357        HandlerParams setTraceCookie(int traceCookie) {
15358            this.traceCookie = traceCookie;
15359            return this;
15360        }
15361
15362        final boolean startCopy() {
15363            boolean res;
15364            try {
15365                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15366
15367                if (++mRetries > MAX_RETRIES) {
15368                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15369                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15370                    handleServiceError();
15371                    return false;
15372                } else {
15373                    handleStartCopy();
15374                    res = true;
15375                }
15376            } catch (RemoteException e) {
15377                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15378                mHandler.sendEmptyMessage(MCS_RECONNECT);
15379                res = false;
15380            }
15381            handleReturnCode();
15382            return res;
15383        }
15384
15385        final void serviceError() {
15386            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15387            handleServiceError();
15388            handleReturnCode();
15389        }
15390
15391        abstract void handleStartCopy() throws RemoteException;
15392        abstract void handleServiceError();
15393        abstract void handleReturnCode();
15394    }
15395
15396    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15397        for (File path : paths) {
15398            try {
15399                mcs.clearDirectory(path.getAbsolutePath());
15400            } catch (RemoteException e) {
15401            }
15402        }
15403    }
15404
15405    static class OriginInfo {
15406        /**
15407         * Location where install is coming from, before it has been
15408         * copied/renamed into place. This could be a single monolithic APK
15409         * file, or a cluster directory. This location may be untrusted.
15410         */
15411        final File file;
15412        final String cid;
15413
15414        /**
15415         * Flag indicating that {@link #file} or {@link #cid} has already been
15416         * staged, meaning downstream users don't need to defensively copy the
15417         * contents.
15418         */
15419        final boolean staged;
15420
15421        /**
15422         * Flag indicating that {@link #file} or {@link #cid} is an already
15423         * installed app that is being moved.
15424         */
15425        final boolean existing;
15426
15427        final String resolvedPath;
15428        final File resolvedFile;
15429
15430        static OriginInfo fromNothing() {
15431            return new OriginInfo(null, null, false, false);
15432        }
15433
15434        static OriginInfo fromUntrustedFile(File file) {
15435            return new OriginInfo(file, null, false, false);
15436        }
15437
15438        static OriginInfo fromExistingFile(File file) {
15439            return new OriginInfo(file, null, false, true);
15440        }
15441
15442        static OriginInfo fromStagedFile(File file) {
15443            return new OriginInfo(file, null, true, false);
15444        }
15445
15446        static OriginInfo fromStagedContainer(String cid) {
15447            return new OriginInfo(null, cid, true, false);
15448        }
15449
15450        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15451            this.file = file;
15452            this.cid = cid;
15453            this.staged = staged;
15454            this.existing = existing;
15455
15456            if (cid != null) {
15457                resolvedPath = PackageHelper.getSdDir(cid);
15458                resolvedFile = new File(resolvedPath);
15459            } else if (file != null) {
15460                resolvedPath = file.getAbsolutePath();
15461                resolvedFile = file;
15462            } else {
15463                resolvedPath = null;
15464                resolvedFile = null;
15465            }
15466        }
15467    }
15468
15469    static class MoveInfo {
15470        final int moveId;
15471        final String fromUuid;
15472        final String toUuid;
15473        final String packageName;
15474        final String dataAppName;
15475        final int appId;
15476        final String seinfo;
15477        final int targetSdkVersion;
15478
15479        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15480                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15481            this.moveId = moveId;
15482            this.fromUuid = fromUuid;
15483            this.toUuid = toUuid;
15484            this.packageName = packageName;
15485            this.dataAppName = dataAppName;
15486            this.appId = appId;
15487            this.seinfo = seinfo;
15488            this.targetSdkVersion = targetSdkVersion;
15489        }
15490    }
15491
15492    static class VerificationInfo {
15493        /** A constant used to indicate that a uid value is not present. */
15494        public static final int NO_UID = -1;
15495
15496        /** URI referencing where the package was downloaded from. */
15497        final Uri originatingUri;
15498
15499        /** HTTP referrer URI associated with the originatingURI. */
15500        final Uri referrer;
15501
15502        /** UID of the application that the install request originated from. */
15503        final int originatingUid;
15504
15505        /** UID of application requesting the install */
15506        final int installerUid;
15507
15508        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15509            this.originatingUri = originatingUri;
15510            this.referrer = referrer;
15511            this.originatingUid = originatingUid;
15512            this.installerUid = installerUid;
15513        }
15514    }
15515
15516    class InstallParams extends HandlerParams {
15517        final OriginInfo origin;
15518        final MoveInfo move;
15519        final IPackageInstallObserver2 observer;
15520        int installFlags;
15521        final String installerPackageName;
15522        final String volumeUuid;
15523        private InstallArgs mArgs;
15524        private int mRet;
15525        final String packageAbiOverride;
15526        final String[] grantedRuntimePermissions;
15527        final VerificationInfo verificationInfo;
15528        final Certificate[][] certificates;
15529        final int installReason;
15530
15531        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15532                int installFlags, String installerPackageName, String volumeUuid,
15533                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15534                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15535            super(user);
15536            this.origin = origin;
15537            this.move = move;
15538            this.observer = observer;
15539            this.installFlags = installFlags;
15540            this.installerPackageName = installerPackageName;
15541            this.volumeUuid = volumeUuid;
15542            this.verificationInfo = verificationInfo;
15543            this.packageAbiOverride = packageAbiOverride;
15544            this.grantedRuntimePermissions = grantedPermissions;
15545            this.certificates = certificates;
15546            this.installReason = installReason;
15547        }
15548
15549        @Override
15550        public String toString() {
15551            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15552                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15553        }
15554
15555        private int installLocationPolicy(PackageInfoLite pkgLite) {
15556            String packageName = pkgLite.packageName;
15557            int installLocation = pkgLite.installLocation;
15558            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15559            // reader
15560            synchronized (mPackages) {
15561                // Currently installed package which the new package is attempting to replace or
15562                // null if no such package is installed.
15563                PackageParser.Package installedPkg = mPackages.get(packageName);
15564                // Package which currently owns the data which the new package will own if installed.
15565                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15566                // will be null whereas dataOwnerPkg will contain information about the package
15567                // which was uninstalled while keeping its data.
15568                PackageParser.Package dataOwnerPkg = installedPkg;
15569                if (dataOwnerPkg  == null) {
15570                    PackageSetting ps = mSettings.mPackages.get(packageName);
15571                    if (ps != null) {
15572                        dataOwnerPkg = ps.pkg;
15573                    }
15574                }
15575
15576                if (dataOwnerPkg != null) {
15577                    // If installed, the package will get access to data left on the device by its
15578                    // predecessor. As a security measure, this is permited only if this is not a
15579                    // version downgrade or if the predecessor package is marked as debuggable and
15580                    // a downgrade is explicitly requested.
15581                    //
15582                    // On debuggable platform builds, downgrades are permitted even for
15583                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15584                    // not offer security guarantees and thus it's OK to disable some security
15585                    // mechanisms to make debugging/testing easier on those builds. However, even on
15586                    // debuggable builds downgrades of packages are permitted only if requested via
15587                    // installFlags. This is because we aim to keep the behavior of debuggable
15588                    // platform builds as close as possible to the behavior of non-debuggable
15589                    // platform builds.
15590                    final boolean downgradeRequested =
15591                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15592                    final boolean packageDebuggable =
15593                                (dataOwnerPkg.applicationInfo.flags
15594                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15595                    final boolean downgradePermitted =
15596                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15597                    if (!downgradePermitted) {
15598                        try {
15599                            checkDowngrade(dataOwnerPkg, pkgLite);
15600                        } catch (PackageManagerException e) {
15601                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15602                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15603                        }
15604                    }
15605                }
15606
15607                if (installedPkg != null) {
15608                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15609                        // Check for updated system application.
15610                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15611                            if (onSd) {
15612                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15613                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15614                            }
15615                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15616                        } else {
15617                            if (onSd) {
15618                                // Install flag overrides everything.
15619                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15620                            }
15621                            // If current upgrade specifies particular preference
15622                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15623                                // Application explicitly specified internal.
15624                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15625                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15626                                // App explictly prefers external. Let policy decide
15627                            } else {
15628                                // Prefer previous location
15629                                if (isExternal(installedPkg)) {
15630                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15631                                }
15632                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15633                            }
15634                        }
15635                    } else {
15636                        // Invalid install. Return error code
15637                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15638                    }
15639                }
15640            }
15641            // All the special cases have been taken care of.
15642            // Return result based on recommended install location.
15643            if (onSd) {
15644                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15645            }
15646            return pkgLite.recommendedInstallLocation;
15647        }
15648
15649        /*
15650         * Invoke remote method to get package information and install
15651         * location values. Override install location based on default
15652         * policy if needed and then create install arguments based
15653         * on the install location.
15654         */
15655        public void handleStartCopy() throws RemoteException {
15656            int ret = PackageManager.INSTALL_SUCCEEDED;
15657
15658            // If we're already staged, we've firmly committed to an install location
15659            if (origin.staged) {
15660                if (origin.file != null) {
15661                    installFlags |= PackageManager.INSTALL_INTERNAL;
15662                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15663                } else if (origin.cid != null) {
15664                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15665                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15666                } else {
15667                    throw new IllegalStateException("Invalid stage location");
15668                }
15669            }
15670
15671            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15672            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15673            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15674            PackageInfoLite pkgLite = null;
15675
15676            if (onInt && onSd) {
15677                // Check if both bits are set.
15678                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15679                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15680            } else if (onSd && ephemeral) {
15681                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15682                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15683            } else {
15684                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15685                        packageAbiOverride);
15686
15687                if (DEBUG_EPHEMERAL && ephemeral) {
15688                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15689                }
15690
15691                /*
15692                 * If we have too little free space, try to free cache
15693                 * before giving up.
15694                 */
15695                if (!origin.staged && pkgLite.recommendedInstallLocation
15696                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15697                    // TODO: focus freeing disk space on the target device
15698                    final StorageManager storage = StorageManager.from(mContext);
15699                    final long lowThreshold = storage.getStorageLowBytes(
15700                            Environment.getDataDirectory());
15701
15702                    final long sizeBytes = mContainerService.calculateInstalledSize(
15703                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15704
15705                    try {
15706                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15707                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15708                                installFlags, packageAbiOverride);
15709                    } catch (InstallerException e) {
15710                        Slog.w(TAG, "Failed to free cache", e);
15711                    }
15712
15713                    /*
15714                     * The cache free must have deleted the file we
15715                     * downloaded to install.
15716                     *
15717                     * TODO: fix the "freeCache" call to not delete
15718                     *       the file we care about.
15719                     */
15720                    if (pkgLite.recommendedInstallLocation
15721                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15722                        pkgLite.recommendedInstallLocation
15723                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15724                    }
15725                }
15726            }
15727
15728            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15729                int loc = pkgLite.recommendedInstallLocation;
15730                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15731                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15732                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15733                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15734                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15735                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15736                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15737                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15738                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15739                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15740                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15741                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15742                } else {
15743                    // Override with defaults if needed.
15744                    loc = installLocationPolicy(pkgLite);
15745                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15746                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15747                    } else if (!onSd && !onInt) {
15748                        // Override install location with flags
15749                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15750                            // Set the flag to install on external media.
15751                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15752                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15753                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15754                            if (DEBUG_EPHEMERAL) {
15755                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15756                            }
15757                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15758                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15759                                    |PackageManager.INSTALL_INTERNAL);
15760                        } else {
15761                            // Make sure the flag for installing on external
15762                            // media is unset
15763                            installFlags |= PackageManager.INSTALL_INTERNAL;
15764                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15765                        }
15766                    }
15767                }
15768            }
15769
15770            final InstallArgs args = createInstallArgs(this);
15771            mArgs = args;
15772
15773            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15774                // TODO: http://b/22976637
15775                // Apps installed for "all" users use the device owner to verify the app
15776                UserHandle verifierUser = getUser();
15777                if (verifierUser == UserHandle.ALL) {
15778                    verifierUser = UserHandle.SYSTEM;
15779                }
15780
15781                /*
15782                 * Determine if we have any installed package verifiers. If we
15783                 * do, then we'll defer to them to verify the packages.
15784                 */
15785                final int requiredUid = mRequiredVerifierPackage == null ? -1
15786                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15787                                verifierUser.getIdentifier());
15788                final int installerUid =
15789                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15790                if (!origin.existing && requiredUid != -1
15791                        && isVerificationEnabled(
15792                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15793                    final Intent verification = new Intent(
15794                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15795                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15796                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15797                            PACKAGE_MIME_TYPE);
15798                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15799
15800                    // Query all live verifiers based on current user state
15801                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15802                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15803
15804                    if (DEBUG_VERIFY) {
15805                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15806                                + verification.toString() + " with " + pkgLite.verifiers.length
15807                                + " optional verifiers");
15808                    }
15809
15810                    final int verificationId = mPendingVerificationToken++;
15811
15812                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15813
15814                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15815                            installerPackageName);
15816
15817                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15818                            installFlags);
15819
15820                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15821                            pkgLite.packageName);
15822
15823                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15824                            pkgLite.versionCode);
15825
15826                    if (verificationInfo != null) {
15827                        if (verificationInfo.originatingUri != null) {
15828                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15829                                    verificationInfo.originatingUri);
15830                        }
15831                        if (verificationInfo.referrer != null) {
15832                            verification.putExtra(Intent.EXTRA_REFERRER,
15833                                    verificationInfo.referrer);
15834                        }
15835                        if (verificationInfo.originatingUid >= 0) {
15836                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15837                                    verificationInfo.originatingUid);
15838                        }
15839                        if (verificationInfo.installerUid >= 0) {
15840                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15841                                    verificationInfo.installerUid);
15842                        }
15843                    }
15844
15845                    final PackageVerificationState verificationState = new PackageVerificationState(
15846                            requiredUid, args);
15847
15848                    mPendingVerification.append(verificationId, verificationState);
15849
15850                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15851                            receivers, verificationState);
15852
15853                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15854                    final long idleDuration = getVerificationTimeout();
15855
15856                    /*
15857                     * If any sufficient verifiers were listed in the package
15858                     * manifest, attempt to ask them.
15859                     */
15860                    if (sufficientVerifiers != null) {
15861                        final int N = sufficientVerifiers.size();
15862                        if (N == 0) {
15863                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15864                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15865                        } else {
15866                            for (int i = 0; i < N; i++) {
15867                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15868                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15869                                        verifierComponent.getPackageName(), idleDuration,
15870                                        verifierUser.getIdentifier(), false, "package verifier");
15871
15872                                final Intent sufficientIntent = new Intent(verification);
15873                                sufficientIntent.setComponent(verifierComponent);
15874                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15875                            }
15876                        }
15877                    }
15878
15879                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15880                            mRequiredVerifierPackage, receivers);
15881                    if (ret == PackageManager.INSTALL_SUCCEEDED
15882                            && mRequiredVerifierPackage != null) {
15883                        Trace.asyncTraceBegin(
15884                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15885                        /*
15886                         * Send the intent to the required verification agent,
15887                         * but only start the verification timeout after the
15888                         * target BroadcastReceivers have run.
15889                         */
15890                        verification.setComponent(requiredVerifierComponent);
15891                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15892                                mRequiredVerifierPackage, idleDuration,
15893                                verifierUser.getIdentifier(), false, "package verifier");
15894                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15895                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15896                                new BroadcastReceiver() {
15897                                    @Override
15898                                    public void onReceive(Context context, Intent intent) {
15899                                        final Message msg = mHandler
15900                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15901                                        msg.arg1 = verificationId;
15902                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15903                                    }
15904                                }, null, 0, null, null);
15905
15906                        /*
15907                         * We don't want the copy to proceed until verification
15908                         * succeeds, so null out this field.
15909                         */
15910                        mArgs = null;
15911                    }
15912                } else {
15913                    /*
15914                     * No package verification is enabled, so immediately start
15915                     * the remote call to initiate copy using temporary file.
15916                     */
15917                    ret = args.copyApk(mContainerService, true);
15918                }
15919            }
15920
15921            mRet = ret;
15922        }
15923
15924        @Override
15925        void handleReturnCode() {
15926            // If mArgs is null, then MCS couldn't be reached. When it
15927            // reconnects, it will try again to install. At that point, this
15928            // will succeed.
15929            if (mArgs != null) {
15930                processPendingInstall(mArgs, mRet);
15931            }
15932        }
15933
15934        @Override
15935        void handleServiceError() {
15936            mArgs = createInstallArgs(this);
15937            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15938        }
15939
15940        public boolean isForwardLocked() {
15941            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15942        }
15943    }
15944
15945    /**
15946     * Used during creation of InstallArgs
15947     *
15948     * @param installFlags package installation flags
15949     * @return true if should be installed on external storage
15950     */
15951    private static boolean installOnExternalAsec(int installFlags) {
15952        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15953            return false;
15954        }
15955        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15956            return true;
15957        }
15958        return false;
15959    }
15960
15961    /**
15962     * Used during creation of InstallArgs
15963     *
15964     * @param installFlags package installation flags
15965     * @return true if should be installed as forward locked
15966     */
15967    private static boolean installForwardLocked(int installFlags) {
15968        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15969    }
15970
15971    private InstallArgs createInstallArgs(InstallParams params) {
15972        if (params.move != null) {
15973            return new MoveInstallArgs(params);
15974        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15975            return new AsecInstallArgs(params);
15976        } else {
15977            return new FileInstallArgs(params);
15978        }
15979    }
15980
15981    /**
15982     * Create args that describe an existing installed package. Typically used
15983     * when cleaning up old installs, or used as a move source.
15984     */
15985    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15986            String resourcePath, String[] instructionSets) {
15987        final boolean isInAsec;
15988        if (installOnExternalAsec(installFlags)) {
15989            /* Apps on SD card are always in ASEC containers. */
15990            isInAsec = true;
15991        } else if (installForwardLocked(installFlags)
15992                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15993            /*
15994             * Forward-locked apps are only in ASEC containers if they're the
15995             * new style
15996             */
15997            isInAsec = true;
15998        } else {
15999            isInAsec = false;
16000        }
16001
16002        if (isInAsec) {
16003            return new AsecInstallArgs(codePath, instructionSets,
16004                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16005        } else {
16006            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16007        }
16008    }
16009
16010    static abstract class InstallArgs {
16011        /** @see InstallParams#origin */
16012        final OriginInfo origin;
16013        /** @see InstallParams#move */
16014        final MoveInfo move;
16015
16016        final IPackageInstallObserver2 observer;
16017        // Always refers to PackageManager flags only
16018        final int installFlags;
16019        final String installerPackageName;
16020        final String volumeUuid;
16021        final UserHandle user;
16022        final String abiOverride;
16023        final String[] installGrantPermissions;
16024        /** If non-null, drop an async trace when the install completes */
16025        final String traceMethod;
16026        final int traceCookie;
16027        final Certificate[][] certificates;
16028        final int installReason;
16029
16030        // The list of instruction sets supported by this app. This is currently
16031        // only used during the rmdex() phase to clean up resources. We can get rid of this
16032        // if we move dex files under the common app path.
16033        /* nullable */ String[] instructionSets;
16034
16035        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16036                int installFlags, String installerPackageName, String volumeUuid,
16037                UserHandle user, String[] instructionSets,
16038                String abiOverride, String[] installGrantPermissions,
16039                String traceMethod, int traceCookie, Certificate[][] certificates,
16040                int installReason) {
16041            this.origin = origin;
16042            this.move = move;
16043            this.installFlags = installFlags;
16044            this.observer = observer;
16045            this.installerPackageName = installerPackageName;
16046            this.volumeUuid = volumeUuid;
16047            this.user = user;
16048            this.instructionSets = instructionSets;
16049            this.abiOverride = abiOverride;
16050            this.installGrantPermissions = installGrantPermissions;
16051            this.traceMethod = traceMethod;
16052            this.traceCookie = traceCookie;
16053            this.certificates = certificates;
16054            this.installReason = installReason;
16055        }
16056
16057        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16058        abstract int doPreInstall(int status);
16059
16060        /**
16061         * Rename package into final resting place. All paths on the given
16062         * scanned package should be updated to reflect the rename.
16063         */
16064        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16065        abstract int doPostInstall(int status, int uid);
16066
16067        /** @see PackageSettingBase#codePathString */
16068        abstract String getCodePath();
16069        /** @see PackageSettingBase#resourcePathString */
16070        abstract String getResourcePath();
16071
16072        // Need installer lock especially for dex file removal.
16073        abstract void cleanUpResourcesLI();
16074        abstract boolean doPostDeleteLI(boolean delete);
16075
16076        /**
16077         * Called before the source arguments are copied. This is used mostly
16078         * for MoveParams when it needs to read the source file to put it in the
16079         * destination.
16080         */
16081        int doPreCopy() {
16082            return PackageManager.INSTALL_SUCCEEDED;
16083        }
16084
16085        /**
16086         * Called after the source arguments are copied. This is used mostly for
16087         * MoveParams when it needs to read the source file to put it in the
16088         * destination.
16089         */
16090        int doPostCopy(int uid) {
16091            return PackageManager.INSTALL_SUCCEEDED;
16092        }
16093
16094        protected boolean isFwdLocked() {
16095            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16096        }
16097
16098        protected boolean isExternalAsec() {
16099            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16100        }
16101
16102        protected boolean isEphemeral() {
16103            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16104        }
16105
16106        UserHandle getUser() {
16107            return user;
16108        }
16109    }
16110
16111    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16112        if (!allCodePaths.isEmpty()) {
16113            if (instructionSets == null) {
16114                throw new IllegalStateException("instructionSet == null");
16115            }
16116            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16117            for (String codePath : allCodePaths) {
16118                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16119                    try {
16120                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16121                    } catch (InstallerException ignored) {
16122                    }
16123                }
16124            }
16125        }
16126    }
16127
16128    /**
16129     * Logic to handle installation of non-ASEC applications, including copying
16130     * and renaming logic.
16131     */
16132    class FileInstallArgs extends InstallArgs {
16133        private File codeFile;
16134        private File resourceFile;
16135
16136        // Example topology:
16137        // /data/app/com.example/base.apk
16138        // /data/app/com.example/split_foo.apk
16139        // /data/app/com.example/lib/arm/libfoo.so
16140        // /data/app/com.example/lib/arm64/libfoo.so
16141        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16142
16143        /** New install */
16144        FileInstallArgs(InstallParams params) {
16145            super(params.origin, params.move, params.observer, params.installFlags,
16146                    params.installerPackageName, params.volumeUuid,
16147                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16148                    params.grantedRuntimePermissions,
16149                    params.traceMethod, params.traceCookie, params.certificates,
16150                    params.installReason);
16151            if (isFwdLocked()) {
16152                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16153            }
16154        }
16155
16156        /** Existing install */
16157        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16158            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16159                    null, null, null, 0, null /*certificates*/,
16160                    PackageManager.INSTALL_REASON_UNKNOWN);
16161            this.codeFile = (codePath != null) ? new File(codePath) : null;
16162            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16163        }
16164
16165        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16166            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16167            try {
16168                return doCopyApk(imcs, temp);
16169            } finally {
16170                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16171            }
16172        }
16173
16174        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16175            if (origin.staged) {
16176                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16177                codeFile = origin.file;
16178                resourceFile = origin.file;
16179                return PackageManager.INSTALL_SUCCEEDED;
16180            }
16181
16182            try {
16183                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16184                final File tempDir =
16185                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16186                codeFile = tempDir;
16187                resourceFile = tempDir;
16188            } catch (IOException e) {
16189                Slog.w(TAG, "Failed to create copy file: " + e);
16190                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16191            }
16192
16193            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16194                @Override
16195                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16196                    if (!FileUtils.isValidExtFilename(name)) {
16197                        throw new IllegalArgumentException("Invalid filename: " + name);
16198                    }
16199                    try {
16200                        final File file = new File(codeFile, name);
16201                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16202                                O_RDWR | O_CREAT, 0644);
16203                        Os.chmod(file.getAbsolutePath(), 0644);
16204                        return new ParcelFileDescriptor(fd);
16205                    } catch (ErrnoException e) {
16206                        throw new RemoteException("Failed to open: " + e.getMessage());
16207                    }
16208                }
16209            };
16210
16211            int ret = PackageManager.INSTALL_SUCCEEDED;
16212            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16213            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16214                Slog.e(TAG, "Failed to copy package");
16215                return ret;
16216            }
16217
16218            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16219            NativeLibraryHelper.Handle handle = null;
16220            try {
16221                handle = NativeLibraryHelper.Handle.create(codeFile);
16222                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16223                        abiOverride);
16224            } catch (IOException e) {
16225                Slog.e(TAG, "Copying native libraries failed", e);
16226                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16227            } finally {
16228                IoUtils.closeQuietly(handle);
16229            }
16230
16231            return ret;
16232        }
16233
16234        int doPreInstall(int status) {
16235            if (status != PackageManager.INSTALL_SUCCEEDED) {
16236                cleanUp();
16237            }
16238            return status;
16239        }
16240
16241        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16242            if (status != PackageManager.INSTALL_SUCCEEDED) {
16243                cleanUp();
16244                return false;
16245            }
16246
16247            final File targetDir = codeFile.getParentFile();
16248            final File beforeCodeFile = codeFile;
16249            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16250
16251            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16252            try {
16253                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16254            } catch (ErrnoException e) {
16255                Slog.w(TAG, "Failed to rename", e);
16256                return false;
16257            }
16258
16259            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16260                Slog.w(TAG, "Failed to restorecon");
16261                return false;
16262            }
16263
16264            // Reflect the rename internally
16265            codeFile = afterCodeFile;
16266            resourceFile = afterCodeFile;
16267
16268            // Reflect the rename in scanned details
16269            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16270            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16271                    afterCodeFile, pkg.baseCodePath));
16272            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16273                    afterCodeFile, pkg.splitCodePaths));
16274
16275            // Reflect the rename in app info
16276            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16277            pkg.setApplicationInfoCodePath(pkg.codePath);
16278            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16279            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16280            pkg.setApplicationInfoResourcePath(pkg.codePath);
16281            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16282            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16283
16284            return true;
16285        }
16286
16287        int doPostInstall(int status, int uid) {
16288            if (status != PackageManager.INSTALL_SUCCEEDED) {
16289                cleanUp();
16290            }
16291            return status;
16292        }
16293
16294        @Override
16295        String getCodePath() {
16296            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16297        }
16298
16299        @Override
16300        String getResourcePath() {
16301            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16302        }
16303
16304        private boolean cleanUp() {
16305            if (codeFile == null || !codeFile.exists()) {
16306                return false;
16307            }
16308
16309            removeCodePathLI(codeFile);
16310
16311            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16312                resourceFile.delete();
16313            }
16314
16315            return true;
16316        }
16317
16318        void cleanUpResourcesLI() {
16319            // Try enumerating all code paths before deleting
16320            List<String> allCodePaths = Collections.EMPTY_LIST;
16321            if (codeFile != null && codeFile.exists()) {
16322                try {
16323                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16324                    allCodePaths = pkg.getAllCodePaths();
16325                } catch (PackageParserException e) {
16326                    // Ignored; we tried our best
16327                }
16328            }
16329
16330            cleanUp();
16331            removeDexFiles(allCodePaths, instructionSets);
16332        }
16333
16334        boolean doPostDeleteLI(boolean delete) {
16335            // XXX err, shouldn't we respect the delete flag?
16336            cleanUpResourcesLI();
16337            return true;
16338        }
16339    }
16340
16341    private boolean isAsecExternal(String cid) {
16342        final String asecPath = PackageHelper.getSdFilesystem(cid);
16343        return !asecPath.startsWith(mAsecInternalPath);
16344    }
16345
16346    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16347            PackageManagerException {
16348        if (copyRet < 0) {
16349            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16350                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16351                throw new PackageManagerException(copyRet, message);
16352            }
16353        }
16354    }
16355
16356    /**
16357     * Extract the StorageManagerService "container ID" from the full code path of an
16358     * .apk.
16359     */
16360    static String cidFromCodePath(String fullCodePath) {
16361        int eidx = fullCodePath.lastIndexOf("/");
16362        String subStr1 = fullCodePath.substring(0, eidx);
16363        int sidx = subStr1.lastIndexOf("/");
16364        return subStr1.substring(sidx+1, eidx);
16365    }
16366
16367    /**
16368     * Logic to handle installation of ASEC applications, including copying and
16369     * renaming logic.
16370     */
16371    class AsecInstallArgs extends InstallArgs {
16372        static final String RES_FILE_NAME = "pkg.apk";
16373        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16374
16375        String cid;
16376        String packagePath;
16377        String resourcePath;
16378
16379        /** New install */
16380        AsecInstallArgs(InstallParams params) {
16381            super(params.origin, params.move, params.observer, params.installFlags,
16382                    params.installerPackageName, params.volumeUuid,
16383                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16384                    params.grantedRuntimePermissions,
16385                    params.traceMethod, params.traceCookie, params.certificates,
16386                    params.installReason);
16387        }
16388
16389        /** Existing install */
16390        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16391                        boolean isExternal, boolean isForwardLocked) {
16392            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16393                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16394                    instructionSets, null, null, null, 0, null /*certificates*/,
16395                    PackageManager.INSTALL_REASON_UNKNOWN);
16396            // Hackily pretend we're still looking at a full code path
16397            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16398                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16399            }
16400
16401            // Extract cid from fullCodePath
16402            int eidx = fullCodePath.lastIndexOf("/");
16403            String subStr1 = fullCodePath.substring(0, eidx);
16404            int sidx = subStr1.lastIndexOf("/");
16405            cid = subStr1.substring(sidx+1, eidx);
16406            setMountPath(subStr1);
16407        }
16408
16409        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16410            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16411                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16412                    instructionSets, null, null, null, 0, null /*certificates*/,
16413                    PackageManager.INSTALL_REASON_UNKNOWN);
16414            this.cid = cid;
16415            setMountPath(PackageHelper.getSdDir(cid));
16416        }
16417
16418        void createCopyFile() {
16419            cid = mInstallerService.allocateExternalStageCidLegacy();
16420        }
16421
16422        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16423            if (origin.staged && origin.cid != null) {
16424                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16425                cid = origin.cid;
16426                setMountPath(PackageHelper.getSdDir(cid));
16427                return PackageManager.INSTALL_SUCCEEDED;
16428            }
16429
16430            if (temp) {
16431                createCopyFile();
16432            } else {
16433                /*
16434                 * Pre-emptively destroy the container since it's destroyed if
16435                 * copying fails due to it existing anyway.
16436                 */
16437                PackageHelper.destroySdDir(cid);
16438            }
16439
16440            final String newMountPath = imcs.copyPackageToContainer(
16441                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16442                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16443
16444            if (newMountPath != null) {
16445                setMountPath(newMountPath);
16446                return PackageManager.INSTALL_SUCCEEDED;
16447            } else {
16448                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16449            }
16450        }
16451
16452        @Override
16453        String getCodePath() {
16454            return packagePath;
16455        }
16456
16457        @Override
16458        String getResourcePath() {
16459            return resourcePath;
16460        }
16461
16462        int doPreInstall(int status) {
16463            if (status != PackageManager.INSTALL_SUCCEEDED) {
16464                // Destroy container
16465                PackageHelper.destroySdDir(cid);
16466            } else {
16467                boolean mounted = PackageHelper.isContainerMounted(cid);
16468                if (!mounted) {
16469                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16470                            Process.SYSTEM_UID);
16471                    if (newMountPath != null) {
16472                        setMountPath(newMountPath);
16473                    } else {
16474                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16475                    }
16476                }
16477            }
16478            return status;
16479        }
16480
16481        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16482            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16483            String newMountPath = null;
16484            if (PackageHelper.isContainerMounted(cid)) {
16485                // Unmount the container
16486                if (!PackageHelper.unMountSdDir(cid)) {
16487                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16488                    return false;
16489                }
16490            }
16491            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16492                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16493                        " which might be stale. Will try to clean up.");
16494                // Clean up the stale container and proceed to recreate.
16495                if (!PackageHelper.destroySdDir(newCacheId)) {
16496                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16497                    return false;
16498                }
16499                // Successfully cleaned up stale container. Try to rename again.
16500                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16501                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16502                            + " inspite of cleaning it up.");
16503                    return false;
16504                }
16505            }
16506            if (!PackageHelper.isContainerMounted(newCacheId)) {
16507                Slog.w(TAG, "Mounting container " + newCacheId);
16508                newMountPath = PackageHelper.mountSdDir(newCacheId,
16509                        getEncryptKey(), Process.SYSTEM_UID);
16510            } else {
16511                newMountPath = PackageHelper.getSdDir(newCacheId);
16512            }
16513            if (newMountPath == null) {
16514                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16515                return false;
16516            }
16517            Log.i(TAG, "Succesfully renamed " + cid +
16518                    " to " + newCacheId +
16519                    " at new path: " + newMountPath);
16520            cid = newCacheId;
16521
16522            final File beforeCodeFile = new File(packagePath);
16523            setMountPath(newMountPath);
16524            final File afterCodeFile = new File(packagePath);
16525
16526            // Reflect the rename in scanned details
16527            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16528            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16529                    afterCodeFile, pkg.baseCodePath));
16530            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16531                    afterCodeFile, pkg.splitCodePaths));
16532
16533            // Reflect the rename in app info
16534            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16535            pkg.setApplicationInfoCodePath(pkg.codePath);
16536            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16537            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16538            pkg.setApplicationInfoResourcePath(pkg.codePath);
16539            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16540            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16541
16542            return true;
16543        }
16544
16545        private void setMountPath(String mountPath) {
16546            final File mountFile = new File(mountPath);
16547
16548            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16549            if (monolithicFile.exists()) {
16550                packagePath = monolithicFile.getAbsolutePath();
16551                if (isFwdLocked()) {
16552                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16553                } else {
16554                    resourcePath = packagePath;
16555                }
16556            } else {
16557                packagePath = mountFile.getAbsolutePath();
16558                resourcePath = packagePath;
16559            }
16560        }
16561
16562        int doPostInstall(int status, int uid) {
16563            if (status != PackageManager.INSTALL_SUCCEEDED) {
16564                cleanUp();
16565            } else {
16566                final int groupOwner;
16567                final String protectedFile;
16568                if (isFwdLocked()) {
16569                    groupOwner = UserHandle.getSharedAppGid(uid);
16570                    protectedFile = RES_FILE_NAME;
16571                } else {
16572                    groupOwner = -1;
16573                    protectedFile = null;
16574                }
16575
16576                if (uid < Process.FIRST_APPLICATION_UID
16577                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16578                    Slog.e(TAG, "Failed to finalize " + cid);
16579                    PackageHelper.destroySdDir(cid);
16580                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16581                }
16582
16583                boolean mounted = PackageHelper.isContainerMounted(cid);
16584                if (!mounted) {
16585                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16586                }
16587            }
16588            return status;
16589        }
16590
16591        private void cleanUp() {
16592            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16593
16594            // Destroy secure container
16595            PackageHelper.destroySdDir(cid);
16596        }
16597
16598        private List<String> getAllCodePaths() {
16599            final File codeFile = new File(getCodePath());
16600            if (codeFile != null && codeFile.exists()) {
16601                try {
16602                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16603                    return pkg.getAllCodePaths();
16604                } catch (PackageParserException e) {
16605                    // Ignored; we tried our best
16606                }
16607            }
16608            return Collections.EMPTY_LIST;
16609        }
16610
16611        void cleanUpResourcesLI() {
16612            // Enumerate all code paths before deleting
16613            cleanUpResourcesLI(getAllCodePaths());
16614        }
16615
16616        private void cleanUpResourcesLI(List<String> allCodePaths) {
16617            cleanUp();
16618            removeDexFiles(allCodePaths, instructionSets);
16619        }
16620
16621        String getPackageName() {
16622            return getAsecPackageName(cid);
16623        }
16624
16625        boolean doPostDeleteLI(boolean delete) {
16626            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16627            final List<String> allCodePaths = getAllCodePaths();
16628            boolean mounted = PackageHelper.isContainerMounted(cid);
16629            if (mounted) {
16630                // Unmount first
16631                if (PackageHelper.unMountSdDir(cid)) {
16632                    mounted = false;
16633                }
16634            }
16635            if (!mounted && delete) {
16636                cleanUpResourcesLI(allCodePaths);
16637            }
16638            return !mounted;
16639        }
16640
16641        @Override
16642        int doPreCopy() {
16643            if (isFwdLocked()) {
16644                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16645                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16646                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16647                }
16648            }
16649
16650            return PackageManager.INSTALL_SUCCEEDED;
16651        }
16652
16653        @Override
16654        int doPostCopy(int uid) {
16655            if (isFwdLocked()) {
16656                if (uid < Process.FIRST_APPLICATION_UID
16657                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16658                                RES_FILE_NAME)) {
16659                    Slog.e(TAG, "Failed to finalize " + cid);
16660                    PackageHelper.destroySdDir(cid);
16661                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16662                }
16663            }
16664
16665            return PackageManager.INSTALL_SUCCEEDED;
16666        }
16667    }
16668
16669    /**
16670     * Logic to handle movement of existing installed applications.
16671     */
16672    class MoveInstallArgs extends InstallArgs {
16673        private File codeFile;
16674        private File resourceFile;
16675
16676        /** New install */
16677        MoveInstallArgs(InstallParams params) {
16678            super(params.origin, params.move, params.observer, params.installFlags,
16679                    params.installerPackageName, params.volumeUuid,
16680                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16681                    params.grantedRuntimePermissions,
16682                    params.traceMethod, params.traceCookie, params.certificates,
16683                    params.installReason);
16684        }
16685
16686        int copyApk(IMediaContainerService imcs, boolean temp) {
16687            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16688                    + move.fromUuid + " to " + move.toUuid);
16689            synchronized (mInstaller) {
16690                try {
16691                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16692                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16693                } catch (InstallerException e) {
16694                    Slog.w(TAG, "Failed to move app", e);
16695                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16696                }
16697            }
16698
16699            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16700            resourceFile = codeFile;
16701            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16702
16703            return PackageManager.INSTALL_SUCCEEDED;
16704        }
16705
16706        int doPreInstall(int status) {
16707            if (status != PackageManager.INSTALL_SUCCEEDED) {
16708                cleanUp(move.toUuid);
16709            }
16710            return status;
16711        }
16712
16713        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16714            if (status != PackageManager.INSTALL_SUCCEEDED) {
16715                cleanUp(move.toUuid);
16716                return false;
16717            }
16718
16719            // Reflect the move in app info
16720            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16721            pkg.setApplicationInfoCodePath(pkg.codePath);
16722            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16723            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16724            pkg.setApplicationInfoResourcePath(pkg.codePath);
16725            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16726            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16727
16728            return true;
16729        }
16730
16731        int doPostInstall(int status, int uid) {
16732            if (status == PackageManager.INSTALL_SUCCEEDED) {
16733                cleanUp(move.fromUuid);
16734            } else {
16735                cleanUp(move.toUuid);
16736            }
16737            return status;
16738        }
16739
16740        @Override
16741        String getCodePath() {
16742            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16743        }
16744
16745        @Override
16746        String getResourcePath() {
16747            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16748        }
16749
16750        private boolean cleanUp(String volumeUuid) {
16751            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16752                    move.dataAppName);
16753            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16754            final int[] userIds = sUserManager.getUserIds();
16755            synchronized (mInstallLock) {
16756                // Clean up both app data and code
16757                // All package moves are frozen until finished
16758                for (int userId : userIds) {
16759                    try {
16760                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16761                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16762                    } catch (InstallerException e) {
16763                        Slog.w(TAG, String.valueOf(e));
16764                    }
16765                }
16766                removeCodePathLI(codeFile);
16767            }
16768            return true;
16769        }
16770
16771        void cleanUpResourcesLI() {
16772            throw new UnsupportedOperationException();
16773        }
16774
16775        boolean doPostDeleteLI(boolean delete) {
16776            throw new UnsupportedOperationException();
16777        }
16778    }
16779
16780    static String getAsecPackageName(String packageCid) {
16781        int idx = packageCid.lastIndexOf("-");
16782        if (idx == -1) {
16783            return packageCid;
16784        }
16785        return packageCid.substring(0, idx);
16786    }
16787
16788    // Utility method used to create code paths based on package name and available index.
16789    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16790        String idxStr = "";
16791        int idx = 1;
16792        // Fall back to default value of idx=1 if prefix is not
16793        // part of oldCodePath
16794        if (oldCodePath != null) {
16795            String subStr = oldCodePath;
16796            // Drop the suffix right away
16797            if (suffix != null && subStr.endsWith(suffix)) {
16798                subStr = subStr.substring(0, subStr.length() - suffix.length());
16799            }
16800            // If oldCodePath already contains prefix find out the
16801            // ending index to either increment or decrement.
16802            int sidx = subStr.lastIndexOf(prefix);
16803            if (sidx != -1) {
16804                subStr = subStr.substring(sidx + prefix.length());
16805                if (subStr != null) {
16806                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16807                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16808                    }
16809                    try {
16810                        idx = Integer.parseInt(subStr);
16811                        if (idx <= 1) {
16812                            idx++;
16813                        } else {
16814                            idx--;
16815                        }
16816                    } catch(NumberFormatException e) {
16817                    }
16818                }
16819            }
16820        }
16821        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16822        return prefix + idxStr;
16823    }
16824
16825    private File getNextCodePath(File targetDir, String packageName) {
16826        File result;
16827        SecureRandom random = new SecureRandom();
16828        byte[] bytes = new byte[16];
16829        do {
16830            random.nextBytes(bytes);
16831            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16832            result = new File(targetDir, packageName + "-" + suffix);
16833        } while (result.exists());
16834        return result;
16835    }
16836
16837    // Utility method that returns the relative package path with respect
16838    // to the installation directory. Like say for /data/data/com.test-1.apk
16839    // string com.test-1 is returned.
16840    static String deriveCodePathName(String codePath) {
16841        if (codePath == null) {
16842            return null;
16843        }
16844        final File codeFile = new File(codePath);
16845        final String name = codeFile.getName();
16846        if (codeFile.isDirectory()) {
16847            return name;
16848        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16849            final int lastDot = name.lastIndexOf('.');
16850            return name.substring(0, lastDot);
16851        } else {
16852            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16853            return null;
16854        }
16855    }
16856
16857    static class PackageInstalledInfo {
16858        String name;
16859        int uid;
16860        // The set of users that originally had this package installed.
16861        int[] origUsers;
16862        // The set of users that now have this package installed.
16863        int[] newUsers;
16864        PackageParser.Package pkg;
16865        int returnCode;
16866        String returnMsg;
16867        PackageRemovedInfo removedInfo;
16868        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16869
16870        public void setError(int code, String msg) {
16871            setReturnCode(code);
16872            setReturnMessage(msg);
16873            Slog.w(TAG, msg);
16874        }
16875
16876        public void setError(String msg, PackageParserException e) {
16877            setReturnCode(e.error);
16878            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16879            Slog.w(TAG, msg, e);
16880        }
16881
16882        public void setError(String msg, PackageManagerException e) {
16883            returnCode = e.error;
16884            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16885            Slog.w(TAG, msg, e);
16886        }
16887
16888        public void setReturnCode(int returnCode) {
16889            this.returnCode = returnCode;
16890            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16891            for (int i = 0; i < childCount; i++) {
16892                addedChildPackages.valueAt(i).returnCode = returnCode;
16893            }
16894        }
16895
16896        private void setReturnMessage(String returnMsg) {
16897            this.returnMsg = returnMsg;
16898            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16899            for (int i = 0; i < childCount; i++) {
16900                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16901            }
16902        }
16903
16904        // In some error cases we want to convey more info back to the observer
16905        String origPackage;
16906        String origPermission;
16907    }
16908
16909    /*
16910     * Install a non-existing package.
16911     */
16912    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16913            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16914            PackageInstalledInfo res, int installReason) {
16915        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16916
16917        // Remember this for later, in case we need to rollback this install
16918        String pkgName = pkg.packageName;
16919
16920        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16921
16922        synchronized(mPackages) {
16923            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16924            if (renamedPackage != null) {
16925                // A package with the same name is already installed, though
16926                // it has been renamed to an older name.  The package we
16927                // are trying to install should be installed as an update to
16928                // the existing one, but that has not been requested, so bail.
16929                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16930                        + " without first uninstalling package running as "
16931                        + renamedPackage);
16932                return;
16933            }
16934            if (mPackages.containsKey(pkgName)) {
16935                // Don't allow installation over an existing package with the same name.
16936                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16937                        + " without first uninstalling.");
16938                return;
16939            }
16940        }
16941
16942        try {
16943            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16944                    System.currentTimeMillis(), user);
16945
16946            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16947
16948            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16949                prepareAppDataAfterInstallLIF(newPackage);
16950
16951            } else {
16952                // Remove package from internal structures, but keep around any
16953                // data that might have already existed
16954                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16955                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16956            }
16957        } catch (PackageManagerException e) {
16958            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16959        }
16960
16961        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16962    }
16963
16964    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16965        // Can't rotate keys during boot or if sharedUser.
16966        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16967                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16968            return false;
16969        }
16970        // app is using upgradeKeySets; make sure all are valid
16971        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16972        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16973        for (int i = 0; i < upgradeKeySets.length; i++) {
16974            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16975                Slog.wtf(TAG, "Package "
16976                         + (oldPs.name != null ? oldPs.name : "<null>")
16977                         + " contains upgrade-key-set reference to unknown key-set: "
16978                         + upgradeKeySets[i]
16979                         + " reverting to signatures check.");
16980                return false;
16981            }
16982        }
16983        return true;
16984    }
16985
16986    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16987        // Upgrade keysets are being used.  Determine if new package has a superset of the
16988        // required keys.
16989        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16990        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16991        for (int i = 0; i < upgradeKeySets.length; i++) {
16992            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16993            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16994                return true;
16995            }
16996        }
16997        return false;
16998    }
16999
17000    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17001        try (DigestInputStream digestStream =
17002                new DigestInputStream(new FileInputStream(file), digest)) {
17003            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17004        }
17005    }
17006
17007    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17008            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17009            int installReason) {
17010        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17011
17012        final PackageParser.Package oldPackage;
17013        final PackageSetting ps;
17014        final String pkgName = pkg.packageName;
17015        final int[] allUsers;
17016        final int[] installedUsers;
17017
17018        synchronized(mPackages) {
17019            oldPackage = mPackages.get(pkgName);
17020            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17021
17022            // don't allow upgrade to target a release SDK from a pre-release SDK
17023            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17024                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17025            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17026                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17027            if (oldTargetsPreRelease
17028                    && !newTargetsPreRelease
17029                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17030                Slog.w(TAG, "Can't install package targeting released sdk");
17031                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17032                return;
17033            }
17034
17035            ps = mSettings.mPackages.get(pkgName);
17036
17037            // verify signatures are valid
17038            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17039                if (!checkUpgradeKeySetLP(ps, pkg)) {
17040                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17041                            "New package not signed by keys specified by upgrade-keysets: "
17042                                    + pkgName);
17043                    return;
17044                }
17045            } else {
17046                // default to original signature matching
17047                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17048                        != PackageManager.SIGNATURE_MATCH) {
17049                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17050                            "New package has a different signature: " + pkgName);
17051                    return;
17052                }
17053            }
17054
17055            // don't allow a system upgrade unless the upgrade hash matches
17056            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17057                byte[] digestBytes = null;
17058                try {
17059                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17060                    updateDigest(digest, new File(pkg.baseCodePath));
17061                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17062                        for (String path : pkg.splitCodePaths) {
17063                            updateDigest(digest, new File(path));
17064                        }
17065                    }
17066                    digestBytes = digest.digest();
17067                } catch (NoSuchAlgorithmException | IOException e) {
17068                    res.setError(INSTALL_FAILED_INVALID_APK,
17069                            "Could not compute hash: " + pkgName);
17070                    return;
17071                }
17072                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17073                    res.setError(INSTALL_FAILED_INVALID_APK,
17074                            "New package fails restrict-update check: " + pkgName);
17075                    return;
17076                }
17077                // retain upgrade restriction
17078                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17079            }
17080
17081            // Check for shared user id changes
17082            String invalidPackageName =
17083                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17084            if (invalidPackageName != null) {
17085                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17086                        "Package " + invalidPackageName + " tried to change user "
17087                                + oldPackage.mSharedUserId);
17088                return;
17089            }
17090
17091            // In case of rollback, remember per-user/profile install state
17092            allUsers = sUserManager.getUserIds();
17093            installedUsers = ps.queryInstalledUsers(allUsers, true);
17094
17095            // don't allow an upgrade from full to ephemeral
17096            if (isInstantApp) {
17097                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17098                    for (int currentUser : allUsers) {
17099                        if (!ps.getInstantApp(currentUser)) {
17100                            // can't downgrade from full to instant
17101                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17102                                    + " for user: " + currentUser);
17103                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17104                            return;
17105                        }
17106                    }
17107                } else if (!ps.getInstantApp(user.getIdentifier())) {
17108                    // can't downgrade from full to instant
17109                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17110                            + " for user: " + user.getIdentifier());
17111                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17112                    return;
17113                }
17114            }
17115        }
17116
17117        // Update what is removed
17118        res.removedInfo = new PackageRemovedInfo(this);
17119        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17120        res.removedInfo.removedPackage = oldPackage.packageName;
17121        res.removedInfo.installerPackageName = ps.installerPackageName;
17122        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17123        res.removedInfo.isUpdate = true;
17124        res.removedInfo.origUsers = installedUsers;
17125        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17126        for (int i = 0; i < installedUsers.length; i++) {
17127            final int userId = installedUsers[i];
17128            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17129        }
17130
17131        final int childCount = (oldPackage.childPackages != null)
17132                ? oldPackage.childPackages.size() : 0;
17133        for (int i = 0; i < childCount; i++) {
17134            boolean childPackageUpdated = false;
17135            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17136            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17137            if (res.addedChildPackages != null) {
17138                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17139                if (childRes != null) {
17140                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17141                    childRes.removedInfo.removedPackage = childPkg.packageName;
17142                    if (childPs != null) {
17143                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17144                    }
17145                    childRes.removedInfo.isUpdate = true;
17146                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17147                    childPackageUpdated = true;
17148                }
17149            }
17150            if (!childPackageUpdated) {
17151                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17152                childRemovedRes.removedPackage = childPkg.packageName;
17153                if (childPs != null) {
17154                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17155                }
17156                childRemovedRes.isUpdate = false;
17157                childRemovedRes.dataRemoved = true;
17158                synchronized (mPackages) {
17159                    if (childPs != null) {
17160                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17161                    }
17162                }
17163                if (res.removedInfo.removedChildPackages == null) {
17164                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17165                }
17166                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17167            }
17168        }
17169
17170        boolean sysPkg = (isSystemApp(oldPackage));
17171        if (sysPkg) {
17172            // Set the system/privileged flags as needed
17173            final boolean privileged =
17174                    (oldPackage.applicationInfo.privateFlags
17175                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17176            final int systemPolicyFlags = policyFlags
17177                    | PackageParser.PARSE_IS_SYSTEM
17178                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17179
17180            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17181                    user, allUsers, installerPackageName, res, installReason);
17182        } else {
17183            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17184                    user, allUsers, installerPackageName, res, installReason);
17185        }
17186    }
17187
17188    @Override
17189    public List<String> getPreviousCodePaths(String packageName) {
17190        final int callingUid = Binder.getCallingUid();
17191        final List<String> result = new ArrayList<>();
17192        if (getInstantAppPackageName(callingUid) != null) {
17193            return result;
17194        }
17195        final PackageSetting ps = mSettings.mPackages.get(packageName);
17196        if (ps != null
17197                && ps.oldCodePaths != null
17198                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17199            result.addAll(ps.oldCodePaths);
17200        }
17201        return result;
17202    }
17203
17204    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17205            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17206            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17207            int installReason) {
17208        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17209                + deletedPackage);
17210
17211        String pkgName = deletedPackage.packageName;
17212        boolean deletedPkg = true;
17213        boolean addedPkg = false;
17214        boolean updatedSettings = false;
17215        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17216        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17217                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17218
17219        final long origUpdateTime = (pkg.mExtras != null)
17220                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17221
17222        // First delete the existing package while retaining the data directory
17223        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17224                res.removedInfo, true, pkg)) {
17225            // If the existing package wasn't successfully deleted
17226            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17227            deletedPkg = false;
17228        } else {
17229            // Successfully deleted the old package; proceed with replace.
17230
17231            // If deleted package lived in a container, give users a chance to
17232            // relinquish resources before killing.
17233            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17234                if (DEBUG_INSTALL) {
17235                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17236                }
17237                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17238                final ArrayList<String> pkgList = new ArrayList<String>(1);
17239                pkgList.add(deletedPackage.applicationInfo.packageName);
17240                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17241            }
17242
17243            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17244                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17245            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17246
17247            try {
17248                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17249                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17250                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17251                        installReason);
17252
17253                // Update the in-memory copy of the previous code paths.
17254                PackageSetting ps = mSettings.mPackages.get(pkgName);
17255                if (!killApp) {
17256                    if (ps.oldCodePaths == null) {
17257                        ps.oldCodePaths = new ArraySet<>();
17258                    }
17259                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17260                    if (deletedPackage.splitCodePaths != null) {
17261                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17262                    }
17263                } else {
17264                    ps.oldCodePaths = null;
17265                }
17266                if (ps.childPackageNames != null) {
17267                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17268                        final String childPkgName = ps.childPackageNames.get(i);
17269                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17270                        childPs.oldCodePaths = ps.oldCodePaths;
17271                    }
17272                }
17273                // set instant app status, but, only if it's explicitly specified
17274                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17275                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17276                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17277                prepareAppDataAfterInstallLIF(newPackage);
17278                addedPkg = true;
17279                mDexManager.notifyPackageUpdated(newPackage.packageName,
17280                        newPackage.baseCodePath, newPackage.splitCodePaths);
17281            } catch (PackageManagerException e) {
17282                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17283            }
17284        }
17285
17286        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17287            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17288
17289            // Revert all internal state mutations and added folders for the failed install
17290            if (addedPkg) {
17291                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17292                        res.removedInfo, true, null);
17293            }
17294
17295            // Restore the old package
17296            if (deletedPkg) {
17297                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17298                File restoreFile = new File(deletedPackage.codePath);
17299                // Parse old package
17300                boolean oldExternal = isExternal(deletedPackage);
17301                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17302                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17303                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17304                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17305                try {
17306                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17307                            null);
17308                } catch (PackageManagerException e) {
17309                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17310                            + e.getMessage());
17311                    return;
17312                }
17313
17314                synchronized (mPackages) {
17315                    // Ensure the installer package name up to date
17316                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17317
17318                    // Update permissions for restored package
17319                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17320
17321                    mSettings.writeLPr();
17322                }
17323
17324                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17325            }
17326        } else {
17327            synchronized (mPackages) {
17328                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17329                if (ps != null) {
17330                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17331                    if (res.removedInfo.removedChildPackages != null) {
17332                        final int childCount = res.removedInfo.removedChildPackages.size();
17333                        // Iterate in reverse as we may modify the collection
17334                        for (int i = childCount - 1; i >= 0; i--) {
17335                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17336                            if (res.addedChildPackages.containsKey(childPackageName)) {
17337                                res.removedInfo.removedChildPackages.removeAt(i);
17338                            } else {
17339                                PackageRemovedInfo childInfo = res.removedInfo
17340                                        .removedChildPackages.valueAt(i);
17341                                childInfo.removedForAllUsers = mPackages.get(
17342                                        childInfo.removedPackage) == null;
17343                            }
17344                        }
17345                    }
17346                }
17347            }
17348        }
17349    }
17350
17351    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17352            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17353            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17354            int installReason) {
17355        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17356                + ", old=" + deletedPackage);
17357
17358        final boolean disabledSystem;
17359
17360        // Remove existing system package
17361        removePackageLI(deletedPackage, true);
17362
17363        synchronized (mPackages) {
17364            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17365        }
17366        if (!disabledSystem) {
17367            // We didn't need to disable the .apk as a current system package,
17368            // which means we are replacing another update that is already
17369            // installed.  We need to make sure to delete the older one's .apk.
17370            res.removedInfo.args = createInstallArgsForExisting(0,
17371                    deletedPackage.applicationInfo.getCodePath(),
17372                    deletedPackage.applicationInfo.getResourcePath(),
17373                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17374        } else {
17375            res.removedInfo.args = null;
17376        }
17377
17378        // Successfully disabled the old package. Now proceed with re-installation
17379        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17380                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17381        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17382
17383        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17384        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17385                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17386
17387        PackageParser.Package newPackage = null;
17388        try {
17389            // Add the package to the internal data structures
17390            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17391
17392            // Set the update and install times
17393            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17394            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17395                    System.currentTimeMillis());
17396
17397            // Update the package dynamic state if succeeded
17398            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17399                // Now that the install succeeded make sure we remove data
17400                // directories for any child package the update removed.
17401                final int deletedChildCount = (deletedPackage.childPackages != null)
17402                        ? deletedPackage.childPackages.size() : 0;
17403                final int newChildCount = (newPackage.childPackages != null)
17404                        ? newPackage.childPackages.size() : 0;
17405                for (int i = 0; i < deletedChildCount; i++) {
17406                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17407                    boolean childPackageDeleted = true;
17408                    for (int j = 0; j < newChildCount; j++) {
17409                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17410                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17411                            childPackageDeleted = false;
17412                            break;
17413                        }
17414                    }
17415                    if (childPackageDeleted) {
17416                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17417                                deletedChildPkg.packageName);
17418                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17419                            PackageRemovedInfo removedChildRes = res.removedInfo
17420                                    .removedChildPackages.get(deletedChildPkg.packageName);
17421                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17422                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17423                        }
17424                    }
17425                }
17426
17427                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17428                        installReason);
17429                prepareAppDataAfterInstallLIF(newPackage);
17430
17431                mDexManager.notifyPackageUpdated(newPackage.packageName,
17432                            newPackage.baseCodePath, newPackage.splitCodePaths);
17433            }
17434        } catch (PackageManagerException e) {
17435            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17436            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17437        }
17438
17439        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17440            // Re installation failed. Restore old information
17441            // Remove new pkg information
17442            if (newPackage != null) {
17443                removeInstalledPackageLI(newPackage, true);
17444            }
17445            // Add back the old system package
17446            try {
17447                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17448            } catch (PackageManagerException e) {
17449                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17450            }
17451
17452            synchronized (mPackages) {
17453                if (disabledSystem) {
17454                    enableSystemPackageLPw(deletedPackage);
17455                }
17456
17457                // Ensure the installer package name up to date
17458                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17459
17460                // Update permissions for restored package
17461                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17462
17463                mSettings.writeLPr();
17464            }
17465
17466            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17467                    + " after failed upgrade");
17468        }
17469    }
17470
17471    /**
17472     * Checks whether the parent or any of the child packages have a change shared
17473     * user. For a package to be a valid update the shred users of the parent and
17474     * the children should match. We may later support changing child shared users.
17475     * @param oldPkg The updated package.
17476     * @param newPkg The update package.
17477     * @return The shared user that change between the versions.
17478     */
17479    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17480            PackageParser.Package newPkg) {
17481        // Check parent shared user
17482        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17483            return newPkg.packageName;
17484        }
17485        // Check child shared users
17486        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17487        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17488        for (int i = 0; i < newChildCount; i++) {
17489            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17490            // If this child was present, did it have the same shared user?
17491            for (int j = 0; j < oldChildCount; j++) {
17492                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17493                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17494                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17495                    return newChildPkg.packageName;
17496                }
17497            }
17498        }
17499        return null;
17500    }
17501
17502    private void removeNativeBinariesLI(PackageSetting ps) {
17503        // Remove the lib path for the parent package
17504        if (ps != null) {
17505            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17506            // Remove the lib path for the child packages
17507            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17508            for (int i = 0; i < childCount; i++) {
17509                PackageSetting childPs = null;
17510                synchronized (mPackages) {
17511                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17512                }
17513                if (childPs != null) {
17514                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17515                            .legacyNativeLibraryPathString);
17516                }
17517            }
17518        }
17519    }
17520
17521    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17522        // Enable the parent package
17523        mSettings.enableSystemPackageLPw(pkg.packageName);
17524        // Enable the child packages
17525        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17526        for (int i = 0; i < childCount; i++) {
17527            PackageParser.Package childPkg = pkg.childPackages.get(i);
17528            mSettings.enableSystemPackageLPw(childPkg.packageName);
17529        }
17530    }
17531
17532    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17533            PackageParser.Package newPkg) {
17534        // Disable the parent package (parent always replaced)
17535        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17536        // Disable the child packages
17537        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17538        for (int i = 0; i < childCount; i++) {
17539            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17540            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17541            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17542        }
17543        return disabled;
17544    }
17545
17546    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17547            String installerPackageName) {
17548        // Enable the parent package
17549        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17550        // Enable the child packages
17551        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17552        for (int i = 0; i < childCount; i++) {
17553            PackageParser.Package childPkg = pkg.childPackages.get(i);
17554            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17555        }
17556    }
17557
17558    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17559        // Collect all used permissions in the UID
17560        ArraySet<String> usedPermissions = new ArraySet<>();
17561        final int packageCount = su.packages.size();
17562        for (int i = 0; i < packageCount; i++) {
17563            PackageSetting ps = su.packages.valueAt(i);
17564            if (ps.pkg == null) {
17565                continue;
17566            }
17567            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17568            for (int j = 0; j < requestedPermCount; j++) {
17569                String permission = ps.pkg.requestedPermissions.get(j);
17570                BasePermission bp = mSettings.mPermissions.get(permission);
17571                if (bp != null) {
17572                    usedPermissions.add(permission);
17573                }
17574            }
17575        }
17576
17577        PermissionsState permissionsState = su.getPermissionsState();
17578        // Prune install permissions
17579        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17580        final int installPermCount = installPermStates.size();
17581        for (int i = installPermCount - 1; i >= 0;  i--) {
17582            PermissionState permissionState = installPermStates.get(i);
17583            if (!usedPermissions.contains(permissionState.getName())) {
17584                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17585                if (bp != null) {
17586                    permissionsState.revokeInstallPermission(bp);
17587                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17588                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17589                }
17590            }
17591        }
17592
17593        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17594
17595        // Prune runtime permissions
17596        for (int userId : allUserIds) {
17597            List<PermissionState> runtimePermStates = permissionsState
17598                    .getRuntimePermissionStates(userId);
17599            final int runtimePermCount = runtimePermStates.size();
17600            for (int i = runtimePermCount - 1; i >= 0; i--) {
17601                PermissionState permissionState = runtimePermStates.get(i);
17602                if (!usedPermissions.contains(permissionState.getName())) {
17603                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17604                    if (bp != null) {
17605                        permissionsState.revokeRuntimePermission(bp, userId);
17606                        permissionsState.updatePermissionFlags(bp, userId,
17607                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17608                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17609                                runtimePermissionChangedUserIds, userId);
17610                    }
17611                }
17612            }
17613        }
17614
17615        return runtimePermissionChangedUserIds;
17616    }
17617
17618    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17619            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17620        // Update the parent package setting
17621        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17622                res, user, installReason);
17623        // Update the child packages setting
17624        final int childCount = (newPackage.childPackages != null)
17625                ? newPackage.childPackages.size() : 0;
17626        for (int i = 0; i < childCount; i++) {
17627            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17628            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17629            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17630                    childRes.origUsers, childRes, user, installReason);
17631        }
17632    }
17633
17634    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17635            String installerPackageName, int[] allUsers, int[] installedForUsers,
17636            PackageInstalledInfo res, UserHandle user, int installReason) {
17637        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17638
17639        String pkgName = newPackage.packageName;
17640        synchronized (mPackages) {
17641            //write settings. the installStatus will be incomplete at this stage.
17642            //note that the new package setting would have already been
17643            //added to mPackages. It hasn't been persisted yet.
17644            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17645            // TODO: Remove this write? It's also written at the end of this method
17646            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17647            mSettings.writeLPr();
17648            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17649        }
17650
17651        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17652        synchronized (mPackages) {
17653            updatePermissionsLPw(newPackage.packageName, newPackage,
17654                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17655                            ? UPDATE_PERMISSIONS_ALL : 0));
17656            // For system-bundled packages, we assume that installing an upgraded version
17657            // of the package implies that the user actually wants to run that new code,
17658            // so we enable the package.
17659            PackageSetting ps = mSettings.mPackages.get(pkgName);
17660            final int userId = user.getIdentifier();
17661            if (ps != null) {
17662                if (isSystemApp(newPackage)) {
17663                    if (DEBUG_INSTALL) {
17664                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17665                    }
17666                    // Enable system package for requested users
17667                    if (res.origUsers != null) {
17668                        for (int origUserId : res.origUsers) {
17669                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17670                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17671                                        origUserId, installerPackageName);
17672                            }
17673                        }
17674                    }
17675                    // Also convey the prior install/uninstall state
17676                    if (allUsers != null && installedForUsers != null) {
17677                        for (int currentUserId : allUsers) {
17678                            final boolean installed = ArrayUtils.contains(
17679                                    installedForUsers, currentUserId);
17680                            if (DEBUG_INSTALL) {
17681                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17682                            }
17683                            ps.setInstalled(installed, currentUserId);
17684                        }
17685                        // these install state changes will be persisted in the
17686                        // upcoming call to mSettings.writeLPr().
17687                    }
17688                }
17689                // It's implied that when a user requests installation, they want the app to be
17690                // installed and enabled.
17691                if (userId != UserHandle.USER_ALL) {
17692                    ps.setInstalled(true, userId);
17693                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17694                }
17695
17696                // When replacing an existing package, preserve the original install reason for all
17697                // users that had the package installed before.
17698                final Set<Integer> previousUserIds = new ArraySet<>();
17699                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17700                    final int installReasonCount = res.removedInfo.installReasons.size();
17701                    for (int i = 0; i < installReasonCount; i++) {
17702                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17703                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17704                        ps.setInstallReason(previousInstallReason, previousUserId);
17705                        previousUserIds.add(previousUserId);
17706                    }
17707                }
17708
17709                // Set install reason for users that are having the package newly installed.
17710                if (userId == UserHandle.USER_ALL) {
17711                    for (int currentUserId : sUserManager.getUserIds()) {
17712                        if (!previousUserIds.contains(currentUserId)) {
17713                            ps.setInstallReason(installReason, currentUserId);
17714                        }
17715                    }
17716                } else if (!previousUserIds.contains(userId)) {
17717                    ps.setInstallReason(installReason, userId);
17718                }
17719                mSettings.writeKernelMappingLPr(ps);
17720            }
17721            res.name = pkgName;
17722            res.uid = newPackage.applicationInfo.uid;
17723            res.pkg = newPackage;
17724            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17725            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17726            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17727            //to update install status
17728            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17729            mSettings.writeLPr();
17730            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17731        }
17732
17733        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17734    }
17735
17736    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17737        try {
17738            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17739            installPackageLI(args, res);
17740        } finally {
17741            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17742        }
17743    }
17744
17745    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17746        final int installFlags = args.installFlags;
17747        final String installerPackageName = args.installerPackageName;
17748        final String volumeUuid = args.volumeUuid;
17749        final File tmpPackageFile = new File(args.getCodePath());
17750        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17751        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17752                || (args.volumeUuid != null));
17753        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17754        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17755        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17756        boolean replace = false;
17757        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17758        if (args.move != null) {
17759            // moving a complete application; perform an initial scan on the new install location
17760            scanFlags |= SCAN_INITIAL;
17761        }
17762        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17763            scanFlags |= SCAN_DONT_KILL_APP;
17764        }
17765        if (instantApp) {
17766            scanFlags |= SCAN_AS_INSTANT_APP;
17767        }
17768        if (fullApp) {
17769            scanFlags |= SCAN_AS_FULL_APP;
17770        }
17771
17772        // Result object to be returned
17773        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17774
17775        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17776
17777        // Sanity check
17778        if (instantApp && (forwardLocked || onExternal)) {
17779            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17780                    + " external=" + onExternal);
17781            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17782            return;
17783        }
17784
17785        // Retrieve PackageSettings and parse package
17786        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17787                | PackageParser.PARSE_ENFORCE_CODE
17788                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17789                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17790                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17791                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17792        PackageParser pp = new PackageParser();
17793        pp.setSeparateProcesses(mSeparateProcesses);
17794        pp.setDisplayMetrics(mMetrics);
17795        pp.setCallback(mPackageParserCallback);
17796
17797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17798        final PackageParser.Package pkg;
17799        try {
17800            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17801        } catch (PackageParserException e) {
17802            res.setError("Failed parse during installPackageLI", e);
17803            return;
17804        } finally {
17805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17806        }
17807
17808        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17809        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17810            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17811            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17812                    "Instant app package must target O");
17813            return;
17814        }
17815        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17816            Slog.w(TAG, "Instant app package " + pkg.packageName
17817                    + " does not target targetSandboxVersion 2");
17818            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17819                    "Instant app package must use targetSanboxVersion 2");
17820            return;
17821        }
17822
17823        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17824            // Static shared libraries have synthetic package names
17825            renameStaticSharedLibraryPackage(pkg);
17826
17827            // No static shared libs on external storage
17828            if (onExternal) {
17829                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17830                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17831                        "Packages declaring static-shared libs cannot be updated");
17832                return;
17833            }
17834        }
17835
17836        // If we are installing a clustered package add results for the children
17837        if (pkg.childPackages != null) {
17838            synchronized (mPackages) {
17839                final int childCount = pkg.childPackages.size();
17840                for (int i = 0; i < childCount; i++) {
17841                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17842                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17843                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17844                    childRes.pkg = childPkg;
17845                    childRes.name = childPkg.packageName;
17846                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17847                    if (childPs != null) {
17848                        childRes.origUsers = childPs.queryInstalledUsers(
17849                                sUserManager.getUserIds(), true);
17850                    }
17851                    if ((mPackages.containsKey(childPkg.packageName))) {
17852                        childRes.removedInfo = new PackageRemovedInfo(this);
17853                        childRes.removedInfo.removedPackage = childPkg.packageName;
17854                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17855                    }
17856                    if (res.addedChildPackages == null) {
17857                        res.addedChildPackages = new ArrayMap<>();
17858                    }
17859                    res.addedChildPackages.put(childPkg.packageName, childRes);
17860                }
17861            }
17862        }
17863
17864        // If package doesn't declare API override, mark that we have an install
17865        // time CPU ABI override.
17866        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17867            pkg.cpuAbiOverride = args.abiOverride;
17868        }
17869
17870        String pkgName = res.name = pkg.packageName;
17871        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17872            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17873                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17874                return;
17875            }
17876        }
17877
17878        try {
17879            // either use what we've been given or parse directly from the APK
17880            if (args.certificates != null) {
17881                try {
17882                    PackageParser.populateCertificates(pkg, args.certificates);
17883                } catch (PackageParserException e) {
17884                    // there was something wrong with the certificates we were given;
17885                    // try to pull them from the APK
17886                    PackageParser.collectCertificates(pkg, parseFlags);
17887                }
17888            } else {
17889                PackageParser.collectCertificates(pkg, parseFlags);
17890            }
17891        } catch (PackageParserException e) {
17892            res.setError("Failed collect during installPackageLI", e);
17893            return;
17894        }
17895
17896        // Get rid of all references to package scan path via parser.
17897        pp = null;
17898        String oldCodePath = null;
17899        boolean systemApp = false;
17900        synchronized (mPackages) {
17901            // Check if installing already existing package
17902            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17903                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17904                if (pkg.mOriginalPackages != null
17905                        && pkg.mOriginalPackages.contains(oldName)
17906                        && mPackages.containsKey(oldName)) {
17907                    // This package is derived from an original package,
17908                    // and this device has been updating from that original
17909                    // name.  We must continue using the original name, so
17910                    // rename the new package here.
17911                    pkg.setPackageName(oldName);
17912                    pkgName = pkg.packageName;
17913                    replace = true;
17914                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17915                            + oldName + " pkgName=" + pkgName);
17916                } else if (mPackages.containsKey(pkgName)) {
17917                    // This package, under its official name, already exists
17918                    // on the device; we should replace it.
17919                    replace = true;
17920                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17921                }
17922
17923                // Child packages are installed through the parent package
17924                if (pkg.parentPackage != null) {
17925                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17926                            "Package " + pkg.packageName + " is child of package "
17927                                    + pkg.parentPackage.parentPackage + ". Child packages "
17928                                    + "can be updated only through the parent package.");
17929                    return;
17930                }
17931
17932                if (replace) {
17933                    // Prevent apps opting out from runtime permissions
17934                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17935                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17936                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17937                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17938                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17939                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17940                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17941                                        + " doesn't support runtime permissions but the old"
17942                                        + " target SDK " + oldTargetSdk + " does.");
17943                        return;
17944                    }
17945                    // Prevent persistent apps from being updated
17946                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17947                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17948                                "Package " + oldPackage.packageName + " is a persistent app. "
17949                                        + "Persistent apps are not updateable.");
17950                        return;
17951                    }
17952                    // Prevent apps from downgrading their targetSandbox.
17953                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17954                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17955                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17956                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17957                                "Package " + pkg.packageName + " new target sandbox "
17958                                + newTargetSandbox + " is incompatible with the previous value of"
17959                                + oldTargetSandbox + ".");
17960                        return;
17961                    }
17962
17963                    // Prevent installing of child packages
17964                    if (oldPackage.parentPackage != null) {
17965                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17966                                "Package " + pkg.packageName + " is child of package "
17967                                        + oldPackage.parentPackage + ". Child packages "
17968                                        + "can be updated only through the parent package.");
17969                        return;
17970                    }
17971                }
17972            }
17973
17974            PackageSetting ps = mSettings.mPackages.get(pkgName);
17975            if (ps != null) {
17976                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17977
17978                // Static shared libs have same package with different versions where
17979                // we internally use a synthetic package name to allow multiple versions
17980                // of the same package, therefore we need to compare signatures against
17981                // the package setting for the latest library version.
17982                PackageSetting signatureCheckPs = ps;
17983                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17984                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17985                    if (libraryEntry != null) {
17986                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17987                    }
17988                }
17989
17990                // Quick sanity check that we're signed correctly if updating;
17991                // we'll check this again later when scanning, but we want to
17992                // bail early here before tripping over redefined permissions.
17993                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17994                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17995                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17996                                + pkg.packageName + " upgrade keys do not match the "
17997                                + "previously installed version");
17998                        return;
17999                    }
18000                } else {
18001                    try {
18002                        verifySignaturesLP(signatureCheckPs, pkg);
18003                    } catch (PackageManagerException e) {
18004                        res.setError(e.error, e.getMessage());
18005                        return;
18006                    }
18007                }
18008
18009                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18010                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18011                    systemApp = (ps.pkg.applicationInfo.flags &
18012                            ApplicationInfo.FLAG_SYSTEM) != 0;
18013                }
18014                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18015            }
18016
18017            int N = pkg.permissions.size();
18018            for (int i = N-1; i >= 0; i--) {
18019                PackageParser.Permission perm = pkg.permissions.get(i);
18020                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18021
18022                // Don't allow anyone but the system to define ephemeral permissions.
18023                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18024                        && !systemApp) {
18025                    Slog.w(TAG, "Non-System package " + pkg.packageName
18026                            + " attempting to delcare ephemeral permission "
18027                            + perm.info.name + "; Removing ephemeral.");
18028                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18029                }
18030                // Check whether the newly-scanned package wants to define an already-defined perm
18031                if (bp != null) {
18032                    // If the defining package is signed with our cert, it's okay.  This
18033                    // also includes the "updating the same package" case, of course.
18034                    // "updating same package" could also involve key-rotation.
18035                    final boolean sigsOk;
18036                    if (bp.sourcePackage.equals(pkg.packageName)
18037                            && (bp.packageSetting instanceof PackageSetting)
18038                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18039                                    scanFlags))) {
18040                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18041                    } else {
18042                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18043                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18044                    }
18045                    if (!sigsOk) {
18046                        // If the owning package is the system itself, we log but allow
18047                        // install to proceed; we fail the install on all other permission
18048                        // redefinitions.
18049                        if (!bp.sourcePackage.equals("android")) {
18050                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18051                                    + pkg.packageName + " attempting to redeclare permission "
18052                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18053                            res.origPermission = perm.info.name;
18054                            res.origPackage = bp.sourcePackage;
18055                            return;
18056                        } else {
18057                            Slog.w(TAG, "Package " + pkg.packageName
18058                                    + " attempting to redeclare system permission "
18059                                    + perm.info.name + "; ignoring new declaration");
18060                            pkg.permissions.remove(i);
18061                        }
18062                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18063                        // Prevent apps to change protection level to dangerous from any other
18064                        // type as this would allow a privilege escalation where an app adds a
18065                        // normal/signature permission in other app's group and later redefines
18066                        // it as dangerous leading to the group auto-grant.
18067                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18068                                == PermissionInfo.PROTECTION_DANGEROUS) {
18069                            if (bp != null && !bp.isRuntime()) {
18070                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18071                                        + "non-runtime permission " + perm.info.name
18072                                        + " to runtime; keeping old protection level");
18073                                perm.info.protectionLevel = bp.protectionLevel;
18074                            }
18075                        }
18076                    }
18077                }
18078            }
18079        }
18080
18081        if (systemApp) {
18082            if (onExternal) {
18083                // Abort update; system app can't be replaced with app on sdcard
18084                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18085                        "Cannot install updates to system apps on sdcard");
18086                return;
18087            } else if (instantApp) {
18088                // Abort update; system app can't be replaced with an instant app
18089                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18090                        "Cannot update a system app with an instant app");
18091                return;
18092            }
18093        }
18094
18095        if (args.move != null) {
18096            // We did an in-place move, so dex is ready to roll
18097            scanFlags |= SCAN_NO_DEX;
18098            scanFlags |= SCAN_MOVE;
18099
18100            synchronized (mPackages) {
18101                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18102                if (ps == null) {
18103                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18104                            "Missing settings for moved package " + pkgName);
18105                }
18106
18107                // We moved the entire application as-is, so bring over the
18108                // previously derived ABI information.
18109                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18110                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18111            }
18112
18113        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18114            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18115            scanFlags |= SCAN_NO_DEX;
18116
18117            try {
18118                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18119                    args.abiOverride : pkg.cpuAbiOverride);
18120                final boolean extractNativeLibs = !pkg.isLibrary();
18121                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18122                        extractNativeLibs, mAppLib32InstallDir);
18123            } catch (PackageManagerException pme) {
18124                Slog.e(TAG, "Error deriving application ABI", pme);
18125                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18126                return;
18127            }
18128
18129            // Shared libraries for the package need to be updated.
18130            synchronized (mPackages) {
18131                try {
18132                    updateSharedLibrariesLPr(pkg, null);
18133                } catch (PackageManagerException e) {
18134                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18135                }
18136            }
18137
18138            // dexopt can take some time to complete, so, for instant apps, we skip this
18139            // step during installation. Instead, we'll take extra time the first time the
18140            // instant app starts. It's preferred to do it this way to provide continuous
18141            // progress to the user instead of mysteriously blocking somewhere in the
18142            // middle of running an instant app. The default behaviour can be overridden
18143            // via gservices.
18144            if (!instantApp || Global.getInt(
18145                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18146                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18147                // Do not run PackageDexOptimizer through the local performDexOpt
18148                // method because `pkg` may not be in `mPackages` yet.
18149                //
18150                // Also, don't fail application installs if the dexopt step fails.
18151                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18152                        null /* instructionSets */, false /* checkProfiles */,
18153                        getCompilerFilterForReason(REASON_INSTALL),
18154                        getOrCreateCompilerPackageStats(pkg),
18155                        mDexManager.isUsedByOtherApps(pkg.packageName),
18156                        true /* bootComplete */);
18157                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18158            }
18159
18160            // Notify BackgroundDexOptService that the package has been changed.
18161            // If this is an update of a package which used to fail to compile,
18162            // BDOS will remove it from its blacklist.
18163            // TODO: Layering violation
18164            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18165        }
18166
18167        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18168            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18169            return;
18170        }
18171
18172        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18173
18174        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18175                "installPackageLI")) {
18176            if (replace) {
18177                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18178                    // Static libs have a synthetic package name containing the version
18179                    // and cannot be updated as an update would get a new package name,
18180                    // unless this is the exact same version code which is useful for
18181                    // development.
18182                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18183                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18184                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18185                                + "static-shared libs cannot be updated");
18186                        return;
18187                    }
18188                }
18189                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18190                        installerPackageName, res, args.installReason);
18191            } else {
18192                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18193                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18194            }
18195        }
18196
18197        synchronized (mPackages) {
18198            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18199            if (ps != null) {
18200                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18201                ps.setUpdateAvailable(false /*updateAvailable*/);
18202            }
18203
18204            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18205            for (int i = 0; i < childCount; i++) {
18206                PackageParser.Package childPkg = pkg.childPackages.get(i);
18207                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18208                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18209                if (childPs != null) {
18210                    childRes.newUsers = childPs.queryInstalledUsers(
18211                            sUserManager.getUserIds(), true);
18212                }
18213            }
18214
18215            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18216                updateSequenceNumberLP(ps, res.newUsers);
18217                updateInstantAppInstallerLocked(pkgName);
18218            }
18219        }
18220    }
18221
18222    private void startIntentFilterVerifications(int userId, boolean replacing,
18223            PackageParser.Package pkg) {
18224        if (mIntentFilterVerifierComponent == null) {
18225            Slog.w(TAG, "No IntentFilter verification will not be done as "
18226                    + "there is no IntentFilterVerifier available!");
18227            return;
18228        }
18229
18230        final int verifierUid = getPackageUid(
18231                mIntentFilterVerifierComponent.getPackageName(),
18232                MATCH_DEBUG_TRIAGED_MISSING,
18233                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18234
18235        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18236        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18237        mHandler.sendMessage(msg);
18238
18239        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18240        for (int i = 0; i < childCount; i++) {
18241            PackageParser.Package childPkg = pkg.childPackages.get(i);
18242            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18243            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18244            mHandler.sendMessage(msg);
18245        }
18246    }
18247
18248    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18249            PackageParser.Package pkg) {
18250        int size = pkg.activities.size();
18251        if (size == 0) {
18252            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18253                    "No activity, so no need to verify any IntentFilter!");
18254            return;
18255        }
18256
18257        final boolean hasDomainURLs = hasDomainURLs(pkg);
18258        if (!hasDomainURLs) {
18259            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18260                    "No domain URLs, so no need to verify any IntentFilter!");
18261            return;
18262        }
18263
18264        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18265                + " if any IntentFilter from the " + size
18266                + " Activities needs verification ...");
18267
18268        int count = 0;
18269        final String packageName = pkg.packageName;
18270
18271        synchronized (mPackages) {
18272            // If this is a new install and we see that we've already run verification for this
18273            // package, we have nothing to do: it means the state was restored from backup.
18274            if (!replacing) {
18275                IntentFilterVerificationInfo ivi =
18276                        mSettings.getIntentFilterVerificationLPr(packageName);
18277                if (ivi != null) {
18278                    if (DEBUG_DOMAIN_VERIFICATION) {
18279                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18280                                + ivi.getStatusString());
18281                    }
18282                    return;
18283                }
18284            }
18285
18286            // If any filters need to be verified, then all need to be.
18287            boolean needToVerify = false;
18288            for (PackageParser.Activity a : pkg.activities) {
18289                for (ActivityIntentInfo filter : a.intents) {
18290                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18291                        if (DEBUG_DOMAIN_VERIFICATION) {
18292                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18293                        }
18294                        needToVerify = true;
18295                        break;
18296                    }
18297                }
18298            }
18299
18300            if (needToVerify) {
18301                final int verificationId = mIntentFilterVerificationToken++;
18302                for (PackageParser.Activity a : pkg.activities) {
18303                    for (ActivityIntentInfo filter : a.intents) {
18304                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18305                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18306                                    "Verification needed for IntentFilter:" + filter.toString());
18307                            mIntentFilterVerifier.addOneIntentFilterVerification(
18308                                    verifierUid, userId, verificationId, filter, packageName);
18309                            count++;
18310                        }
18311                    }
18312                }
18313            }
18314        }
18315
18316        if (count > 0) {
18317            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18318                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18319                    +  " for userId:" + userId);
18320            mIntentFilterVerifier.startVerifications(userId);
18321        } else {
18322            if (DEBUG_DOMAIN_VERIFICATION) {
18323                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18324            }
18325        }
18326    }
18327
18328    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18329        final ComponentName cn  = filter.activity.getComponentName();
18330        final String packageName = cn.getPackageName();
18331
18332        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18333                packageName);
18334        if (ivi == null) {
18335            return true;
18336        }
18337        int status = ivi.getStatus();
18338        switch (status) {
18339            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18340            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18341                return true;
18342
18343            default:
18344                // Nothing to do
18345                return false;
18346        }
18347    }
18348
18349    private static boolean isMultiArch(ApplicationInfo info) {
18350        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18351    }
18352
18353    private static boolean isExternal(PackageParser.Package pkg) {
18354        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18355    }
18356
18357    private static boolean isExternal(PackageSetting ps) {
18358        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18359    }
18360
18361    private static boolean isSystemApp(PackageParser.Package pkg) {
18362        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18363    }
18364
18365    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18366        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18367    }
18368
18369    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18370        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18371    }
18372
18373    private static boolean isSystemApp(PackageSetting ps) {
18374        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18375    }
18376
18377    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18378        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18379    }
18380
18381    private int packageFlagsToInstallFlags(PackageSetting ps) {
18382        int installFlags = 0;
18383        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18384            // This existing package was an external ASEC install when we have
18385            // the external flag without a UUID
18386            installFlags |= PackageManager.INSTALL_EXTERNAL;
18387        }
18388        if (ps.isForwardLocked()) {
18389            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18390        }
18391        return installFlags;
18392    }
18393
18394    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18395        if (isExternal(pkg)) {
18396            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18397                return StorageManager.UUID_PRIMARY_PHYSICAL;
18398            } else {
18399                return pkg.volumeUuid;
18400            }
18401        } else {
18402            return StorageManager.UUID_PRIVATE_INTERNAL;
18403        }
18404    }
18405
18406    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18407        if (isExternal(pkg)) {
18408            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18409                return mSettings.getExternalVersion();
18410            } else {
18411                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18412            }
18413        } else {
18414            return mSettings.getInternalVersion();
18415        }
18416    }
18417
18418    private void deleteTempPackageFiles() {
18419        final FilenameFilter filter = new FilenameFilter() {
18420            public boolean accept(File dir, String name) {
18421                return name.startsWith("vmdl") && name.endsWith(".tmp");
18422            }
18423        };
18424        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18425            file.delete();
18426        }
18427    }
18428
18429    @Override
18430    public void deletePackageAsUser(String packageName, int versionCode,
18431            IPackageDeleteObserver observer, int userId, int flags) {
18432        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18433                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18434    }
18435
18436    @Override
18437    public void deletePackageVersioned(VersionedPackage versionedPackage,
18438            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18439        final int callingUid = Binder.getCallingUid();
18440        mContext.enforceCallingOrSelfPermission(
18441                android.Manifest.permission.DELETE_PACKAGES, null);
18442        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18443        Preconditions.checkNotNull(versionedPackage);
18444        Preconditions.checkNotNull(observer);
18445        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18446                PackageManager.VERSION_CODE_HIGHEST,
18447                Integer.MAX_VALUE, "versionCode must be >= -1");
18448
18449        final String packageName = versionedPackage.getPackageName();
18450        final int versionCode = versionedPackage.getVersionCode();
18451        final String internalPackageName;
18452        synchronized (mPackages) {
18453            // Normalize package name to handle renamed packages and static libs
18454            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18455                    versionedPackage.getVersionCode());
18456        }
18457
18458        final int uid = Binder.getCallingUid();
18459        if (!isOrphaned(internalPackageName)
18460                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18461            try {
18462                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18463                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18464                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18465                observer.onUserActionRequired(intent);
18466            } catch (RemoteException re) {
18467            }
18468            return;
18469        }
18470        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18471        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18472        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18473            mContext.enforceCallingOrSelfPermission(
18474                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18475                    "deletePackage for user " + userId);
18476        }
18477
18478        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18479            try {
18480                observer.onPackageDeleted(packageName,
18481                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18482            } catch (RemoteException re) {
18483            }
18484            return;
18485        }
18486
18487        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18488            try {
18489                observer.onPackageDeleted(packageName,
18490                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18491            } catch (RemoteException re) {
18492            }
18493            return;
18494        }
18495
18496        if (DEBUG_REMOVE) {
18497            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18498                    + " deleteAllUsers: " + deleteAllUsers + " version="
18499                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18500                    ? "VERSION_CODE_HIGHEST" : versionCode));
18501        }
18502        // Queue up an async operation since the package deletion may take a little while.
18503        mHandler.post(new Runnable() {
18504            public void run() {
18505                mHandler.removeCallbacks(this);
18506                int returnCode;
18507                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18508                boolean doDeletePackage = true;
18509                if (ps != null) {
18510                    final boolean targetIsInstantApp =
18511                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18512                    doDeletePackage = !targetIsInstantApp
18513                            || canViewInstantApps;
18514                }
18515                if (doDeletePackage) {
18516                    if (!deleteAllUsers) {
18517                        returnCode = deletePackageX(internalPackageName, versionCode,
18518                                userId, deleteFlags);
18519                    } else {
18520                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18521                                internalPackageName, users);
18522                        // If nobody is blocking uninstall, proceed with delete for all users
18523                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18524                            returnCode = deletePackageX(internalPackageName, versionCode,
18525                                    userId, deleteFlags);
18526                        } else {
18527                            // Otherwise uninstall individually for users with blockUninstalls=false
18528                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18529                            for (int userId : users) {
18530                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18531                                    returnCode = deletePackageX(internalPackageName, versionCode,
18532                                            userId, userFlags);
18533                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18534                                        Slog.w(TAG, "Package delete failed for user " + userId
18535                                                + ", returnCode " + returnCode);
18536                                    }
18537                                }
18538                            }
18539                            // The app has only been marked uninstalled for certain users.
18540                            // We still need to report that delete was blocked
18541                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18542                        }
18543                    }
18544                } else {
18545                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18546                }
18547                try {
18548                    observer.onPackageDeleted(packageName, returnCode, null);
18549                } catch (RemoteException e) {
18550                    Log.i(TAG, "Observer no longer exists.");
18551                } //end catch
18552            } //end run
18553        });
18554    }
18555
18556    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18557        if (pkg.staticSharedLibName != null) {
18558            return pkg.manifestPackageName;
18559        }
18560        return pkg.packageName;
18561    }
18562
18563    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18564        // Handle renamed packages
18565        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18566        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18567
18568        // Is this a static library?
18569        SparseArray<SharedLibraryEntry> versionedLib =
18570                mStaticLibsByDeclaringPackage.get(packageName);
18571        if (versionedLib == null || versionedLib.size() <= 0) {
18572            return packageName;
18573        }
18574
18575        // Figure out which lib versions the caller can see
18576        SparseIntArray versionsCallerCanSee = null;
18577        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18578        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18579                && callingAppId != Process.ROOT_UID) {
18580            versionsCallerCanSee = new SparseIntArray();
18581            String libName = versionedLib.valueAt(0).info.getName();
18582            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18583            if (uidPackages != null) {
18584                for (String uidPackage : uidPackages) {
18585                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18586                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18587                    if (libIdx >= 0) {
18588                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18589                        versionsCallerCanSee.append(libVersion, libVersion);
18590                    }
18591                }
18592            }
18593        }
18594
18595        // Caller can see nothing - done
18596        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18597            return packageName;
18598        }
18599
18600        // Find the version the caller can see and the app version code
18601        SharedLibraryEntry highestVersion = null;
18602        final int versionCount = versionedLib.size();
18603        for (int i = 0; i < versionCount; i++) {
18604            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18605            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18606                    libEntry.info.getVersion()) < 0) {
18607                continue;
18608            }
18609            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18610            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18611                if (libVersionCode == versionCode) {
18612                    return libEntry.apk;
18613                }
18614            } else if (highestVersion == null) {
18615                highestVersion = libEntry;
18616            } else if (libVersionCode  > highestVersion.info
18617                    .getDeclaringPackage().getVersionCode()) {
18618                highestVersion = libEntry;
18619            }
18620        }
18621
18622        if (highestVersion != null) {
18623            return highestVersion.apk;
18624        }
18625
18626        return packageName;
18627    }
18628
18629    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18630        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18631              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18632            return true;
18633        }
18634        final int callingUserId = UserHandle.getUserId(callingUid);
18635        // If the caller installed the pkgName, then allow it to silently uninstall.
18636        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18637            return true;
18638        }
18639
18640        // Allow package verifier to silently uninstall.
18641        if (mRequiredVerifierPackage != null &&
18642                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18643            return true;
18644        }
18645
18646        // Allow package uninstaller to silently uninstall.
18647        if (mRequiredUninstallerPackage != null &&
18648                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18649            return true;
18650        }
18651
18652        // Allow storage manager to silently uninstall.
18653        if (mStorageManagerPackage != null &&
18654                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18655            return true;
18656        }
18657
18658        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18659        // uninstall for device owner provisioning.
18660        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18661                == PERMISSION_GRANTED) {
18662            return true;
18663        }
18664
18665        return false;
18666    }
18667
18668    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18669        int[] result = EMPTY_INT_ARRAY;
18670        for (int userId : userIds) {
18671            if (getBlockUninstallForUser(packageName, userId)) {
18672                result = ArrayUtils.appendInt(result, userId);
18673            }
18674        }
18675        return result;
18676    }
18677
18678    @Override
18679    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18680        final int callingUid = Binder.getCallingUid();
18681        if (getInstantAppPackageName(callingUid) != null
18682                && !isCallerSameApp(packageName, callingUid)) {
18683            return false;
18684        }
18685        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18686    }
18687
18688    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18689        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18690                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18691        try {
18692            if (dpm != null) {
18693                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18694                        /* callingUserOnly =*/ false);
18695                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18696                        : deviceOwnerComponentName.getPackageName();
18697                // Does the package contains the device owner?
18698                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18699                // this check is probably not needed, since DO should be registered as a device
18700                // admin on some user too. (Original bug for this: b/17657954)
18701                if (packageName.equals(deviceOwnerPackageName)) {
18702                    return true;
18703                }
18704                // Does it contain a device admin for any user?
18705                int[] users;
18706                if (userId == UserHandle.USER_ALL) {
18707                    users = sUserManager.getUserIds();
18708                } else {
18709                    users = new int[]{userId};
18710                }
18711                for (int i = 0; i < users.length; ++i) {
18712                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18713                        return true;
18714                    }
18715                }
18716            }
18717        } catch (RemoteException e) {
18718        }
18719        return false;
18720    }
18721
18722    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18723        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18724    }
18725
18726    /**
18727     *  This method is an internal method that could be get invoked either
18728     *  to delete an installed package or to clean up a failed installation.
18729     *  After deleting an installed package, a broadcast is sent to notify any
18730     *  listeners that the package has been removed. For cleaning up a failed
18731     *  installation, the broadcast is not necessary since the package's
18732     *  installation wouldn't have sent the initial broadcast either
18733     *  The key steps in deleting a package are
18734     *  deleting the package information in internal structures like mPackages,
18735     *  deleting the packages base directories through installd
18736     *  updating mSettings to reflect current status
18737     *  persisting settings for later use
18738     *  sending a broadcast if necessary
18739     */
18740    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18741        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18742        final boolean res;
18743
18744        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18745                ? UserHandle.USER_ALL : userId;
18746
18747        if (isPackageDeviceAdmin(packageName, removeUser)) {
18748            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18749            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18750        }
18751
18752        PackageSetting uninstalledPs = null;
18753        PackageParser.Package pkg = null;
18754
18755        // for the uninstall-updates case and restricted profiles, remember the per-
18756        // user handle installed state
18757        int[] allUsers;
18758        synchronized (mPackages) {
18759            uninstalledPs = mSettings.mPackages.get(packageName);
18760            if (uninstalledPs == null) {
18761                Slog.w(TAG, "Not removing non-existent package " + packageName);
18762                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18763            }
18764
18765            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18766                    && uninstalledPs.versionCode != versionCode) {
18767                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18768                        + uninstalledPs.versionCode + " != " + versionCode);
18769                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18770            }
18771
18772            // Static shared libs can be declared by any package, so let us not
18773            // allow removing a package if it provides a lib others depend on.
18774            pkg = mPackages.get(packageName);
18775
18776            allUsers = sUserManager.getUserIds();
18777
18778            if (pkg != null && pkg.staticSharedLibName != null) {
18779                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18780                        pkg.staticSharedLibVersion);
18781                if (libEntry != null) {
18782                    for (int currUserId : allUsers) {
18783                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18784                            continue;
18785                        }
18786                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18787                                libEntry.info, 0, currUserId);
18788                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18789                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18790                                    + " hosting lib " + libEntry.info.getName() + " version "
18791                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18792                                    + " for user " + currUserId);
18793                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18794                        }
18795                    }
18796                }
18797            }
18798
18799            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18800        }
18801
18802        final int freezeUser;
18803        if (isUpdatedSystemApp(uninstalledPs)
18804                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18805            // We're downgrading a system app, which will apply to all users, so
18806            // freeze them all during the downgrade
18807            freezeUser = UserHandle.USER_ALL;
18808        } else {
18809            freezeUser = removeUser;
18810        }
18811
18812        synchronized (mInstallLock) {
18813            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18814            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18815                    deleteFlags, "deletePackageX")) {
18816                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18817                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18818            }
18819            synchronized (mPackages) {
18820                if (res) {
18821                    if (pkg != null) {
18822                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18823                    }
18824                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18825                    updateInstantAppInstallerLocked(packageName);
18826                }
18827            }
18828        }
18829
18830        if (res) {
18831            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18832            info.sendPackageRemovedBroadcasts(killApp);
18833            info.sendSystemPackageUpdatedBroadcasts();
18834            info.sendSystemPackageAppearedBroadcasts();
18835        }
18836        // Force a gc here.
18837        Runtime.getRuntime().gc();
18838        // Delete the resources here after sending the broadcast to let
18839        // other processes clean up before deleting resources.
18840        if (info.args != null) {
18841            synchronized (mInstallLock) {
18842                info.args.doPostDeleteLI(true);
18843            }
18844        }
18845
18846        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18847    }
18848
18849    static class PackageRemovedInfo {
18850        final PackageSender packageSender;
18851        String removedPackage;
18852        String installerPackageName;
18853        int uid = -1;
18854        int removedAppId = -1;
18855        int[] origUsers;
18856        int[] removedUsers = null;
18857        int[] broadcastUsers = null;
18858        SparseArray<Integer> installReasons;
18859        boolean isRemovedPackageSystemUpdate = false;
18860        boolean isUpdate;
18861        boolean dataRemoved;
18862        boolean removedForAllUsers;
18863        boolean isStaticSharedLib;
18864        // Clean up resources deleted packages.
18865        InstallArgs args = null;
18866        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18867        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18868
18869        PackageRemovedInfo(PackageSender packageSender) {
18870            this.packageSender = packageSender;
18871        }
18872
18873        void sendPackageRemovedBroadcasts(boolean killApp) {
18874            sendPackageRemovedBroadcastInternal(killApp);
18875            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18876            for (int i = 0; i < childCount; i++) {
18877                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18878                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18879            }
18880        }
18881
18882        void sendSystemPackageUpdatedBroadcasts() {
18883            if (isRemovedPackageSystemUpdate) {
18884                sendSystemPackageUpdatedBroadcastsInternal();
18885                final int childCount = (removedChildPackages != null)
18886                        ? removedChildPackages.size() : 0;
18887                for (int i = 0; i < childCount; i++) {
18888                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18889                    if (childInfo.isRemovedPackageSystemUpdate) {
18890                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18891                    }
18892                }
18893            }
18894        }
18895
18896        void sendSystemPackageAppearedBroadcasts() {
18897            final int packageCount = (appearedChildPackages != null)
18898                    ? appearedChildPackages.size() : 0;
18899            for (int i = 0; i < packageCount; i++) {
18900                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18901                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18902                    true, UserHandle.getAppId(installedInfo.uid),
18903                    installedInfo.newUsers);
18904            }
18905        }
18906
18907        private void sendSystemPackageUpdatedBroadcastsInternal() {
18908            Bundle extras = new Bundle(2);
18909            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18910            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18911            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18912                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18913            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18914                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18915            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18916                null, null, 0, removedPackage, null, null);
18917            if (installerPackageName != null) {
18918                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18919                        removedPackage, extras, 0 /*flags*/,
18920                        installerPackageName, null, null);
18921                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18922                        removedPackage, extras, 0 /*flags*/,
18923                        installerPackageName, null, null);
18924            }
18925        }
18926
18927        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18928            // Don't send static shared library removal broadcasts as these
18929            // libs are visible only the the apps that depend on them an one
18930            // cannot remove the library if it has a dependency.
18931            if (isStaticSharedLib) {
18932                return;
18933            }
18934            Bundle extras = new Bundle(2);
18935            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18936            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18937            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18938            if (isUpdate || isRemovedPackageSystemUpdate) {
18939                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18940            }
18941            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18942            if (removedPackage != null) {
18943                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18944                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18945                if (installerPackageName != null) {
18946                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18947                            removedPackage, extras, 0 /*flags*/,
18948                            installerPackageName, null, broadcastUsers);
18949                }
18950                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18951                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18952                        removedPackage, extras,
18953                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18954                        null, null, broadcastUsers);
18955                }
18956            }
18957            if (removedAppId >= 0) {
18958                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18959                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18960            }
18961        }
18962
18963        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18964            removedUsers = userIds;
18965            if (removedUsers == null) {
18966                broadcastUsers = null;
18967                return;
18968            }
18969
18970            broadcastUsers = EMPTY_INT_ARRAY;
18971            for (int i = userIds.length - 1; i >= 0; --i) {
18972                final int userId = userIds[i];
18973                if (deletedPackageSetting.getInstantApp(userId)) {
18974                    continue;
18975                }
18976                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18977            }
18978        }
18979    }
18980
18981    /*
18982     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18983     * flag is not set, the data directory is removed as well.
18984     * make sure this flag is set for partially installed apps. If not its meaningless to
18985     * delete a partially installed application.
18986     */
18987    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18988            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18989        String packageName = ps.name;
18990        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18991        // Retrieve object to delete permissions for shared user later on
18992        final PackageParser.Package deletedPkg;
18993        final PackageSetting deletedPs;
18994        // reader
18995        synchronized (mPackages) {
18996            deletedPkg = mPackages.get(packageName);
18997            deletedPs = mSettings.mPackages.get(packageName);
18998            if (outInfo != null) {
18999                outInfo.removedPackage = packageName;
19000                outInfo.installerPackageName = ps.installerPackageName;
19001                outInfo.isStaticSharedLib = deletedPkg != null
19002                        && deletedPkg.staticSharedLibName != null;
19003                outInfo.populateUsers(deletedPs == null ? null
19004                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19005            }
19006        }
19007
19008        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19009
19010        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19011            final PackageParser.Package resolvedPkg;
19012            if (deletedPkg != null) {
19013                resolvedPkg = deletedPkg;
19014            } else {
19015                // We don't have a parsed package when it lives on an ejected
19016                // adopted storage device, so fake something together
19017                resolvedPkg = new PackageParser.Package(ps.name);
19018                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19019            }
19020            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19021                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19022            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19023            if (outInfo != null) {
19024                outInfo.dataRemoved = true;
19025            }
19026            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19027        }
19028
19029        int removedAppId = -1;
19030
19031        // writer
19032        synchronized (mPackages) {
19033            boolean installedStateChanged = false;
19034            if (deletedPs != null) {
19035                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19036                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19037                    clearDefaultBrowserIfNeeded(packageName);
19038                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19039                    removedAppId = mSettings.removePackageLPw(packageName);
19040                    if (outInfo != null) {
19041                        outInfo.removedAppId = removedAppId;
19042                    }
19043                    updatePermissionsLPw(deletedPs.name, null, 0);
19044                    if (deletedPs.sharedUser != null) {
19045                        // Remove permissions associated with package. Since runtime
19046                        // permissions are per user we have to kill the removed package
19047                        // or packages running under the shared user of the removed
19048                        // package if revoking the permissions requested only by the removed
19049                        // package is successful and this causes a change in gids.
19050                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19051                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19052                                    userId);
19053                            if (userIdToKill == UserHandle.USER_ALL
19054                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19055                                // If gids changed for this user, kill all affected packages.
19056                                mHandler.post(new Runnable() {
19057                                    @Override
19058                                    public void run() {
19059                                        // This has to happen with no lock held.
19060                                        killApplication(deletedPs.name, deletedPs.appId,
19061                                                KILL_APP_REASON_GIDS_CHANGED);
19062                                    }
19063                                });
19064                                break;
19065                            }
19066                        }
19067                    }
19068                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19069                }
19070                // make sure to preserve per-user disabled state if this removal was just
19071                // a downgrade of a system app to the factory package
19072                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19073                    if (DEBUG_REMOVE) {
19074                        Slog.d(TAG, "Propagating install state across downgrade");
19075                    }
19076                    for (int userId : allUserHandles) {
19077                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19078                        if (DEBUG_REMOVE) {
19079                            Slog.d(TAG, "    user " + userId + " => " + installed);
19080                        }
19081                        if (installed != ps.getInstalled(userId)) {
19082                            installedStateChanged = true;
19083                        }
19084                        ps.setInstalled(installed, userId);
19085                    }
19086                }
19087            }
19088            // can downgrade to reader
19089            if (writeSettings) {
19090                // Save settings now
19091                mSettings.writeLPr();
19092            }
19093            if (installedStateChanged) {
19094                mSettings.writeKernelMappingLPr(ps);
19095            }
19096        }
19097        if (removedAppId != -1) {
19098            // A user ID was deleted here. Go through all users and remove it
19099            // from KeyStore.
19100            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19101        }
19102    }
19103
19104    static boolean locationIsPrivileged(File path) {
19105        try {
19106            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19107                    .getCanonicalPath();
19108            return path.getCanonicalPath().startsWith(privilegedAppDir);
19109        } catch (IOException e) {
19110            Slog.e(TAG, "Unable to access code path " + path);
19111        }
19112        return false;
19113    }
19114
19115    /*
19116     * Tries to delete system package.
19117     */
19118    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19119            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19120            boolean writeSettings) {
19121        if (deletedPs.parentPackageName != null) {
19122            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19123            return false;
19124        }
19125
19126        final boolean applyUserRestrictions
19127                = (allUserHandles != null) && (outInfo.origUsers != null);
19128        final PackageSetting disabledPs;
19129        // Confirm if the system package has been updated
19130        // An updated system app can be deleted. This will also have to restore
19131        // the system pkg from system partition
19132        // reader
19133        synchronized (mPackages) {
19134            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19135        }
19136
19137        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19138                + " disabledPs=" + disabledPs);
19139
19140        if (disabledPs == null) {
19141            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19142            return false;
19143        } else if (DEBUG_REMOVE) {
19144            Slog.d(TAG, "Deleting system pkg from data partition");
19145        }
19146
19147        if (DEBUG_REMOVE) {
19148            if (applyUserRestrictions) {
19149                Slog.d(TAG, "Remembering install states:");
19150                for (int userId : allUserHandles) {
19151                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19152                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19153                }
19154            }
19155        }
19156
19157        // Delete the updated package
19158        outInfo.isRemovedPackageSystemUpdate = true;
19159        if (outInfo.removedChildPackages != null) {
19160            final int childCount = (deletedPs.childPackageNames != null)
19161                    ? deletedPs.childPackageNames.size() : 0;
19162            for (int i = 0; i < childCount; i++) {
19163                String childPackageName = deletedPs.childPackageNames.get(i);
19164                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19165                        .contains(childPackageName)) {
19166                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19167                            childPackageName);
19168                    if (childInfo != null) {
19169                        childInfo.isRemovedPackageSystemUpdate = true;
19170                    }
19171                }
19172            }
19173        }
19174
19175        if (disabledPs.versionCode < deletedPs.versionCode) {
19176            // Delete data for downgrades
19177            flags &= ~PackageManager.DELETE_KEEP_DATA;
19178        } else {
19179            // Preserve data by setting flag
19180            flags |= PackageManager.DELETE_KEEP_DATA;
19181        }
19182
19183        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19184                outInfo, writeSettings, disabledPs.pkg);
19185        if (!ret) {
19186            return false;
19187        }
19188
19189        // writer
19190        synchronized (mPackages) {
19191            // Reinstate the old system package
19192            enableSystemPackageLPw(disabledPs.pkg);
19193            // Remove any native libraries from the upgraded package.
19194            removeNativeBinariesLI(deletedPs);
19195        }
19196
19197        // Install the system package
19198        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19199        int parseFlags = mDefParseFlags
19200                | PackageParser.PARSE_MUST_BE_APK
19201                | PackageParser.PARSE_IS_SYSTEM
19202                | PackageParser.PARSE_IS_SYSTEM_DIR;
19203        if (locationIsPrivileged(disabledPs.codePath)) {
19204            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19205        }
19206
19207        final PackageParser.Package newPkg;
19208        try {
19209            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19210                0 /* currentTime */, null);
19211        } catch (PackageManagerException e) {
19212            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19213                    + e.getMessage());
19214            return false;
19215        }
19216
19217        try {
19218            // update shared libraries for the newly re-installed system package
19219            updateSharedLibrariesLPr(newPkg, null);
19220        } catch (PackageManagerException e) {
19221            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19222        }
19223
19224        prepareAppDataAfterInstallLIF(newPkg);
19225
19226        // writer
19227        synchronized (mPackages) {
19228            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19229
19230            // Propagate the permissions state as we do not want to drop on the floor
19231            // runtime permissions. The update permissions method below will take
19232            // care of removing obsolete permissions and grant install permissions.
19233            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19234            updatePermissionsLPw(newPkg.packageName, newPkg,
19235                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19236
19237            if (applyUserRestrictions) {
19238                boolean installedStateChanged = false;
19239                if (DEBUG_REMOVE) {
19240                    Slog.d(TAG, "Propagating install state across reinstall");
19241                }
19242                for (int userId : allUserHandles) {
19243                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19244                    if (DEBUG_REMOVE) {
19245                        Slog.d(TAG, "    user " + userId + " => " + installed);
19246                    }
19247                    if (installed != ps.getInstalled(userId)) {
19248                        installedStateChanged = true;
19249                    }
19250                    ps.setInstalled(installed, userId);
19251
19252                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19253                }
19254                // Regardless of writeSettings we need to ensure that this restriction
19255                // state propagation is persisted
19256                mSettings.writeAllUsersPackageRestrictionsLPr();
19257                if (installedStateChanged) {
19258                    mSettings.writeKernelMappingLPr(ps);
19259                }
19260            }
19261            // can downgrade to reader here
19262            if (writeSettings) {
19263                mSettings.writeLPr();
19264            }
19265        }
19266        return true;
19267    }
19268
19269    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19270            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19271            PackageRemovedInfo outInfo, boolean writeSettings,
19272            PackageParser.Package replacingPackage) {
19273        synchronized (mPackages) {
19274            if (outInfo != null) {
19275                outInfo.uid = ps.appId;
19276            }
19277
19278            if (outInfo != null && outInfo.removedChildPackages != null) {
19279                final int childCount = (ps.childPackageNames != null)
19280                        ? ps.childPackageNames.size() : 0;
19281                for (int i = 0; i < childCount; i++) {
19282                    String childPackageName = ps.childPackageNames.get(i);
19283                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19284                    if (childPs == null) {
19285                        return false;
19286                    }
19287                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19288                            childPackageName);
19289                    if (childInfo != null) {
19290                        childInfo.uid = childPs.appId;
19291                    }
19292                }
19293            }
19294        }
19295
19296        // Delete package data from internal structures and also remove data if flag is set
19297        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19298
19299        // Delete the child packages data
19300        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19301        for (int i = 0; i < childCount; i++) {
19302            PackageSetting childPs;
19303            synchronized (mPackages) {
19304                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19305            }
19306            if (childPs != null) {
19307                PackageRemovedInfo childOutInfo = (outInfo != null
19308                        && outInfo.removedChildPackages != null)
19309                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19310                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19311                        && (replacingPackage != null
19312                        && !replacingPackage.hasChildPackage(childPs.name))
19313                        ? flags & ~DELETE_KEEP_DATA : flags;
19314                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19315                        deleteFlags, writeSettings);
19316            }
19317        }
19318
19319        // Delete application code and resources only for parent packages
19320        if (ps.parentPackageName == null) {
19321            if (deleteCodeAndResources && (outInfo != null)) {
19322                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19323                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19324                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19325            }
19326        }
19327
19328        return true;
19329    }
19330
19331    @Override
19332    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19333            int userId) {
19334        mContext.enforceCallingOrSelfPermission(
19335                android.Manifest.permission.DELETE_PACKAGES, null);
19336        synchronized (mPackages) {
19337            // Cannot block uninstall of static shared libs as they are
19338            // considered a part of the using app (emulating static linking).
19339            // Also static libs are installed always on internal storage.
19340            PackageParser.Package pkg = mPackages.get(packageName);
19341            if (pkg != null && pkg.staticSharedLibName != null) {
19342                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19343                        + " providing static shared library: " + pkg.staticSharedLibName);
19344                return false;
19345            }
19346            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19347            mSettings.writePackageRestrictionsLPr(userId);
19348        }
19349        return true;
19350    }
19351
19352    @Override
19353    public boolean getBlockUninstallForUser(String packageName, int userId) {
19354        synchronized (mPackages) {
19355            final PackageSetting ps = mSettings.mPackages.get(packageName);
19356            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19357                return false;
19358            }
19359            return mSettings.getBlockUninstallLPr(userId, packageName);
19360        }
19361    }
19362
19363    @Override
19364    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19365        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19366        synchronized (mPackages) {
19367            PackageSetting ps = mSettings.mPackages.get(packageName);
19368            if (ps == null) {
19369                Log.w(TAG, "Package doesn't exist: " + packageName);
19370                return false;
19371            }
19372            if (systemUserApp) {
19373                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19374            } else {
19375                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19376            }
19377            mSettings.writeLPr();
19378        }
19379        return true;
19380    }
19381
19382    /*
19383     * This method handles package deletion in general
19384     */
19385    private boolean deletePackageLIF(String packageName, UserHandle user,
19386            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19387            PackageRemovedInfo outInfo, boolean writeSettings,
19388            PackageParser.Package replacingPackage) {
19389        if (packageName == null) {
19390            Slog.w(TAG, "Attempt to delete null packageName.");
19391            return false;
19392        }
19393
19394        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19395
19396        PackageSetting ps;
19397        synchronized (mPackages) {
19398            ps = mSettings.mPackages.get(packageName);
19399            if (ps == null) {
19400                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19401                return false;
19402            }
19403
19404            if (ps.parentPackageName != null && (!isSystemApp(ps)
19405                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19406                if (DEBUG_REMOVE) {
19407                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19408                            + ((user == null) ? UserHandle.USER_ALL : user));
19409                }
19410                final int removedUserId = (user != null) ? user.getIdentifier()
19411                        : UserHandle.USER_ALL;
19412                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19413                    return false;
19414                }
19415                markPackageUninstalledForUserLPw(ps, user);
19416                scheduleWritePackageRestrictionsLocked(user);
19417                return true;
19418            }
19419        }
19420
19421        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19422                && user.getIdentifier() != UserHandle.USER_ALL)) {
19423            // The caller is asking that the package only be deleted for a single
19424            // user.  To do this, we just mark its uninstalled state and delete
19425            // its data. If this is a system app, we only allow this to happen if
19426            // they have set the special DELETE_SYSTEM_APP which requests different
19427            // semantics than normal for uninstalling system apps.
19428            markPackageUninstalledForUserLPw(ps, user);
19429
19430            if (!isSystemApp(ps)) {
19431                // Do not uninstall the APK if an app should be cached
19432                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19433                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19434                    // Other user still have this package installed, so all
19435                    // we need to do is clear this user's data and save that
19436                    // it is uninstalled.
19437                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19438                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19439                        return false;
19440                    }
19441                    scheduleWritePackageRestrictionsLocked(user);
19442                    return true;
19443                } else {
19444                    // We need to set it back to 'installed' so the uninstall
19445                    // broadcasts will be sent correctly.
19446                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19447                    ps.setInstalled(true, user.getIdentifier());
19448                    mSettings.writeKernelMappingLPr(ps);
19449                }
19450            } else {
19451                // This is a system app, so we assume that the
19452                // other users still have this package installed, so all
19453                // we need to do is clear this user's data and save that
19454                // it is uninstalled.
19455                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19456                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19457                    return false;
19458                }
19459                scheduleWritePackageRestrictionsLocked(user);
19460                return true;
19461            }
19462        }
19463
19464        // If we are deleting a composite package for all users, keep track
19465        // of result for each child.
19466        if (ps.childPackageNames != null && outInfo != null) {
19467            synchronized (mPackages) {
19468                final int childCount = ps.childPackageNames.size();
19469                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19470                for (int i = 0; i < childCount; i++) {
19471                    String childPackageName = ps.childPackageNames.get(i);
19472                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19473                    childInfo.removedPackage = childPackageName;
19474                    childInfo.installerPackageName = ps.installerPackageName;
19475                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19476                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19477                    if (childPs != null) {
19478                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19479                    }
19480                }
19481            }
19482        }
19483
19484        boolean ret = false;
19485        if (isSystemApp(ps)) {
19486            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19487            // When an updated system application is deleted we delete the existing resources
19488            // as well and fall back to existing code in system partition
19489            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19490        } else {
19491            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19492            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19493                    outInfo, writeSettings, replacingPackage);
19494        }
19495
19496        // Take a note whether we deleted the package for all users
19497        if (outInfo != null) {
19498            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19499            if (outInfo.removedChildPackages != null) {
19500                synchronized (mPackages) {
19501                    final int childCount = outInfo.removedChildPackages.size();
19502                    for (int i = 0; i < childCount; i++) {
19503                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19504                        if (childInfo != null) {
19505                            childInfo.removedForAllUsers = mPackages.get(
19506                                    childInfo.removedPackage) == null;
19507                        }
19508                    }
19509                }
19510            }
19511            // If we uninstalled an update to a system app there may be some
19512            // child packages that appeared as they are declared in the system
19513            // app but were not declared in the update.
19514            if (isSystemApp(ps)) {
19515                synchronized (mPackages) {
19516                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19517                    final int childCount = (updatedPs.childPackageNames != null)
19518                            ? updatedPs.childPackageNames.size() : 0;
19519                    for (int i = 0; i < childCount; i++) {
19520                        String childPackageName = updatedPs.childPackageNames.get(i);
19521                        if (outInfo.removedChildPackages == null
19522                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19523                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19524                            if (childPs == null) {
19525                                continue;
19526                            }
19527                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19528                            installRes.name = childPackageName;
19529                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19530                            installRes.pkg = mPackages.get(childPackageName);
19531                            installRes.uid = childPs.pkg.applicationInfo.uid;
19532                            if (outInfo.appearedChildPackages == null) {
19533                                outInfo.appearedChildPackages = new ArrayMap<>();
19534                            }
19535                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19536                        }
19537                    }
19538                }
19539            }
19540        }
19541
19542        return ret;
19543    }
19544
19545    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19546        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19547                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19548        for (int nextUserId : userIds) {
19549            if (DEBUG_REMOVE) {
19550                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19551            }
19552            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19553                    false /*installed*/,
19554                    true /*stopped*/,
19555                    true /*notLaunched*/,
19556                    false /*hidden*/,
19557                    false /*suspended*/,
19558                    false /*instantApp*/,
19559                    null /*lastDisableAppCaller*/,
19560                    null /*enabledComponents*/,
19561                    null /*disabledComponents*/,
19562                    ps.readUserState(nextUserId).domainVerificationStatus,
19563                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19564        }
19565        mSettings.writeKernelMappingLPr(ps);
19566    }
19567
19568    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19569            PackageRemovedInfo outInfo) {
19570        final PackageParser.Package pkg;
19571        synchronized (mPackages) {
19572            pkg = mPackages.get(ps.name);
19573        }
19574
19575        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19576                : new int[] {userId};
19577        for (int nextUserId : userIds) {
19578            if (DEBUG_REMOVE) {
19579                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19580                        + nextUserId);
19581            }
19582
19583            destroyAppDataLIF(pkg, userId,
19584                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19585            destroyAppProfilesLIF(pkg, userId);
19586            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19587            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19588            schedulePackageCleaning(ps.name, nextUserId, false);
19589            synchronized (mPackages) {
19590                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19591                    scheduleWritePackageRestrictionsLocked(nextUserId);
19592                }
19593                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19594            }
19595        }
19596
19597        if (outInfo != null) {
19598            outInfo.removedPackage = ps.name;
19599            outInfo.installerPackageName = ps.installerPackageName;
19600            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19601            outInfo.removedAppId = ps.appId;
19602            outInfo.removedUsers = userIds;
19603            outInfo.broadcastUsers = userIds;
19604        }
19605
19606        return true;
19607    }
19608
19609    private final class ClearStorageConnection implements ServiceConnection {
19610        IMediaContainerService mContainerService;
19611
19612        @Override
19613        public void onServiceConnected(ComponentName name, IBinder service) {
19614            synchronized (this) {
19615                mContainerService = IMediaContainerService.Stub
19616                        .asInterface(Binder.allowBlocking(service));
19617                notifyAll();
19618            }
19619        }
19620
19621        @Override
19622        public void onServiceDisconnected(ComponentName name) {
19623        }
19624    }
19625
19626    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19627        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19628
19629        final boolean mounted;
19630        if (Environment.isExternalStorageEmulated()) {
19631            mounted = true;
19632        } else {
19633            final String status = Environment.getExternalStorageState();
19634
19635            mounted = status.equals(Environment.MEDIA_MOUNTED)
19636                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19637        }
19638
19639        if (!mounted) {
19640            return;
19641        }
19642
19643        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19644        int[] users;
19645        if (userId == UserHandle.USER_ALL) {
19646            users = sUserManager.getUserIds();
19647        } else {
19648            users = new int[] { userId };
19649        }
19650        final ClearStorageConnection conn = new ClearStorageConnection();
19651        if (mContext.bindServiceAsUser(
19652                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19653            try {
19654                for (int curUser : users) {
19655                    long timeout = SystemClock.uptimeMillis() + 5000;
19656                    synchronized (conn) {
19657                        long now;
19658                        while (conn.mContainerService == null &&
19659                                (now = SystemClock.uptimeMillis()) < timeout) {
19660                            try {
19661                                conn.wait(timeout - now);
19662                            } catch (InterruptedException e) {
19663                            }
19664                        }
19665                    }
19666                    if (conn.mContainerService == null) {
19667                        return;
19668                    }
19669
19670                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19671                    clearDirectory(conn.mContainerService,
19672                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19673                    if (allData) {
19674                        clearDirectory(conn.mContainerService,
19675                                userEnv.buildExternalStorageAppDataDirs(packageName));
19676                        clearDirectory(conn.mContainerService,
19677                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19678                    }
19679                }
19680            } finally {
19681                mContext.unbindService(conn);
19682            }
19683        }
19684    }
19685
19686    @Override
19687    public void clearApplicationProfileData(String packageName) {
19688        enforceSystemOrRoot("Only the system can clear all profile data");
19689
19690        final PackageParser.Package pkg;
19691        synchronized (mPackages) {
19692            pkg = mPackages.get(packageName);
19693        }
19694
19695        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19696            synchronized (mInstallLock) {
19697                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19698            }
19699        }
19700    }
19701
19702    @Override
19703    public void clearApplicationUserData(final String packageName,
19704            final IPackageDataObserver observer, final int userId) {
19705        mContext.enforceCallingOrSelfPermission(
19706                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19707
19708        final int callingUid = Binder.getCallingUid();
19709        enforceCrossUserPermission(callingUid, userId,
19710                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19711
19712        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19713        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19714            return;
19715        }
19716        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19717            throw new SecurityException("Cannot clear data for a protected package: "
19718                    + packageName);
19719        }
19720        // Queue up an async operation since the package deletion may take a little while.
19721        mHandler.post(new Runnable() {
19722            public void run() {
19723                mHandler.removeCallbacks(this);
19724                final boolean succeeded;
19725                try (PackageFreezer freezer = freezePackage(packageName,
19726                        "clearApplicationUserData")) {
19727                    synchronized (mInstallLock) {
19728                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19729                    }
19730                    clearExternalStorageDataSync(packageName, userId, true);
19731                    synchronized (mPackages) {
19732                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19733                                packageName, userId);
19734                    }
19735                }
19736                if (succeeded) {
19737                    // invoke DeviceStorageMonitor's update method to clear any notifications
19738                    DeviceStorageMonitorInternal dsm = LocalServices
19739                            .getService(DeviceStorageMonitorInternal.class);
19740                    if (dsm != null) {
19741                        dsm.checkMemory();
19742                    }
19743                }
19744                if(observer != null) {
19745                    try {
19746                        observer.onRemoveCompleted(packageName, succeeded);
19747                    } catch (RemoteException e) {
19748                        Log.i(TAG, "Observer no longer exists.");
19749                    }
19750                } //end if observer
19751            } //end run
19752        });
19753    }
19754
19755    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19756        if (packageName == null) {
19757            Slog.w(TAG, "Attempt to delete null packageName.");
19758            return false;
19759        }
19760
19761        // Try finding details about the requested package
19762        PackageParser.Package pkg;
19763        synchronized (mPackages) {
19764            pkg = mPackages.get(packageName);
19765            if (pkg == null) {
19766                final PackageSetting ps = mSettings.mPackages.get(packageName);
19767                if (ps != null) {
19768                    pkg = ps.pkg;
19769                }
19770            }
19771
19772            if (pkg == null) {
19773                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19774                return false;
19775            }
19776
19777            PackageSetting ps = (PackageSetting) pkg.mExtras;
19778            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19779        }
19780
19781        clearAppDataLIF(pkg, userId,
19782                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19783
19784        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19785        removeKeystoreDataIfNeeded(userId, appId);
19786
19787        UserManagerInternal umInternal = getUserManagerInternal();
19788        final int flags;
19789        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19790            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19791        } else if (umInternal.isUserRunning(userId)) {
19792            flags = StorageManager.FLAG_STORAGE_DE;
19793        } else {
19794            flags = 0;
19795        }
19796        prepareAppDataContentsLIF(pkg, userId, flags);
19797
19798        return true;
19799    }
19800
19801    /**
19802     * Reverts user permission state changes (permissions and flags) in
19803     * all packages for a given user.
19804     *
19805     * @param userId The device user for which to do a reset.
19806     */
19807    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19808        final int packageCount = mPackages.size();
19809        for (int i = 0; i < packageCount; i++) {
19810            PackageParser.Package pkg = mPackages.valueAt(i);
19811            PackageSetting ps = (PackageSetting) pkg.mExtras;
19812            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19813        }
19814    }
19815
19816    private void resetNetworkPolicies(int userId) {
19817        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19818    }
19819
19820    /**
19821     * Reverts user permission state changes (permissions and flags).
19822     *
19823     * @param ps The package for which to reset.
19824     * @param userId The device user for which to do a reset.
19825     */
19826    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19827            final PackageSetting ps, final int userId) {
19828        if (ps.pkg == null) {
19829            return;
19830        }
19831
19832        // These are flags that can change base on user actions.
19833        final int userSettableMask = FLAG_PERMISSION_USER_SET
19834                | FLAG_PERMISSION_USER_FIXED
19835                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19836                | FLAG_PERMISSION_REVIEW_REQUIRED;
19837
19838        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19839                | FLAG_PERMISSION_POLICY_FIXED;
19840
19841        boolean writeInstallPermissions = false;
19842        boolean writeRuntimePermissions = false;
19843
19844        final int permissionCount = ps.pkg.requestedPermissions.size();
19845        for (int i = 0; i < permissionCount; i++) {
19846            String permission = ps.pkg.requestedPermissions.get(i);
19847
19848            BasePermission bp = mSettings.mPermissions.get(permission);
19849            if (bp == null) {
19850                continue;
19851            }
19852
19853            // If shared user we just reset the state to which only this app contributed.
19854            if (ps.sharedUser != null) {
19855                boolean used = false;
19856                final int packageCount = ps.sharedUser.packages.size();
19857                for (int j = 0; j < packageCount; j++) {
19858                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19859                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19860                            && pkg.pkg.requestedPermissions.contains(permission)) {
19861                        used = true;
19862                        break;
19863                    }
19864                }
19865                if (used) {
19866                    continue;
19867                }
19868            }
19869
19870            PermissionsState permissionsState = ps.getPermissionsState();
19871
19872            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19873
19874            // Always clear the user settable flags.
19875            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19876                    bp.name) != null;
19877            // If permission review is enabled and this is a legacy app, mark the
19878            // permission as requiring a review as this is the initial state.
19879            int flags = 0;
19880            if (mPermissionReviewRequired
19881                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19882                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19883            }
19884            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19885                if (hasInstallState) {
19886                    writeInstallPermissions = true;
19887                } else {
19888                    writeRuntimePermissions = true;
19889                }
19890            }
19891
19892            // Below is only runtime permission handling.
19893            if (!bp.isRuntime()) {
19894                continue;
19895            }
19896
19897            // Never clobber system or policy.
19898            if ((oldFlags & policyOrSystemFlags) != 0) {
19899                continue;
19900            }
19901
19902            // If this permission was granted by default, make sure it is.
19903            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19904                if (permissionsState.grantRuntimePermission(bp, userId)
19905                        != PERMISSION_OPERATION_FAILURE) {
19906                    writeRuntimePermissions = true;
19907                }
19908            // If permission review is enabled the permissions for a legacy apps
19909            // are represented as constantly granted runtime ones, so don't revoke.
19910            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19911                // Otherwise, reset the permission.
19912                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19913                switch (revokeResult) {
19914                    case PERMISSION_OPERATION_SUCCESS:
19915                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19916                        writeRuntimePermissions = true;
19917                        final int appId = ps.appId;
19918                        mHandler.post(new Runnable() {
19919                            @Override
19920                            public void run() {
19921                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19922                            }
19923                        });
19924                    } break;
19925                }
19926            }
19927        }
19928
19929        // Synchronously write as we are taking permissions away.
19930        if (writeRuntimePermissions) {
19931            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19932        }
19933
19934        // Synchronously write as we are taking permissions away.
19935        if (writeInstallPermissions) {
19936            mSettings.writeLPr();
19937        }
19938    }
19939
19940    /**
19941     * Remove entries from the keystore daemon. Will only remove it if the
19942     * {@code appId} is valid.
19943     */
19944    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19945        if (appId < 0) {
19946            return;
19947        }
19948
19949        final KeyStore keyStore = KeyStore.getInstance();
19950        if (keyStore != null) {
19951            if (userId == UserHandle.USER_ALL) {
19952                for (final int individual : sUserManager.getUserIds()) {
19953                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19954                }
19955            } else {
19956                keyStore.clearUid(UserHandle.getUid(userId, appId));
19957            }
19958        } else {
19959            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19960        }
19961    }
19962
19963    @Override
19964    public void deleteApplicationCacheFiles(final String packageName,
19965            final IPackageDataObserver observer) {
19966        final int userId = UserHandle.getCallingUserId();
19967        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19968    }
19969
19970    @Override
19971    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19972            final IPackageDataObserver observer) {
19973        final int callingUid = Binder.getCallingUid();
19974        mContext.enforceCallingOrSelfPermission(
19975                android.Manifest.permission.DELETE_CACHE_FILES, null);
19976        enforceCrossUserPermission(callingUid, userId,
19977                /* requireFullPermission= */ true, /* checkShell= */ false,
19978                "delete application cache files");
19979        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19980                android.Manifest.permission.ACCESS_INSTANT_APPS);
19981
19982        final PackageParser.Package pkg;
19983        synchronized (mPackages) {
19984            pkg = mPackages.get(packageName);
19985        }
19986
19987        // Queue up an async operation since the package deletion may take a little while.
19988        mHandler.post(new Runnable() {
19989            public void run() {
19990                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19991                boolean doClearData = true;
19992                if (ps != null) {
19993                    final boolean targetIsInstantApp =
19994                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19995                    doClearData = !targetIsInstantApp
19996                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19997                }
19998                if (doClearData) {
19999                    synchronized (mInstallLock) {
20000                        final int flags = StorageManager.FLAG_STORAGE_DE
20001                                | StorageManager.FLAG_STORAGE_CE;
20002                        // We're only clearing cache files, so we don't care if the
20003                        // app is unfrozen and still able to run
20004                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20005                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20006                    }
20007                    clearExternalStorageDataSync(packageName, userId, false);
20008                }
20009                if (observer != null) {
20010                    try {
20011                        observer.onRemoveCompleted(packageName, true);
20012                    } catch (RemoteException e) {
20013                        Log.i(TAG, "Observer no longer exists.");
20014                    }
20015                }
20016            }
20017        });
20018    }
20019
20020    @Override
20021    public void getPackageSizeInfo(final String packageName, int userHandle,
20022            final IPackageStatsObserver observer) {
20023        throw new UnsupportedOperationException(
20024                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20025    }
20026
20027    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20028        final PackageSetting ps;
20029        synchronized (mPackages) {
20030            ps = mSettings.mPackages.get(packageName);
20031            if (ps == null) {
20032                Slog.w(TAG, "Failed to find settings for " + packageName);
20033                return false;
20034            }
20035        }
20036
20037        final String[] packageNames = { packageName };
20038        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20039        final String[] codePaths = { ps.codePathString };
20040
20041        try {
20042            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20043                    ps.appId, ceDataInodes, codePaths, stats);
20044
20045            // For now, ignore code size of packages on system partition
20046            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20047                stats.codeSize = 0;
20048            }
20049
20050            // External clients expect these to be tracked separately
20051            stats.dataSize -= stats.cacheSize;
20052
20053        } catch (InstallerException e) {
20054            Slog.w(TAG, String.valueOf(e));
20055            return false;
20056        }
20057
20058        return true;
20059    }
20060
20061    private int getUidTargetSdkVersionLockedLPr(int uid) {
20062        Object obj = mSettings.getUserIdLPr(uid);
20063        if (obj instanceof SharedUserSetting) {
20064            final SharedUserSetting sus = (SharedUserSetting) obj;
20065            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20066            final Iterator<PackageSetting> it = sus.packages.iterator();
20067            while (it.hasNext()) {
20068                final PackageSetting ps = it.next();
20069                if (ps.pkg != null) {
20070                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20071                    if (v < vers) vers = v;
20072                }
20073            }
20074            return vers;
20075        } else if (obj instanceof PackageSetting) {
20076            final PackageSetting ps = (PackageSetting) obj;
20077            if (ps.pkg != null) {
20078                return ps.pkg.applicationInfo.targetSdkVersion;
20079            }
20080        }
20081        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20082    }
20083
20084    @Override
20085    public void addPreferredActivity(IntentFilter filter, int match,
20086            ComponentName[] set, ComponentName activity, int userId) {
20087        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20088                "Adding preferred");
20089    }
20090
20091    private void addPreferredActivityInternal(IntentFilter filter, int match,
20092            ComponentName[] set, ComponentName activity, boolean always, int userId,
20093            String opname) {
20094        // writer
20095        int callingUid = Binder.getCallingUid();
20096        enforceCrossUserPermission(callingUid, userId,
20097                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20098        if (filter.countActions() == 0) {
20099            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20100            return;
20101        }
20102        synchronized (mPackages) {
20103            if (mContext.checkCallingOrSelfPermission(
20104                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20105                    != PackageManager.PERMISSION_GRANTED) {
20106                if (getUidTargetSdkVersionLockedLPr(callingUid)
20107                        < Build.VERSION_CODES.FROYO) {
20108                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20109                            + callingUid);
20110                    return;
20111                }
20112                mContext.enforceCallingOrSelfPermission(
20113                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20114            }
20115
20116            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20117            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20118                    + userId + ":");
20119            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20120            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20121            scheduleWritePackageRestrictionsLocked(userId);
20122            postPreferredActivityChangedBroadcast(userId);
20123        }
20124    }
20125
20126    private void postPreferredActivityChangedBroadcast(int userId) {
20127        mHandler.post(() -> {
20128            final IActivityManager am = ActivityManager.getService();
20129            if (am == null) {
20130                return;
20131            }
20132
20133            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20134            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20135            try {
20136                am.broadcastIntent(null, intent, null, null,
20137                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20138                        null, false, false, userId);
20139            } catch (RemoteException e) {
20140            }
20141        });
20142    }
20143
20144    @Override
20145    public void replacePreferredActivity(IntentFilter filter, int match,
20146            ComponentName[] set, ComponentName activity, int userId) {
20147        if (filter.countActions() != 1) {
20148            throw new IllegalArgumentException(
20149                    "replacePreferredActivity expects filter to have only 1 action.");
20150        }
20151        if (filter.countDataAuthorities() != 0
20152                || filter.countDataPaths() != 0
20153                || filter.countDataSchemes() > 1
20154                || filter.countDataTypes() != 0) {
20155            throw new IllegalArgumentException(
20156                    "replacePreferredActivity expects filter to have no data authorities, " +
20157                    "paths, or types; and at most one scheme.");
20158        }
20159
20160        final int callingUid = Binder.getCallingUid();
20161        enforceCrossUserPermission(callingUid, userId,
20162                true /* requireFullPermission */, false /* checkShell */,
20163                "replace preferred activity");
20164        synchronized (mPackages) {
20165            if (mContext.checkCallingOrSelfPermission(
20166                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20167                    != PackageManager.PERMISSION_GRANTED) {
20168                if (getUidTargetSdkVersionLockedLPr(callingUid)
20169                        < Build.VERSION_CODES.FROYO) {
20170                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20171                            + Binder.getCallingUid());
20172                    return;
20173                }
20174                mContext.enforceCallingOrSelfPermission(
20175                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20176            }
20177
20178            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20179            if (pir != null) {
20180                // Get all of the existing entries that exactly match this filter.
20181                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20182                if (existing != null && existing.size() == 1) {
20183                    PreferredActivity cur = existing.get(0);
20184                    if (DEBUG_PREFERRED) {
20185                        Slog.i(TAG, "Checking replace of preferred:");
20186                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20187                        if (!cur.mPref.mAlways) {
20188                            Slog.i(TAG, "  -- CUR; not mAlways!");
20189                        } else {
20190                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20191                            Slog.i(TAG, "  -- CUR: mSet="
20192                                    + Arrays.toString(cur.mPref.mSetComponents));
20193                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20194                            Slog.i(TAG, "  -- NEW: mMatch="
20195                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20196                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20197                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20198                        }
20199                    }
20200                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20201                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20202                            && cur.mPref.sameSet(set)) {
20203                        // Setting the preferred activity to what it happens to be already
20204                        if (DEBUG_PREFERRED) {
20205                            Slog.i(TAG, "Replacing with same preferred activity "
20206                                    + cur.mPref.mShortComponent + " for user "
20207                                    + userId + ":");
20208                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20209                        }
20210                        return;
20211                    }
20212                }
20213
20214                if (existing != null) {
20215                    if (DEBUG_PREFERRED) {
20216                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20217                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20218                    }
20219                    for (int i = 0; i < existing.size(); i++) {
20220                        PreferredActivity pa = existing.get(i);
20221                        if (DEBUG_PREFERRED) {
20222                            Slog.i(TAG, "Removing existing preferred activity "
20223                                    + pa.mPref.mComponent + ":");
20224                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20225                        }
20226                        pir.removeFilter(pa);
20227                    }
20228                }
20229            }
20230            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20231                    "Replacing preferred");
20232        }
20233    }
20234
20235    @Override
20236    public void clearPackagePreferredActivities(String packageName) {
20237        final int callingUid = Binder.getCallingUid();
20238        if (getInstantAppPackageName(callingUid) != null) {
20239            return;
20240        }
20241        // writer
20242        synchronized (mPackages) {
20243            PackageParser.Package pkg = mPackages.get(packageName);
20244            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20245                if (mContext.checkCallingOrSelfPermission(
20246                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20247                        != PackageManager.PERMISSION_GRANTED) {
20248                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20249                            < Build.VERSION_CODES.FROYO) {
20250                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20251                                + callingUid);
20252                        return;
20253                    }
20254                    mContext.enforceCallingOrSelfPermission(
20255                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20256                }
20257            }
20258            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20259            if (ps != null
20260                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20261                return;
20262            }
20263            int user = UserHandle.getCallingUserId();
20264            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20265                scheduleWritePackageRestrictionsLocked(user);
20266            }
20267        }
20268    }
20269
20270    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20271    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20272        ArrayList<PreferredActivity> removed = null;
20273        boolean changed = false;
20274        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20275            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20276            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20277            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20278                continue;
20279            }
20280            Iterator<PreferredActivity> it = pir.filterIterator();
20281            while (it.hasNext()) {
20282                PreferredActivity pa = it.next();
20283                // Mark entry for removal only if it matches the package name
20284                // and the entry is of type "always".
20285                if (packageName == null ||
20286                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20287                                && pa.mPref.mAlways)) {
20288                    if (removed == null) {
20289                        removed = new ArrayList<PreferredActivity>();
20290                    }
20291                    removed.add(pa);
20292                }
20293            }
20294            if (removed != null) {
20295                for (int j=0; j<removed.size(); j++) {
20296                    PreferredActivity pa = removed.get(j);
20297                    pir.removeFilter(pa);
20298                }
20299                changed = true;
20300            }
20301        }
20302        if (changed) {
20303            postPreferredActivityChangedBroadcast(userId);
20304        }
20305        return changed;
20306    }
20307
20308    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20309    private void clearIntentFilterVerificationsLPw(int userId) {
20310        final int packageCount = mPackages.size();
20311        for (int i = 0; i < packageCount; i++) {
20312            PackageParser.Package pkg = mPackages.valueAt(i);
20313            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20314        }
20315    }
20316
20317    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20318    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20319        if (userId == UserHandle.USER_ALL) {
20320            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20321                    sUserManager.getUserIds())) {
20322                for (int oneUserId : sUserManager.getUserIds()) {
20323                    scheduleWritePackageRestrictionsLocked(oneUserId);
20324                }
20325            }
20326        } else {
20327            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20328                scheduleWritePackageRestrictionsLocked(userId);
20329            }
20330        }
20331    }
20332
20333    /** Clears state for all users, and touches intent filter verification policy */
20334    void clearDefaultBrowserIfNeeded(String packageName) {
20335        for (int oneUserId : sUserManager.getUserIds()) {
20336            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20337        }
20338    }
20339
20340    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20341        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20342        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20343            if (packageName.equals(defaultBrowserPackageName)) {
20344                setDefaultBrowserPackageName(null, userId);
20345            }
20346        }
20347    }
20348
20349    @Override
20350    public void resetApplicationPreferences(int userId) {
20351        mContext.enforceCallingOrSelfPermission(
20352                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20353        final long identity = Binder.clearCallingIdentity();
20354        // writer
20355        try {
20356            synchronized (mPackages) {
20357                clearPackagePreferredActivitiesLPw(null, userId);
20358                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20359                // TODO: We have to reset the default SMS and Phone. This requires
20360                // significant refactoring to keep all default apps in the package
20361                // manager (cleaner but more work) or have the services provide
20362                // callbacks to the package manager to request a default app reset.
20363                applyFactoryDefaultBrowserLPw(userId);
20364                clearIntentFilterVerificationsLPw(userId);
20365                primeDomainVerificationsLPw(userId);
20366                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20367                scheduleWritePackageRestrictionsLocked(userId);
20368            }
20369            resetNetworkPolicies(userId);
20370        } finally {
20371            Binder.restoreCallingIdentity(identity);
20372        }
20373    }
20374
20375    @Override
20376    public int getPreferredActivities(List<IntentFilter> outFilters,
20377            List<ComponentName> outActivities, String packageName) {
20378        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20379            return 0;
20380        }
20381        int num = 0;
20382        final int userId = UserHandle.getCallingUserId();
20383        // reader
20384        synchronized (mPackages) {
20385            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20386            if (pir != null) {
20387                final Iterator<PreferredActivity> it = pir.filterIterator();
20388                while (it.hasNext()) {
20389                    final PreferredActivity pa = it.next();
20390                    if (packageName == null
20391                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20392                                    && pa.mPref.mAlways)) {
20393                        if (outFilters != null) {
20394                            outFilters.add(new IntentFilter(pa));
20395                        }
20396                        if (outActivities != null) {
20397                            outActivities.add(pa.mPref.mComponent);
20398                        }
20399                    }
20400                }
20401            }
20402        }
20403
20404        return num;
20405    }
20406
20407    @Override
20408    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20409            int userId) {
20410        int callingUid = Binder.getCallingUid();
20411        if (callingUid != Process.SYSTEM_UID) {
20412            throw new SecurityException(
20413                    "addPersistentPreferredActivity can only be run by the system");
20414        }
20415        if (filter.countActions() == 0) {
20416            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20417            return;
20418        }
20419        synchronized (mPackages) {
20420            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20421                    ":");
20422            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20423            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20424                    new PersistentPreferredActivity(filter, activity));
20425            scheduleWritePackageRestrictionsLocked(userId);
20426            postPreferredActivityChangedBroadcast(userId);
20427        }
20428    }
20429
20430    @Override
20431    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20432        int callingUid = Binder.getCallingUid();
20433        if (callingUid != Process.SYSTEM_UID) {
20434            throw new SecurityException(
20435                    "clearPackagePersistentPreferredActivities can only be run by the system");
20436        }
20437        ArrayList<PersistentPreferredActivity> removed = null;
20438        boolean changed = false;
20439        synchronized (mPackages) {
20440            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20441                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20442                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20443                        .valueAt(i);
20444                if (userId != thisUserId) {
20445                    continue;
20446                }
20447                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20448                while (it.hasNext()) {
20449                    PersistentPreferredActivity ppa = it.next();
20450                    // Mark entry for removal only if it matches the package name.
20451                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20452                        if (removed == null) {
20453                            removed = new ArrayList<PersistentPreferredActivity>();
20454                        }
20455                        removed.add(ppa);
20456                    }
20457                }
20458                if (removed != null) {
20459                    for (int j=0; j<removed.size(); j++) {
20460                        PersistentPreferredActivity ppa = removed.get(j);
20461                        ppir.removeFilter(ppa);
20462                    }
20463                    changed = true;
20464                }
20465            }
20466
20467            if (changed) {
20468                scheduleWritePackageRestrictionsLocked(userId);
20469                postPreferredActivityChangedBroadcast(userId);
20470            }
20471        }
20472    }
20473
20474    /**
20475     * Common machinery for picking apart a restored XML blob and passing
20476     * it to a caller-supplied functor to be applied to the running system.
20477     */
20478    private void restoreFromXml(XmlPullParser parser, int userId,
20479            String expectedStartTag, BlobXmlRestorer functor)
20480            throws IOException, XmlPullParserException {
20481        int type;
20482        while ((type = parser.next()) != XmlPullParser.START_TAG
20483                && type != XmlPullParser.END_DOCUMENT) {
20484        }
20485        if (type != XmlPullParser.START_TAG) {
20486            // oops didn't find a start tag?!
20487            if (DEBUG_BACKUP) {
20488                Slog.e(TAG, "Didn't find start tag during restore");
20489            }
20490            return;
20491        }
20492Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20493        // this is supposed to be TAG_PREFERRED_BACKUP
20494        if (!expectedStartTag.equals(parser.getName())) {
20495            if (DEBUG_BACKUP) {
20496                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20497            }
20498            return;
20499        }
20500
20501        // skip interfering stuff, then we're aligned with the backing implementation
20502        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20503Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20504        functor.apply(parser, userId);
20505    }
20506
20507    private interface BlobXmlRestorer {
20508        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20509    }
20510
20511    /**
20512     * Non-Binder method, support for the backup/restore mechanism: write the
20513     * full set of preferred activities in its canonical XML format.  Returns the
20514     * XML output as a byte array, or null if there is none.
20515     */
20516    @Override
20517    public byte[] getPreferredActivityBackup(int userId) {
20518        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20519            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20520        }
20521
20522        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20523        try {
20524            final XmlSerializer serializer = new FastXmlSerializer();
20525            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20526            serializer.startDocument(null, true);
20527            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20528
20529            synchronized (mPackages) {
20530                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20531            }
20532
20533            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20534            serializer.endDocument();
20535            serializer.flush();
20536        } catch (Exception e) {
20537            if (DEBUG_BACKUP) {
20538                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20539            }
20540            return null;
20541        }
20542
20543        return dataStream.toByteArray();
20544    }
20545
20546    @Override
20547    public void restorePreferredActivities(byte[] backup, int userId) {
20548        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20549            throw new SecurityException("Only the system may call restorePreferredActivities()");
20550        }
20551
20552        try {
20553            final XmlPullParser parser = Xml.newPullParser();
20554            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20555            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20556                    new BlobXmlRestorer() {
20557                        @Override
20558                        public void apply(XmlPullParser parser, int userId)
20559                                throws XmlPullParserException, IOException {
20560                            synchronized (mPackages) {
20561                                mSettings.readPreferredActivitiesLPw(parser, userId);
20562                            }
20563                        }
20564                    } );
20565        } catch (Exception e) {
20566            if (DEBUG_BACKUP) {
20567                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20568            }
20569        }
20570    }
20571
20572    /**
20573     * Non-Binder method, support for the backup/restore mechanism: write the
20574     * default browser (etc) settings in its canonical XML format.  Returns the default
20575     * browser XML representation as a byte array, or null if there is none.
20576     */
20577    @Override
20578    public byte[] getDefaultAppsBackup(int userId) {
20579        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20580            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20581        }
20582
20583        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20584        try {
20585            final XmlSerializer serializer = new FastXmlSerializer();
20586            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20587            serializer.startDocument(null, true);
20588            serializer.startTag(null, TAG_DEFAULT_APPS);
20589
20590            synchronized (mPackages) {
20591                mSettings.writeDefaultAppsLPr(serializer, userId);
20592            }
20593
20594            serializer.endTag(null, TAG_DEFAULT_APPS);
20595            serializer.endDocument();
20596            serializer.flush();
20597        } catch (Exception e) {
20598            if (DEBUG_BACKUP) {
20599                Slog.e(TAG, "Unable to write default apps for backup", e);
20600            }
20601            return null;
20602        }
20603
20604        return dataStream.toByteArray();
20605    }
20606
20607    @Override
20608    public void restoreDefaultApps(byte[] backup, int userId) {
20609        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20610            throw new SecurityException("Only the system may call restoreDefaultApps()");
20611        }
20612
20613        try {
20614            final XmlPullParser parser = Xml.newPullParser();
20615            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20616            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20617                    new BlobXmlRestorer() {
20618                        @Override
20619                        public void apply(XmlPullParser parser, int userId)
20620                                throws XmlPullParserException, IOException {
20621                            synchronized (mPackages) {
20622                                mSettings.readDefaultAppsLPw(parser, userId);
20623                            }
20624                        }
20625                    } );
20626        } catch (Exception e) {
20627            if (DEBUG_BACKUP) {
20628                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20629            }
20630        }
20631    }
20632
20633    @Override
20634    public byte[] getIntentFilterVerificationBackup(int userId) {
20635        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20636            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20637        }
20638
20639        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20640        try {
20641            final XmlSerializer serializer = new FastXmlSerializer();
20642            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20643            serializer.startDocument(null, true);
20644            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20645
20646            synchronized (mPackages) {
20647                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20648            }
20649
20650            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20651            serializer.endDocument();
20652            serializer.flush();
20653        } catch (Exception e) {
20654            if (DEBUG_BACKUP) {
20655                Slog.e(TAG, "Unable to write default apps for backup", e);
20656            }
20657            return null;
20658        }
20659
20660        return dataStream.toByteArray();
20661    }
20662
20663    @Override
20664    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20665        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20666            throw new SecurityException("Only the system may call restorePreferredActivities()");
20667        }
20668
20669        try {
20670            final XmlPullParser parser = Xml.newPullParser();
20671            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20672            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20673                    new BlobXmlRestorer() {
20674                        @Override
20675                        public void apply(XmlPullParser parser, int userId)
20676                                throws XmlPullParserException, IOException {
20677                            synchronized (mPackages) {
20678                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20679                                mSettings.writeLPr();
20680                            }
20681                        }
20682                    } );
20683        } catch (Exception e) {
20684            if (DEBUG_BACKUP) {
20685                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20686            }
20687        }
20688    }
20689
20690    @Override
20691    public byte[] getPermissionGrantBackup(int userId) {
20692        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20693            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20694        }
20695
20696        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20697        try {
20698            final XmlSerializer serializer = new FastXmlSerializer();
20699            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20700            serializer.startDocument(null, true);
20701            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20702
20703            synchronized (mPackages) {
20704                serializeRuntimePermissionGrantsLPr(serializer, userId);
20705            }
20706
20707            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20708            serializer.endDocument();
20709            serializer.flush();
20710        } catch (Exception e) {
20711            if (DEBUG_BACKUP) {
20712                Slog.e(TAG, "Unable to write default apps for backup", e);
20713            }
20714            return null;
20715        }
20716
20717        return dataStream.toByteArray();
20718    }
20719
20720    @Override
20721    public void restorePermissionGrants(byte[] backup, int userId) {
20722        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20723            throw new SecurityException("Only the system may call restorePermissionGrants()");
20724        }
20725
20726        try {
20727            final XmlPullParser parser = Xml.newPullParser();
20728            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20729            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20730                    new BlobXmlRestorer() {
20731                        @Override
20732                        public void apply(XmlPullParser parser, int userId)
20733                                throws XmlPullParserException, IOException {
20734                            synchronized (mPackages) {
20735                                processRestoredPermissionGrantsLPr(parser, userId);
20736                            }
20737                        }
20738                    } );
20739        } catch (Exception e) {
20740            if (DEBUG_BACKUP) {
20741                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20742            }
20743        }
20744    }
20745
20746    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20747            throws IOException {
20748        serializer.startTag(null, TAG_ALL_GRANTS);
20749
20750        final int N = mSettings.mPackages.size();
20751        for (int i = 0; i < N; i++) {
20752            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20753            boolean pkgGrantsKnown = false;
20754
20755            PermissionsState packagePerms = ps.getPermissionsState();
20756
20757            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20758                final int grantFlags = state.getFlags();
20759                // only look at grants that are not system/policy fixed
20760                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20761                    final boolean isGranted = state.isGranted();
20762                    // And only back up the user-twiddled state bits
20763                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20764                        final String packageName = mSettings.mPackages.keyAt(i);
20765                        if (!pkgGrantsKnown) {
20766                            serializer.startTag(null, TAG_GRANT);
20767                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20768                            pkgGrantsKnown = true;
20769                        }
20770
20771                        final boolean userSet =
20772                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20773                        final boolean userFixed =
20774                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20775                        final boolean revoke =
20776                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20777
20778                        serializer.startTag(null, TAG_PERMISSION);
20779                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20780                        if (isGranted) {
20781                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20782                        }
20783                        if (userSet) {
20784                            serializer.attribute(null, ATTR_USER_SET, "true");
20785                        }
20786                        if (userFixed) {
20787                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20788                        }
20789                        if (revoke) {
20790                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20791                        }
20792                        serializer.endTag(null, TAG_PERMISSION);
20793                    }
20794                }
20795            }
20796
20797            if (pkgGrantsKnown) {
20798                serializer.endTag(null, TAG_GRANT);
20799            }
20800        }
20801
20802        serializer.endTag(null, TAG_ALL_GRANTS);
20803    }
20804
20805    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20806            throws XmlPullParserException, IOException {
20807        String pkgName = null;
20808        int outerDepth = parser.getDepth();
20809        int type;
20810        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20811                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20812            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20813                continue;
20814            }
20815
20816            final String tagName = parser.getName();
20817            if (tagName.equals(TAG_GRANT)) {
20818                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20819                if (DEBUG_BACKUP) {
20820                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20821                }
20822            } else if (tagName.equals(TAG_PERMISSION)) {
20823
20824                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20825                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20826
20827                int newFlagSet = 0;
20828                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20829                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20830                }
20831                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20832                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20833                }
20834                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20835                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20836                }
20837                if (DEBUG_BACKUP) {
20838                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20839                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20840                }
20841                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20842                if (ps != null) {
20843                    // Already installed so we apply the grant immediately
20844                    if (DEBUG_BACKUP) {
20845                        Slog.v(TAG, "        + already installed; applying");
20846                    }
20847                    PermissionsState perms = ps.getPermissionsState();
20848                    BasePermission bp = mSettings.mPermissions.get(permName);
20849                    if (bp != null) {
20850                        if (isGranted) {
20851                            perms.grantRuntimePermission(bp, userId);
20852                        }
20853                        if (newFlagSet != 0) {
20854                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20855                        }
20856                    }
20857                } else {
20858                    // Need to wait for post-restore install to apply the grant
20859                    if (DEBUG_BACKUP) {
20860                        Slog.v(TAG, "        - not yet installed; saving for later");
20861                    }
20862                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20863                            isGranted, newFlagSet, userId);
20864                }
20865            } else {
20866                PackageManagerService.reportSettingsProblem(Log.WARN,
20867                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20868                XmlUtils.skipCurrentTag(parser);
20869            }
20870        }
20871
20872        scheduleWriteSettingsLocked();
20873        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20874    }
20875
20876    @Override
20877    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20878            int sourceUserId, int targetUserId, int flags) {
20879        mContext.enforceCallingOrSelfPermission(
20880                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20881        int callingUid = Binder.getCallingUid();
20882        enforceOwnerRights(ownerPackage, callingUid);
20883        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20884        if (intentFilter.countActions() == 0) {
20885            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20886            return;
20887        }
20888        synchronized (mPackages) {
20889            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20890                    ownerPackage, targetUserId, flags);
20891            CrossProfileIntentResolver resolver =
20892                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20893            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20894            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20895            if (existing != null) {
20896                int size = existing.size();
20897                for (int i = 0; i < size; i++) {
20898                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20899                        return;
20900                    }
20901                }
20902            }
20903            resolver.addFilter(newFilter);
20904            scheduleWritePackageRestrictionsLocked(sourceUserId);
20905        }
20906    }
20907
20908    @Override
20909    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20910        mContext.enforceCallingOrSelfPermission(
20911                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20912        final int callingUid = Binder.getCallingUid();
20913        enforceOwnerRights(ownerPackage, callingUid);
20914        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20915        synchronized (mPackages) {
20916            CrossProfileIntentResolver resolver =
20917                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20918            ArraySet<CrossProfileIntentFilter> set =
20919                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20920            for (CrossProfileIntentFilter filter : set) {
20921                if (filter.getOwnerPackage().equals(ownerPackage)) {
20922                    resolver.removeFilter(filter);
20923                }
20924            }
20925            scheduleWritePackageRestrictionsLocked(sourceUserId);
20926        }
20927    }
20928
20929    // Enforcing that callingUid is owning pkg on userId
20930    private void enforceOwnerRights(String pkg, int callingUid) {
20931        // The system owns everything.
20932        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20933            return;
20934        }
20935        final int callingUserId = UserHandle.getUserId(callingUid);
20936        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20937        if (pi == null) {
20938            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20939                    + callingUserId);
20940        }
20941        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20942            throw new SecurityException("Calling uid " + callingUid
20943                    + " does not own package " + pkg);
20944        }
20945    }
20946
20947    @Override
20948    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20949        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20950            return null;
20951        }
20952        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20953    }
20954
20955    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20956        UserManagerService ums = UserManagerService.getInstance();
20957        if (ums != null) {
20958            final UserInfo parent = ums.getProfileParent(userId);
20959            final int launcherUid = (parent != null) ? parent.id : userId;
20960            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20961            if (launcherComponent != null) {
20962                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20963                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20964                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20965                        .setPackage(launcherComponent.getPackageName());
20966                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20967            }
20968        }
20969    }
20970
20971    /**
20972     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20973     * then reports the most likely home activity or null if there are more than one.
20974     */
20975    private ComponentName getDefaultHomeActivity(int userId) {
20976        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20977        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20978        if (cn != null) {
20979            return cn;
20980        }
20981
20982        // Find the launcher with the highest priority and return that component if there are no
20983        // other home activity with the same priority.
20984        int lastPriority = Integer.MIN_VALUE;
20985        ComponentName lastComponent = null;
20986        final int size = allHomeCandidates.size();
20987        for (int i = 0; i < size; i++) {
20988            final ResolveInfo ri = allHomeCandidates.get(i);
20989            if (ri.priority > lastPriority) {
20990                lastComponent = ri.activityInfo.getComponentName();
20991                lastPriority = ri.priority;
20992            } else if (ri.priority == lastPriority) {
20993                // Two components found with same priority.
20994                lastComponent = null;
20995            }
20996        }
20997        return lastComponent;
20998    }
20999
21000    private Intent getHomeIntent() {
21001        Intent intent = new Intent(Intent.ACTION_MAIN);
21002        intent.addCategory(Intent.CATEGORY_HOME);
21003        intent.addCategory(Intent.CATEGORY_DEFAULT);
21004        return intent;
21005    }
21006
21007    private IntentFilter getHomeFilter() {
21008        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21009        filter.addCategory(Intent.CATEGORY_HOME);
21010        filter.addCategory(Intent.CATEGORY_DEFAULT);
21011        return filter;
21012    }
21013
21014    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21015            int userId) {
21016        Intent intent  = getHomeIntent();
21017        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21018                PackageManager.GET_META_DATA, userId);
21019        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21020                true, false, false, userId);
21021
21022        allHomeCandidates.clear();
21023        if (list != null) {
21024            for (ResolveInfo ri : list) {
21025                allHomeCandidates.add(ri);
21026            }
21027        }
21028        return (preferred == null || preferred.activityInfo == null)
21029                ? null
21030                : new ComponentName(preferred.activityInfo.packageName,
21031                        preferred.activityInfo.name);
21032    }
21033
21034    @Override
21035    public void setHomeActivity(ComponentName comp, int userId) {
21036        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21037            return;
21038        }
21039        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21040        getHomeActivitiesAsUser(homeActivities, userId);
21041
21042        boolean found = false;
21043
21044        final int size = homeActivities.size();
21045        final ComponentName[] set = new ComponentName[size];
21046        for (int i = 0; i < size; i++) {
21047            final ResolveInfo candidate = homeActivities.get(i);
21048            final ActivityInfo info = candidate.activityInfo;
21049            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21050            set[i] = activityName;
21051            if (!found && activityName.equals(comp)) {
21052                found = true;
21053            }
21054        }
21055        if (!found) {
21056            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21057                    + userId);
21058        }
21059        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21060                set, comp, userId);
21061    }
21062
21063    private @Nullable String getSetupWizardPackageName() {
21064        final Intent intent = new Intent(Intent.ACTION_MAIN);
21065        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21066
21067        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21068                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21069                        | MATCH_DISABLED_COMPONENTS,
21070                UserHandle.myUserId());
21071        if (matches.size() == 1) {
21072            return matches.get(0).getComponentInfo().packageName;
21073        } else {
21074            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21075                    + ": matches=" + matches);
21076            return null;
21077        }
21078    }
21079
21080    private @Nullable String getStorageManagerPackageName() {
21081        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21082
21083        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21084                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21085                        | MATCH_DISABLED_COMPONENTS,
21086                UserHandle.myUserId());
21087        if (matches.size() == 1) {
21088            return matches.get(0).getComponentInfo().packageName;
21089        } else {
21090            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21091                    + matches.size() + ": matches=" + matches);
21092            return null;
21093        }
21094    }
21095
21096    @Override
21097    public void setApplicationEnabledSetting(String appPackageName,
21098            int newState, int flags, int userId, String callingPackage) {
21099        if (!sUserManager.exists(userId)) return;
21100        if (callingPackage == null) {
21101            callingPackage = Integer.toString(Binder.getCallingUid());
21102        }
21103        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21104    }
21105
21106    @Override
21107    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21108        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21109        synchronized (mPackages) {
21110            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21111            if (pkgSetting != null) {
21112                pkgSetting.setUpdateAvailable(updateAvailable);
21113            }
21114        }
21115    }
21116
21117    @Override
21118    public void setComponentEnabledSetting(ComponentName componentName,
21119            int newState, int flags, int userId) {
21120        if (!sUserManager.exists(userId)) return;
21121        setEnabledSetting(componentName.getPackageName(),
21122                componentName.getClassName(), newState, flags, userId, null);
21123    }
21124
21125    private void setEnabledSetting(final String packageName, String className, int newState,
21126            final int flags, int userId, String callingPackage) {
21127        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21128              || newState == COMPONENT_ENABLED_STATE_ENABLED
21129              || newState == COMPONENT_ENABLED_STATE_DISABLED
21130              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21131              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21132            throw new IllegalArgumentException("Invalid new component state: "
21133                    + newState);
21134        }
21135        PackageSetting pkgSetting;
21136        final int callingUid = Binder.getCallingUid();
21137        final int permission;
21138        if (callingUid == Process.SYSTEM_UID) {
21139            permission = PackageManager.PERMISSION_GRANTED;
21140        } else {
21141            permission = mContext.checkCallingOrSelfPermission(
21142                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21143        }
21144        enforceCrossUserPermission(callingUid, userId,
21145                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21146        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21147        boolean sendNow = false;
21148        boolean isApp = (className == null);
21149        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21150        String componentName = isApp ? packageName : className;
21151        int packageUid = -1;
21152        ArrayList<String> components;
21153
21154        // reader
21155        synchronized (mPackages) {
21156            pkgSetting = mSettings.mPackages.get(packageName);
21157            if (pkgSetting == null) {
21158                if (!isCallerInstantApp) {
21159                    if (className == null) {
21160                        throw new IllegalArgumentException("Unknown package: " + packageName);
21161                    }
21162                    throw new IllegalArgumentException(
21163                            "Unknown component: " + packageName + "/" + className);
21164                } else {
21165                    // throw SecurityException to prevent leaking package information
21166                    throw new SecurityException(
21167                            "Attempt to change component state; "
21168                            + "pid=" + Binder.getCallingPid()
21169                            + ", uid=" + callingUid
21170                            + (className == null
21171                                    ? ", package=" + packageName
21172                                    : ", component=" + packageName + "/" + className));
21173                }
21174            }
21175        }
21176
21177        // Limit who can change which apps
21178        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21179            // Don't allow apps that don't have permission to modify other apps
21180            if (!allowedByPermission
21181                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21182                throw new SecurityException(
21183                        "Attempt to change component state; "
21184                        + "pid=" + Binder.getCallingPid()
21185                        + ", uid=" + callingUid
21186                        + (className == null
21187                                ? ", package=" + packageName
21188                                : ", component=" + packageName + "/" + className));
21189            }
21190            // Don't allow changing protected packages.
21191            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21192                throw new SecurityException("Cannot disable a protected package: " + packageName);
21193            }
21194        }
21195
21196        synchronized (mPackages) {
21197            if (callingUid == Process.SHELL_UID
21198                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21199                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21200                // unless it is a test package.
21201                int oldState = pkgSetting.getEnabled(userId);
21202                if (className == null
21203                    &&
21204                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21205                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21206                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21207                    &&
21208                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21209                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21210                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21211                    // ok
21212                } else {
21213                    throw new SecurityException(
21214                            "Shell cannot change component state for " + packageName + "/"
21215                            + className + " to " + newState);
21216                }
21217            }
21218            if (className == null) {
21219                // We're dealing with an application/package level state change
21220                if (pkgSetting.getEnabled(userId) == newState) {
21221                    // Nothing to do
21222                    return;
21223                }
21224                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21225                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21226                    // Don't care about who enables an app.
21227                    callingPackage = null;
21228                }
21229                pkgSetting.setEnabled(newState, userId, callingPackage);
21230                // pkgSetting.pkg.mSetEnabled = newState;
21231            } else {
21232                // We're dealing with a component level state change
21233                // First, verify that this is a valid class name.
21234                PackageParser.Package pkg = pkgSetting.pkg;
21235                if (pkg == null || !pkg.hasComponentClassName(className)) {
21236                    if (pkg != null &&
21237                            pkg.applicationInfo.targetSdkVersion >=
21238                                    Build.VERSION_CODES.JELLY_BEAN) {
21239                        throw new IllegalArgumentException("Component class " + className
21240                                + " does not exist in " + packageName);
21241                    } else {
21242                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21243                                + className + " does not exist in " + packageName);
21244                    }
21245                }
21246                switch (newState) {
21247                case COMPONENT_ENABLED_STATE_ENABLED:
21248                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21249                        return;
21250                    }
21251                    break;
21252                case COMPONENT_ENABLED_STATE_DISABLED:
21253                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21254                        return;
21255                    }
21256                    break;
21257                case COMPONENT_ENABLED_STATE_DEFAULT:
21258                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21259                        return;
21260                    }
21261                    break;
21262                default:
21263                    Slog.e(TAG, "Invalid new component state: " + newState);
21264                    return;
21265                }
21266            }
21267            scheduleWritePackageRestrictionsLocked(userId);
21268            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21269            final long callingId = Binder.clearCallingIdentity();
21270            try {
21271                updateInstantAppInstallerLocked(packageName);
21272            } finally {
21273                Binder.restoreCallingIdentity(callingId);
21274            }
21275            components = mPendingBroadcasts.get(userId, packageName);
21276            final boolean newPackage = components == null;
21277            if (newPackage) {
21278                components = new ArrayList<String>();
21279            }
21280            if (!components.contains(componentName)) {
21281                components.add(componentName);
21282            }
21283            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21284                sendNow = true;
21285                // Purge entry from pending broadcast list if another one exists already
21286                // since we are sending one right away.
21287                mPendingBroadcasts.remove(userId, packageName);
21288            } else {
21289                if (newPackage) {
21290                    mPendingBroadcasts.put(userId, packageName, components);
21291                }
21292                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21293                    // Schedule a message
21294                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21295                }
21296            }
21297        }
21298
21299        long callingId = Binder.clearCallingIdentity();
21300        try {
21301            if (sendNow) {
21302                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21303                sendPackageChangedBroadcast(packageName,
21304                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21305            }
21306        } finally {
21307            Binder.restoreCallingIdentity(callingId);
21308        }
21309    }
21310
21311    @Override
21312    public void flushPackageRestrictionsAsUser(int userId) {
21313        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21314            return;
21315        }
21316        if (!sUserManager.exists(userId)) {
21317            return;
21318        }
21319        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21320                false /* checkShell */, "flushPackageRestrictions");
21321        synchronized (mPackages) {
21322            mSettings.writePackageRestrictionsLPr(userId);
21323            mDirtyUsers.remove(userId);
21324            if (mDirtyUsers.isEmpty()) {
21325                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21326            }
21327        }
21328    }
21329
21330    private void sendPackageChangedBroadcast(String packageName,
21331            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21332        if (DEBUG_INSTALL)
21333            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21334                    + componentNames);
21335        Bundle extras = new Bundle(4);
21336        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21337        String nameList[] = new String[componentNames.size()];
21338        componentNames.toArray(nameList);
21339        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21340        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21341        extras.putInt(Intent.EXTRA_UID, packageUid);
21342        // If this is not reporting a change of the overall package, then only send it
21343        // to registered receivers.  We don't want to launch a swath of apps for every
21344        // little component state change.
21345        final int flags = !componentNames.contains(packageName)
21346                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21347        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21348                new int[] {UserHandle.getUserId(packageUid)});
21349    }
21350
21351    @Override
21352    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21353        if (!sUserManager.exists(userId)) return;
21354        final int callingUid = Binder.getCallingUid();
21355        if (getInstantAppPackageName(callingUid) != null) {
21356            return;
21357        }
21358        final int permission = mContext.checkCallingOrSelfPermission(
21359                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21360        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21361        enforceCrossUserPermission(callingUid, userId,
21362                true /* requireFullPermission */, true /* checkShell */, "stop package");
21363        // writer
21364        synchronized (mPackages) {
21365            final PackageSetting ps = mSettings.mPackages.get(packageName);
21366            if (!filterAppAccessLPr(ps, callingUid, userId)
21367                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21368                            allowedByPermission, callingUid, userId)) {
21369                scheduleWritePackageRestrictionsLocked(userId);
21370            }
21371        }
21372    }
21373
21374    @Override
21375    public String getInstallerPackageName(String packageName) {
21376        final int callingUid = Binder.getCallingUid();
21377        if (getInstantAppPackageName(callingUid) != null) {
21378            return null;
21379        }
21380        // reader
21381        synchronized (mPackages) {
21382            final PackageSetting ps = mSettings.mPackages.get(packageName);
21383            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21384                return null;
21385            }
21386            return mSettings.getInstallerPackageNameLPr(packageName);
21387        }
21388    }
21389
21390    public boolean isOrphaned(String packageName) {
21391        // reader
21392        synchronized (mPackages) {
21393            return mSettings.isOrphaned(packageName);
21394        }
21395    }
21396
21397    @Override
21398    public int getApplicationEnabledSetting(String packageName, int userId) {
21399        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21400        int callingUid = Binder.getCallingUid();
21401        enforceCrossUserPermission(callingUid, userId,
21402                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21403        // reader
21404        synchronized (mPackages) {
21405            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21406                return COMPONENT_ENABLED_STATE_DISABLED;
21407            }
21408            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21409        }
21410    }
21411
21412    @Override
21413    public int getComponentEnabledSetting(ComponentName component, int userId) {
21414        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21415        int callingUid = Binder.getCallingUid();
21416        enforceCrossUserPermission(callingUid, userId,
21417                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21418        synchronized (mPackages) {
21419            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21420                    component, TYPE_UNKNOWN, userId)) {
21421                return COMPONENT_ENABLED_STATE_DISABLED;
21422            }
21423            return mSettings.getComponentEnabledSettingLPr(component, userId);
21424        }
21425    }
21426
21427    @Override
21428    public void enterSafeMode() {
21429        enforceSystemOrRoot("Only the system can request entering safe mode");
21430
21431        if (!mSystemReady) {
21432            mSafeMode = true;
21433        }
21434    }
21435
21436    @Override
21437    public void systemReady() {
21438        enforceSystemOrRoot("Only the system can claim the system is ready");
21439
21440        mSystemReady = true;
21441        final ContentResolver resolver = mContext.getContentResolver();
21442        ContentObserver co = new ContentObserver(mHandler) {
21443            @Override
21444            public void onChange(boolean selfChange) {
21445                mEphemeralAppsDisabled =
21446                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21447                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21448            }
21449        };
21450        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21451                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21452                false, co, UserHandle.USER_SYSTEM);
21453        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21454                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21455        co.onChange(true);
21456
21457        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21458        // disabled after already being started.
21459        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21460                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21461
21462        // Read the compatibilty setting when the system is ready.
21463        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21464                mContext.getContentResolver(),
21465                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21466        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21467        if (DEBUG_SETTINGS) {
21468            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21469        }
21470
21471        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21472
21473        synchronized (mPackages) {
21474            // Verify that all of the preferred activity components actually
21475            // exist.  It is possible for applications to be updated and at
21476            // that point remove a previously declared activity component that
21477            // had been set as a preferred activity.  We try to clean this up
21478            // the next time we encounter that preferred activity, but it is
21479            // possible for the user flow to never be able to return to that
21480            // situation so here we do a sanity check to make sure we haven't
21481            // left any junk around.
21482            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21483            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21484                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21485                removed.clear();
21486                for (PreferredActivity pa : pir.filterSet()) {
21487                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21488                        removed.add(pa);
21489                    }
21490                }
21491                if (removed.size() > 0) {
21492                    for (int r=0; r<removed.size(); r++) {
21493                        PreferredActivity pa = removed.get(r);
21494                        Slog.w(TAG, "Removing dangling preferred activity: "
21495                                + pa.mPref.mComponent);
21496                        pir.removeFilter(pa);
21497                    }
21498                    mSettings.writePackageRestrictionsLPr(
21499                            mSettings.mPreferredActivities.keyAt(i));
21500                }
21501            }
21502
21503            for (int userId : UserManagerService.getInstance().getUserIds()) {
21504                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21505                    grantPermissionsUserIds = ArrayUtils.appendInt(
21506                            grantPermissionsUserIds, userId);
21507                }
21508            }
21509        }
21510        sUserManager.systemReady();
21511
21512        // If we upgraded grant all default permissions before kicking off.
21513        for (int userId : grantPermissionsUserIds) {
21514            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21515        }
21516
21517        // If we did not grant default permissions, we preload from this the
21518        // default permission exceptions lazily to ensure we don't hit the
21519        // disk on a new user creation.
21520        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21521            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21522        }
21523
21524        // Kick off any messages waiting for system ready
21525        if (mPostSystemReadyMessages != null) {
21526            for (Message msg : mPostSystemReadyMessages) {
21527                msg.sendToTarget();
21528            }
21529            mPostSystemReadyMessages = null;
21530        }
21531
21532        // Watch for external volumes that come and go over time
21533        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21534        storage.registerListener(mStorageListener);
21535
21536        mInstallerService.systemReady();
21537        mPackageDexOptimizer.systemReady();
21538
21539        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21540                StorageManagerInternal.class);
21541        StorageManagerInternal.addExternalStoragePolicy(
21542                new StorageManagerInternal.ExternalStorageMountPolicy() {
21543            @Override
21544            public int getMountMode(int uid, String packageName) {
21545                if (Process.isIsolated(uid)) {
21546                    return Zygote.MOUNT_EXTERNAL_NONE;
21547                }
21548                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21549                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21550                }
21551                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21552                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21553                }
21554                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21555                    return Zygote.MOUNT_EXTERNAL_READ;
21556                }
21557                return Zygote.MOUNT_EXTERNAL_WRITE;
21558            }
21559
21560            @Override
21561            public boolean hasExternalStorage(int uid, String packageName) {
21562                return true;
21563            }
21564        });
21565
21566        // Now that we're mostly running, clean up stale users and apps
21567        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21568        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21569
21570        if (mPrivappPermissionsViolations != null) {
21571            Slog.wtf(TAG,"Signature|privileged permissions not in "
21572                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21573            mPrivappPermissionsViolations = null;
21574        }
21575    }
21576
21577    public void waitForAppDataPrepared() {
21578        if (mPrepareAppDataFuture == null) {
21579            return;
21580        }
21581        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21582        mPrepareAppDataFuture = null;
21583    }
21584
21585    @Override
21586    public boolean isSafeMode() {
21587        // allow instant applications
21588        return mSafeMode;
21589    }
21590
21591    @Override
21592    public boolean hasSystemUidErrors() {
21593        // allow instant applications
21594        return mHasSystemUidErrors;
21595    }
21596
21597    static String arrayToString(int[] array) {
21598        StringBuffer buf = new StringBuffer(128);
21599        buf.append('[');
21600        if (array != null) {
21601            for (int i=0; i<array.length; i++) {
21602                if (i > 0) buf.append(", ");
21603                buf.append(array[i]);
21604            }
21605        }
21606        buf.append(']');
21607        return buf.toString();
21608    }
21609
21610    static class DumpState {
21611        public static final int DUMP_LIBS = 1 << 0;
21612        public static final int DUMP_FEATURES = 1 << 1;
21613        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21614        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21615        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21616        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21617        public static final int DUMP_PERMISSIONS = 1 << 6;
21618        public static final int DUMP_PACKAGES = 1 << 7;
21619        public static final int DUMP_SHARED_USERS = 1 << 8;
21620        public static final int DUMP_MESSAGES = 1 << 9;
21621        public static final int DUMP_PROVIDERS = 1 << 10;
21622        public static final int DUMP_VERIFIERS = 1 << 11;
21623        public static final int DUMP_PREFERRED = 1 << 12;
21624        public static final int DUMP_PREFERRED_XML = 1 << 13;
21625        public static final int DUMP_KEYSETS = 1 << 14;
21626        public static final int DUMP_VERSION = 1 << 15;
21627        public static final int DUMP_INSTALLS = 1 << 16;
21628        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21629        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21630        public static final int DUMP_FROZEN = 1 << 19;
21631        public static final int DUMP_DEXOPT = 1 << 20;
21632        public static final int DUMP_COMPILER_STATS = 1 << 21;
21633        public static final int DUMP_CHANGES = 1 << 22;
21634
21635        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21636
21637        private int mTypes;
21638
21639        private int mOptions;
21640
21641        private boolean mTitlePrinted;
21642
21643        private SharedUserSetting mSharedUser;
21644
21645        public boolean isDumping(int type) {
21646            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21647                return true;
21648            }
21649
21650            return (mTypes & type) != 0;
21651        }
21652
21653        public void setDump(int type) {
21654            mTypes |= type;
21655        }
21656
21657        public boolean isOptionEnabled(int option) {
21658            return (mOptions & option) != 0;
21659        }
21660
21661        public void setOptionEnabled(int option) {
21662            mOptions |= option;
21663        }
21664
21665        public boolean onTitlePrinted() {
21666            final boolean printed = mTitlePrinted;
21667            mTitlePrinted = true;
21668            return printed;
21669        }
21670
21671        public boolean getTitlePrinted() {
21672            return mTitlePrinted;
21673        }
21674
21675        public void setTitlePrinted(boolean enabled) {
21676            mTitlePrinted = enabled;
21677        }
21678
21679        public SharedUserSetting getSharedUser() {
21680            return mSharedUser;
21681        }
21682
21683        public void setSharedUser(SharedUserSetting user) {
21684            mSharedUser = user;
21685        }
21686    }
21687
21688    @Override
21689    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21690            FileDescriptor err, String[] args, ShellCallback callback,
21691            ResultReceiver resultReceiver) {
21692        (new PackageManagerShellCommand(this)).exec(
21693                this, in, out, err, args, callback, resultReceiver);
21694    }
21695
21696    @Override
21697    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21698        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21699
21700        DumpState dumpState = new DumpState();
21701        boolean fullPreferred = false;
21702        boolean checkin = false;
21703
21704        String packageName = null;
21705        ArraySet<String> permissionNames = null;
21706
21707        int opti = 0;
21708        while (opti < args.length) {
21709            String opt = args[opti];
21710            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21711                break;
21712            }
21713            opti++;
21714
21715            if ("-a".equals(opt)) {
21716                // Right now we only know how to print all.
21717            } else if ("-h".equals(opt)) {
21718                pw.println("Package manager dump options:");
21719                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21720                pw.println("    --checkin: dump for a checkin");
21721                pw.println("    -f: print details of intent filters");
21722                pw.println("    -h: print this help");
21723                pw.println("  cmd may be one of:");
21724                pw.println("    l[ibraries]: list known shared libraries");
21725                pw.println("    f[eatures]: list device features");
21726                pw.println("    k[eysets]: print known keysets");
21727                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21728                pw.println("    perm[issions]: dump permissions");
21729                pw.println("    permission [name ...]: dump declaration and use of given permission");
21730                pw.println("    pref[erred]: print preferred package settings");
21731                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21732                pw.println("    prov[iders]: dump content providers");
21733                pw.println("    p[ackages]: dump installed packages");
21734                pw.println("    s[hared-users]: dump shared user IDs");
21735                pw.println("    m[essages]: print collected runtime messages");
21736                pw.println("    v[erifiers]: print package verifier info");
21737                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21738                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21739                pw.println("    version: print database version info");
21740                pw.println("    write: write current settings now");
21741                pw.println("    installs: details about install sessions");
21742                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21743                pw.println("    dexopt: dump dexopt state");
21744                pw.println("    compiler-stats: dump compiler statistics");
21745                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21746                pw.println("    <package.name>: info about given package");
21747                return;
21748            } else if ("--checkin".equals(opt)) {
21749                checkin = true;
21750            } else if ("-f".equals(opt)) {
21751                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21752            } else if ("--proto".equals(opt)) {
21753                dumpProto(fd);
21754                return;
21755            } else {
21756                pw.println("Unknown argument: " + opt + "; use -h for help");
21757            }
21758        }
21759
21760        // Is the caller requesting to dump a particular piece of data?
21761        if (opti < args.length) {
21762            String cmd = args[opti];
21763            opti++;
21764            // Is this a package name?
21765            if ("android".equals(cmd) || cmd.contains(".")) {
21766                packageName = cmd;
21767                // When dumping a single package, we always dump all of its
21768                // filter information since the amount of data will be reasonable.
21769                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21770            } else if ("check-permission".equals(cmd)) {
21771                if (opti >= args.length) {
21772                    pw.println("Error: check-permission missing permission argument");
21773                    return;
21774                }
21775                String perm = args[opti];
21776                opti++;
21777                if (opti >= args.length) {
21778                    pw.println("Error: check-permission missing package argument");
21779                    return;
21780                }
21781
21782                String pkg = args[opti];
21783                opti++;
21784                int user = UserHandle.getUserId(Binder.getCallingUid());
21785                if (opti < args.length) {
21786                    try {
21787                        user = Integer.parseInt(args[opti]);
21788                    } catch (NumberFormatException e) {
21789                        pw.println("Error: check-permission user argument is not a number: "
21790                                + args[opti]);
21791                        return;
21792                    }
21793                }
21794
21795                // Normalize package name to handle renamed packages and static libs
21796                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21797
21798                pw.println(checkPermission(perm, pkg, user));
21799                return;
21800            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21801                dumpState.setDump(DumpState.DUMP_LIBS);
21802            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21803                dumpState.setDump(DumpState.DUMP_FEATURES);
21804            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21805                if (opti >= args.length) {
21806                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21807                            | DumpState.DUMP_SERVICE_RESOLVERS
21808                            | DumpState.DUMP_RECEIVER_RESOLVERS
21809                            | DumpState.DUMP_CONTENT_RESOLVERS);
21810                } else {
21811                    while (opti < args.length) {
21812                        String name = args[opti];
21813                        if ("a".equals(name) || "activity".equals(name)) {
21814                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21815                        } else if ("s".equals(name) || "service".equals(name)) {
21816                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21817                        } else if ("r".equals(name) || "receiver".equals(name)) {
21818                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21819                        } else if ("c".equals(name) || "content".equals(name)) {
21820                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21821                        } else {
21822                            pw.println("Error: unknown resolver table type: " + name);
21823                            return;
21824                        }
21825                        opti++;
21826                    }
21827                }
21828            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21829                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21830            } else if ("permission".equals(cmd)) {
21831                if (opti >= args.length) {
21832                    pw.println("Error: permission requires permission name");
21833                    return;
21834                }
21835                permissionNames = new ArraySet<>();
21836                while (opti < args.length) {
21837                    permissionNames.add(args[opti]);
21838                    opti++;
21839                }
21840                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21841                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21842            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21843                dumpState.setDump(DumpState.DUMP_PREFERRED);
21844            } else if ("preferred-xml".equals(cmd)) {
21845                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21846                if (opti < args.length && "--full".equals(args[opti])) {
21847                    fullPreferred = true;
21848                    opti++;
21849                }
21850            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21851                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21852            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21853                dumpState.setDump(DumpState.DUMP_PACKAGES);
21854            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21855                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21856            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21857                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21858            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21859                dumpState.setDump(DumpState.DUMP_MESSAGES);
21860            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21861                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21862            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21863                    || "intent-filter-verifiers".equals(cmd)) {
21864                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21865            } else if ("version".equals(cmd)) {
21866                dumpState.setDump(DumpState.DUMP_VERSION);
21867            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21868                dumpState.setDump(DumpState.DUMP_KEYSETS);
21869            } else if ("installs".equals(cmd)) {
21870                dumpState.setDump(DumpState.DUMP_INSTALLS);
21871            } else if ("frozen".equals(cmd)) {
21872                dumpState.setDump(DumpState.DUMP_FROZEN);
21873            } else if ("dexopt".equals(cmd)) {
21874                dumpState.setDump(DumpState.DUMP_DEXOPT);
21875            } else if ("compiler-stats".equals(cmd)) {
21876                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21877            } else if ("changes".equals(cmd)) {
21878                dumpState.setDump(DumpState.DUMP_CHANGES);
21879            } else if ("write".equals(cmd)) {
21880                synchronized (mPackages) {
21881                    mSettings.writeLPr();
21882                    pw.println("Settings written.");
21883                    return;
21884                }
21885            }
21886        }
21887
21888        if (checkin) {
21889            pw.println("vers,1");
21890        }
21891
21892        // reader
21893        synchronized (mPackages) {
21894            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21895                if (!checkin) {
21896                    if (dumpState.onTitlePrinted())
21897                        pw.println();
21898                    pw.println("Database versions:");
21899                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21900                }
21901            }
21902
21903            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21904                if (!checkin) {
21905                    if (dumpState.onTitlePrinted())
21906                        pw.println();
21907                    pw.println("Verifiers:");
21908                    pw.print("  Required: ");
21909                    pw.print(mRequiredVerifierPackage);
21910                    pw.print(" (uid=");
21911                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21912                            UserHandle.USER_SYSTEM));
21913                    pw.println(")");
21914                } else if (mRequiredVerifierPackage != null) {
21915                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21916                    pw.print(",");
21917                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21918                            UserHandle.USER_SYSTEM));
21919                }
21920            }
21921
21922            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21923                    packageName == null) {
21924                if (mIntentFilterVerifierComponent != null) {
21925                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21926                    if (!checkin) {
21927                        if (dumpState.onTitlePrinted())
21928                            pw.println();
21929                        pw.println("Intent Filter Verifier:");
21930                        pw.print("  Using: ");
21931                        pw.print(verifierPackageName);
21932                        pw.print(" (uid=");
21933                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21934                                UserHandle.USER_SYSTEM));
21935                        pw.println(")");
21936                    } else if (verifierPackageName != null) {
21937                        pw.print("ifv,"); pw.print(verifierPackageName);
21938                        pw.print(",");
21939                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21940                                UserHandle.USER_SYSTEM));
21941                    }
21942                } else {
21943                    pw.println();
21944                    pw.println("No Intent Filter Verifier available!");
21945                }
21946            }
21947
21948            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21949                boolean printedHeader = false;
21950                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21951                while (it.hasNext()) {
21952                    String libName = it.next();
21953                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21954                    if (versionedLib == null) {
21955                        continue;
21956                    }
21957                    final int versionCount = versionedLib.size();
21958                    for (int i = 0; i < versionCount; i++) {
21959                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21960                        if (!checkin) {
21961                            if (!printedHeader) {
21962                                if (dumpState.onTitlePrinted())
21963                                    pw.println();
21964                                pw.println("Libraries:");
21965                                printedHeader = true;
21966                            }
21967                            pw.print("  ");
21968                        } else {
21969                            pw.print("lib,");
21970                        }
21971                        pw.print(libEntry.info.getName());
21972                        if (libEntry.info.isStatic()) {
21973                            pw.print(" version=" + libEntry.info.getVersion());
21974                        }
21975                        if (!checkin) {
21976                            pw.print(" -> ");
21977                        }
21978                        if (libEntry.path != null) {
21979                            pw.print(" (jar) ");
21980                            pw.print(libEntry.path);
21981                        } else {
21982                            pw.print(" (apk) ");
21983                            pw.print(libEntry.apk);
21984                        }
21985                        pw.println();
21986                    }
21987                }
21988            }
21989
21990            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21991                if (dumpState.onTitlePrinted())
21992                    pw.println();
21993                if (!checkin) {
21994                    pw.println("Features:");
21995                }
21996
21997                synchronized (mAvailableFeatures) {
21998                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21999                        if (checkin) {
22000                            pw.print("feat,");
22001                            pw.print(feat.name);
22002                            pw.print(",");
22003                            pw.println(feat.version);
22004                        } else {
22005                            pw.print("  ");
22006                            pw.print(feat.name);
22007                            if (feat.version > 0) {
22008                                pw.print(" version=");
22009                                pw.print(feat.version);
22010                            }
22011                            pw.println();
22012                        }
22013                    }
22014                }
22015            }
22016
22017            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22018                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22019                        : "Activity Resolver Table:", "  ", packageName,
22020                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22021                    dumpState.setTitlePrinted(true);
22022                }
22023            }
22024            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22025                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22026                        : "Receiver Resolver Table:", "  ", packageName,
22027                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22028                    dumpState.setTitlePrinted(true);
22029                }
22030            }
22031            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22032                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22033                        : "Service Resolver Table:", "  ", packageName,
22034                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22035                    dumpState.setTitlePrinted(true);
22036                }
22037            }
22038            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22039                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22040                        : "Provider Resolver Table:", "  ", packageName,
22041                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22042                    dumpState.setTitlePrinted(true);
22043                }
22044            }
22045
22046            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22047                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22048                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22049                    int user = mSettings.mPreferredActivities.keyAt(i);
22050                    if (pir.dump(pw,
22051                            dumpState.getTitlePrinted()
22052                                ? "\nPreferred Activities User " + user + ":"
22053                                : "Preferred Activities User " + user + ":", "  ",
22054                            packageName, true, false)) {
22055                        dumpState.setTitlePrinted(true);
22056                    }
22057                }
22058            }
22059
22060            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22061                pw.flush();
22062                FileOutputStream fout = new FileOutputStream(fd);
22063                BufferedOutputStream str = new BufferedOutputStream(fout);
22064                XmlSerializer serializer = new FastXmlSerializer();
22065                try {
22066                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22067                    serializer.startDocument(null, true);
22068                    serializer.setFeature(
22069                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22070                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22071                    serializer.endDocument();
22072                    serializer.flush();
22073                } catch (IllegalArgumentException e) {
22074                    pw.println("Failed writing: " + e);
22075                } catch (IllegalStateException e) {
22076                    pw.println("Failed writing: " + e);
22077                } catch (IOException e) {
22078                    pw.println("Failed writing: " + e);
22079                }
22080            }
22081
22082            if (!checkin
22083                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22084                    && packageName == null) {
22085                pw.println();
22086                int count = mSettings.mPackages.size();
22087                if (count == 0) {
22088                    pw.println("No applications!");
22089                    pw.println();
22090                } else {
22091                    final String prefix = "  ";
22092                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22093                    if (allPackageSettings.size() == 0) {
22094                        pw.println("No domain preferred apps!");
22095                        pw.println();
22096                    } else {
22097                        pw.println("App verification status:");
22098                        pw.println();
22099                        count = 0;
22100                        for (PackageSetting ps : allPackageSettings) {
22101                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22102                            if (ivi == null || ivi.getPackageName() == null) continue;
22103                            pw.println(prefix + "Package: " + ivi.getPackageName());
22104                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22105                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22106                            pw.println();
22107                            count++;
22108                        }
22109                        if (count == 0) {
22110                            pw.println(prefix + "No app verification established.");
22111                            pw.println();
22112                        }
22113                        for (int userId : sUserManager.getUserIds()) {
22114                            pw.println("App linkages for user " + userId + ":");
22115                            pw.println();
22116                            count = 0;
22117                            for (PackageSetting ps : allPackageSettings) {
22118                                final long status = ps.getDomainVerificationStatusForUser(userId);
22119                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22120                                        && !DEBUG_DOMAIN_VERIFICATION) {
22121                                    continue;
22122                                }
22123                                pw.println(prefix + "Package: " + ps.name);
22124                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22125                                String statusStr = IntentFilterVerificationInfo.
22126                                        getStatusStringFromValue(status);
22127                                pw.println(prefix + "Status:  " + statusStr);
22128                                pw.println();
22129                                count++;
22130                            }
22131                            if (count == 0) {
22132                                pw.println(prefix + "No configured app linkages.");
22133                                pw.println();
22134                            }
22135                        }
22136                    }
22137                }
22138            }
22139
22140            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22141                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22142                if (packageName == null && permissionNames == null) {
22143                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22144                        if (iperm == 0) {
22145                            if (dumpState.onTitlePrinted())
22146                                pw.println();
22147                            pw.println("AppOp Permissions:");
22148                        }
22149                        pw.print("  AppOp Permission ");
22150                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22151                        pw.println(":");
22152                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22153                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22154                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22155                        }
22156                    }
22157                }
22158            }
22159
22160            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22161                boolean printedSomething = false;
22162                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22163                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22164                        continue;
22165                    }
22166                    if (!printedSomething) {
22167                        if (dumpState.onTitlePrinted())
22168                            pw.println();
22169                        pw.println("Registered ContentProviders:");
22170                        printedSomething = true;
22171                    }
22172                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22173                    pw.print("    "); pw.println(p.toString());
22174                }
22175                printedSomething = false;
22176                for (Map.Entry<String, PackageParser.Provider> entry :
22177                        mProvidersByAuthority.entrySet()) {
22178                    PackageParser.Provider p = entry.getValue();
22179                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22180                        continue;
22181                    }
22182                    if (!printedSomething) {
22183                        if (dumpState.onTitlePrinted())
22184                            pw.println();
22185                        pw.println("ContentProvider Authorities:");
22186                        printedSomething = true;
22187                    }
22188                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22189                    pw.print("    "); pw.println(p.toString());
22190                    if (p.info != null && p.info.applicationInfo != null) {
22191                        final String appInfo = p.info.applicationInfo.toString();
22192                        pw.print("      applicationInfo="); pw.println(appInfo);
22193                    }
22194                }
22195            }
22196
22197            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22198                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22199            }
22200
22201            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22202                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22203            }
22204
22205            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22206                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22207            }
22208
22209            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22210                if (dumpState.onTitlePrinted()) pw.println();
22211                pw.println("Package Changes:");
22212                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22213                final int K = mChangedPackages.size();
22214                for (int i = 0; i < K; i++) {
22215                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22216                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22217                    final int N = changes.size();
22218                    if (N == 0) {
22219                        pw.print("    "); pw.println("No packages changed");
22220                    } else {
22221                        for (int j = 0; j < N; j++) {
22222                            final String pkgName = changes.valueAt(j);
22223                            final int sequenceNumber = changes.keyAt(j);
22224                            pw.print("    ");
22225                            pw.print("seq=");
22226                            pw.print(sequenceNumber);
22227                            pw.print(", package=");
22228                            pw.println(pkgName);
22229                        }
22230                    }
22231                }
22232            }
22233
22234            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22235                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22236            }
22237
22238            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22239                // XXX should handle packageName != null by dumping only install data that
22240                // the given package is involved with.
22241                if (dumpState.onTitlePrinted()) pw.println();
22242
22243                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22244                ipw.println();
22245                ipw.println("Frozen packages:");
22246                ipw.increaseIndent();
22247                if (mFrozenPackages.size() == 0) {
22248                    ipw.println("(none)");
22249                } else {
22250                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22251                        ipw.println(mFrozenPackages.valueAt(i));
22252                    }
22253                }
22254                ipw.decreaseIndent();
22255            }
22256
22257            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22258                if (dumpState.onTitlePrinted()) pw.println();
22259                dumpDexoptStateLPr(pw, packageName);
22260            }
22261
22262            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22263                if (dumpState.onTitlePrinted()) pw.println();
22264                dumpCompilerStatsLPr(pw, packageName);
22265            }
22266
22267            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22268                if (dumpState.onTitlePrinted()) pw.println();
22269                mSettings.dumpReadMessagesLPr(pw, dumpState);
22270
22271                pw.println();
22272                pw.println("Package warning messages:");
22273                BufferedReader in = null;
22274                String line = null;
22275                try {
22276                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22277                    while ((line = in.readLine()) != null) {
22278                        if (line.contains("ignored: updated version")) continue;
22279                        pw.println(line);
22280                    }
22281                } catch (IOException ignored) {
22282                } finally {
22283                    IoUtils.closeQuietly(in);
22284                }
22285            }
22286
22287            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22288                BufferedReader in = null;
22289                String line = null;
22290                try {
22291                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22292                    while ((line = in.readLine()) != null) {
22293                        if (line.contains("ignored: updated version")) continue;
22294                        pw.print("msg,");
22295                        pw.println(line);
22296                    }
22297                } catch (IOException ignored) {
22298                } finally {
22299                    IoUtils.closeQuietly(in);
22300                }
22301            }
22302        }
22303
22304        // PackageInstaller should be called outside of mPackages lock
22305        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22306            // XXX should handle packageName != null by dumping only install data that
22307            // the given package is involved with.
22308            if (dumpState.onTitlePrinted()) pw.println();
22309            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22310        }
22311    }
22312
22313    private void dumpProto(FileDescriptor fd) {
22314        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22315
22316        synchronized (mPackages) {
22317            final long requiredVerifierPackageToken =
22318                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22319            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22320            proto.write(
22321                    PackageServiceDumpProto.PackageShortProto.UID,
22322                    getPackageUid(
22323                            mRequiredVerifierPackage,
22324                            MATCH_DEBUG_TRIAGED_MISSING,
22325                            UserHandle.USER_SYSTEM));
22326            proto.end(requiredVerifierPackageToken);
22327
22328            if (mIntentFilterVerifierComponent != null) {
22329                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22330                final long verifierPackageToken =
22331                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22332                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22333                proto.write(
22334                        PackageServiceDumpProto.PackageShortProto.UID,
22335                        getPackageUid(
22336                                verifierPackageName,
22337                                MATCH_DEBUG_TRIAGED_MISSING,
22338                                UserHandle.USER_SYSTEM));
22339                proto.end(verifierPackageToken);
22340            }
22341
22342            dumpSharedLibrariesProto(proto);
22343            dumpFeaturesProto(proto);
22344            mSettings.dumpPackagesProto(proto);
22345            mSettings.dumpSharedUsersProto(proto);
22346            dumpMessagesProto(proto);
22347        }
22348        proto.flush();
22349    }
22350
22351    private void dumpMessagesProto(ProtoOutputStream proto) {
22352        BufferedReader in = null;
22353        String line = null;
22354        try {
22355            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22356            while ((line = in.readLine()) != null) {
22357                if (line.contains("ignored: updated version")) continue;
22358                proto.write(PackageServiceDumpProto.MESSAGES, line);
22359            }
22360        } catch (IOException ignored) {
22361        } finally {
22362            IoUtils.closeQuietly(in);
22363        }
22364    }
22365
22366    private void dumpFeaturesProto(ProtoOutputStream proto) {
22367        synchronized (mAvailableFeatures) {
22368            final int count = mAvailableFeatures.size();
22369            for (int i = 0; i < count; i++) {
22370                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22371                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22372                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22373                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22374                proto.end(featureToken);
22375            }
22376        }
22377    }
22378
22379    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22380        final int count = mSharedLibraries.size();
22381        for (int i = 0; i < count; i++) {
22382            final String libName = mSharedLibraries.keyAt(i);
22383            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22384            if (versionedLib == null) {
22385                continue;
22386            }
22387            final int versionCount = versionedLib.size();
22388            for (int j = 0; j < versionCount; j++) {
22389                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22390                final long sharedLibraryToken =
22391                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22392                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22393                final boolean isJar = (libEntry.path != null);
22394                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22395                if (isJar) {
22396                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22397                } else {
22398                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22399                }
22400                proto.end(sharedLibraryToken);
22401            }
22402        }
22403    }
22404
22405    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22406        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22407        ipw.println();
22408        ipw.println("Dexopt state:");
22409        ipw.increaseIndent();
22410        Collection<PackageParser.Package> packages = null;
22411        if (packageName != null) {
22412            PackageParser.Package targetPackage = mPackages.get(packageName);
22413            if (targetPackage != null) {
22414                packages = Collections.singletonList(targetPackage);
22415            } else {
22416                ipw.println("Unable to find package: " + packageName);
22417                return;
22418            }
22419        } else {
22420            packages = mPackages.values();
22421        }
22422
22423        for (PackageParser.Package pkg : packages) {
22424            ipw.println("[" + pkg.packageName + "]");
22425            ipw.increaseIndent();
22426            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22427            ipw.decreaseIndent();
22428        }
22429    }
22430
22431    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22432        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22433        ipw.println();
22434        ipw.println("Compiler stats:");
22435        ipw.increaseIndent();
22436        Collection<PackageParser.Package> packages = null;
22437        if (packageName != null) {
22438            PackageParser.Package targetPackage = mPackages.get(packageName);
22439            if (targetPackage != null) {
22440                packages = Collections.singletonList(targetPackage);
22441            } else {
22442                ipw.println("Unable to find package: " + packageName);
22443                return;
22444            }
22445        } else {
22446            packages = mPackages.values();
22447        }
22448
22449        for (PackageParser.Package pkg : packages) {
22450            ipw.println("[" + pkg.packageName + "]");
22451            ipw.increaseIndent();
22452
22453            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22454            if (stats == null) {
22455                ipw.println("(No recorded stats)");
22456            } else {
22457                stats.dump(ipw);
22458            }
22459            ipw.decreaseIndent();
22460        }
22461    }
22462
22463    private String dumpDomainString(String packageName) {
22464        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22465                .getList();
22466        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22467
22468        ArraySet<String> result = new ArraySet<>();
22469        if (iviList.size() > 0) {
22470            for (IntentFilterVerificationInfo ivi : iviList) {
22471                for (String host : ivi.getDomains()) {
22472                    result.add(host);
22473                }
22474            }
22475        }
22476        if (filters != null && filters.size() > 0) {
22477            for (IntentFilter filter : filters) {
22478                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22479                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22480                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22481                    result.addAll(filter.getHostsList());
22482                }
22483            }
22484        }
22485
22486        StringBuilder sb = new StringBuilder(result.size() * 16);
22487        for (String domain : result) {
22488            if (sb.length() > 0) sb.append(" ");
22489            sb.append(domain);
22490        }
22491        return sb.toString();
22492    }
22493
22494    // ------- apps on sdcard specific code -------
22495    static final boolean DEBUG_SD_INSTALL = false;
22496
22497    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22498
22499    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22500
22501    private boolean mMediaMounted = false;
22502
22503    static String getEncryptKey() {
22504        try {
22505            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22506                    SD_ENCRYPTION_KEYSTORE_NAME);
22507            if (sdEncKey == null) {
22508                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22509                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22510                if (sdEncKey == null) {
22511                    Slog.e(TAG, "Failed to create encryption keys");
22512                    return null;
22513                }
22514            }
22515            return sdEncKey;
22516        } catch (NoSuchAlgorithmException nsae) {
22517            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22518            return null;
22519        } catch (IOException ioe) {
22520            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22521            return null;
22522        }
22523    }
22524
22525    /*
22526     * Update media status on PackageManager.
22527     */
22528    @Override
22529    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22530        enforceSystemOrRoot("Media status can only be updated by the system");
22531        // reader; this apparently protects mMediaMounted, but should probably
22532        // be a different lock in that case.
22533        synchronized (mPackages) {
22534            Log.i(TAG, "Updating external media status from "
22535                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22536                    + (mediaStatus ? "mounted" : "unmounted"));
22537            if (DEBUG_SD_INSTALL)
22538                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22539                        + ", mMediaMounted=" + mMediaMounted);
22540            if (mediaStatus == mMediaMounted) {
22541                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22542                        : 0, -1);
22543                mHandler.sendMessage(msg);
22544                return;
22545            }
22546            mMediaMounted = mediaStatus;
22547        }
22548        // Queue up an async operation since the package installation may take a
22549        // little while.
22550        mHandler.post(new Runnable() {
22551            public void run() {
22552                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22553            }
22554        });
22555    }
22556
22557    /**
22558     * Called by StorageManagerService when the initial ASECs to scan are available.
22559     * Should block until all the ASEC containers are finished being scanned.
22560     */
22561    public void scanAvailableAsecs() {
22562        updateExternalMediaStatusInner(true, false, false);
22563    }
22564
22565    /*
22566     * Collect information of applications on external media, map them against
22567     * existing containers and update information based on current mount status.
22568     * Please note that we always have to report status if reportStatus has been
22569     * set to true especially when unloading packages.
22570     */
22571    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22572            boolean externalStorage) {
22573        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22574        int[] uidArr = EmptyArray.INT;
22575
22576        final String[] list = PackageHelper.getSecureContainerList();
22577        if (ArrayUtils.isEmpty(list)) {
22578            Log.i(TAG, "No secure containers found");
22579        } else {
22580            // Process list of secure containers and categorize them
22581            // as active or stale based on their package internal state.
22582
22583            // reader
22584            synchronized (mPackages) {
22585                for (String cid : list) {
22586                    // Leave stages untouched for now; installer service owns them
22587                    if (PackageInstallerService.isStageName(cid)) continue;
22588
22589                    if (DEBUG_SD_INSTALL)
22590                        Log.i(TAG, "Processing container " + cid);
22591                    String pkgName = getAsecPackageName(cid);
22592                    if (pkgName == null) {
22593                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22594                        continue;
22595                    }
22596                    if (DEBUG_SD_INSTALL)
22597                        Log.i(TAG, "Looking for pkg : " + pkgName);
22598
22599                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22600                    if (ps == null) {
22601                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22602                        continue;
22603                    }
22604
22605                    /*
22606                     * Skip packages that are not external if we're unmounting
22607                     * external storage.
22608                     */
22609                    if (externalStorage && !isMounted && !isExternal(ps)) {
22610                        continue;
22611                    }
22612
22613                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22614                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22615                    // The package status is changed only if the code path
22616                    // matches between settings and the container id.
22617                    if (ps.codePathString != null
22618                            && ps.codePathString.startsWith(args.getCodePath())) {
22619                        if (DEBUG_SD_INSTALL) {
22620                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22621                                    + " at code path: " + ps.codePathString);
22622                        }
22623
22624                        // We do have a valid package installed on sdcard
22625                        processCids.put(args, ps.codePathString);
22626                        final int uid = ps.appId;
22627                        if (uid != -1) {
22628                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22629                        }
22630                    } else {
22631                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22632                                + ps.codePathString);
22633                    }
22634                }
22635            }
22636
22637            Arrays.sort(uidArr);
22638        }
22639
22640        // Process packages with valid entries.
22641        if (isMounted) {
22642            if (DEBUG_SD_INSTALL)
22643                Log.i(TAG, "Loading packages");
22644            loadMediaPackages(processCids, uidArr, externalStorage);
22645            startCleaningPackages();
22646            mInstallerService.onSecureContainersAvailable();
22647        } else {
22648            if (DEBUG_SD_INSTALL)
22649                Log.i(TAG, "Unloading packages");
22650            unloadMediaPackages(processCids, uidArr, reportStatus);
22651        }
22652    }
22653
22654    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22655            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22656        final int size = infos.size();
22657        final String[] packageNames = new String[size];
22658        final int[] packageUids = new int[size];
22659        for (int i = 0; i < size; i++) {
22660            final ApplicationInfo info = infos.get(i);
22661            packageNames[i] = info.packageName;
22662            packageUids[i] = info.uid;
22663        }
22664        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22665                finishedReceiver);
22666    }
22667
22668    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22669            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22670        sendResourcesChangedBroadcast(mediaStatus, replacing,
22671                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22672    }
22673
22674    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22675            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22676        int size = pkgList.length;
22677        if (size > 0) {
22678            // Send broadcasts here
22679            Bundle extras = new Bundle();
22680            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22681            if (uidArr != null) {
22682                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22683            }
22684            if (replacing) {
22685                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22686            }
22687            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22688                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22689            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22690        }
22691    }
22692
22693   /*
22694     * Look at potentially valid container ids from processCids If package
22695     * information doesn't match the one on record or package scanning fails,
22696     * the cid is added to list of removeCids. We currently don't delete stale
22697     * containers.
22698     */
22699    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22700            boolean externalStorage) {
22701        ArrayList<String> pkgList = new ArrayList<String>();
22702        Set<AsecInstallArgs> keys = processCids.keySet();
22703
22704        for (AsecInstallArgs args : keys) {
22705            String codePath = processCids.get(args);
22706            if (DEBUG_SD_INSTALL)
22707                Log.i(TAG, "Loading container : " + args.cid);
22708            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22709            try {
22710                // Make sure there are no container errors first.
22711                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22712                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22713                            + " when installing from sdcard");
22714                    continue;
22715                }
22716                // Check code path here.
22717                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22718                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22719                            + " does not match one in settings " + codePath);
22720                    continue;
22721                }
22722                // Parse package
22723                int parseFlags = mDefParseFlags;
22724                if (args.isExternalAsec()) {
22725                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22726                }
22727                if (args.isFwdLocked()) {
22728                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22729                }
22730
22731                synchronized (mInstallLock) {
22732                    PackageParser.Package pkg = null;
22733                    try {
22734                        // Sadly we don't know the package name yet to freeze it
22735                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22736                                SCAN_IGNORE_FROZEN, 0, null);
22737                    } catch (PackageManagerException e) {
22738                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22739                    }
22740                    // Scan the package
22741                    if (pkg != null) {
22742                        /*
22743                         * TODO why is the lock being held? doPostInstall is
22744                         * called in other places without the lock. This needs
22745                         * to be straightened out.
22746                         */
22747                        // writer
22748                        synchronized (mPackages) {
22749                            retCode = PackageManager.INSTALL_SUCCEEDED;
22750                            pkgList.add(pkg.packageName);
22751                            // Post process args
22752                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22753                                    pkg.applicationInfo.uid);
22754                        }
22755                    } else {
22756                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22757                    }
22758                }
22759
22760            } finally {
22761                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22762                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22763                }
22764            }
22765        }
22766        // writer
22767        synchronized (mPackages) {
22768            // If the platform SDK has changed since the last time we booted,
22769            // we need to re-grant app permission to catch any new ones that
22770            // appear. This is really a hack, and means that apps can in some
22771            // cases get permissions that the user didn't initially explicitly
22772            // allow... it would be nice to have some better way to handle
22773            // this situation.
22774            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22775                    : mSettings.getInternalVersion();
22776            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22777                    : StorageManager.UUID_PRIVATE_INTERNAL;
22778
22779            int updateFlags = UPDATE_PERMISSIONS_ALL;
22780            if (ver.sdkVersion != mSdkVersion) {
22781                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22782                        + mSdkVersion + "; regranting permissions for external");
22783                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22784            }
22785            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22786
22787            // Yay, everything is now upgraded
22788            ver.forceCurrent();
22789
22790            // can downgrade to reader
22791            // Persist settings
22792            mSettings.writeLPr();
22793        }
22794        // Send a broadcast to let everyone know we are done processing
22795        if (pkgList.size() > 0) {
22796            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22797        }
22798    }
22799
22800   /*
22801     * Utility method to unload a list of specified containers
22802     */
22803    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22804        // Just unmount all valid containers.
22805        for (AsecInstallArgs arg : cidArgs) {
22806            synchronized (mInstallLock) {
22807                arg.doPostDeleteLI(false);
22808           }
22809       }
22810   }
22811
22812    /*
22813     * Unload packages mounted on external media. This involves deleting package
22814     * data from internal structures, sending broadcasts about disabled packages,
22815     * gc'ing to free up references, unmounting all secure containers
22816     * corresponding to packages on external media, and posting a
22817     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22818     * that we always have to post this message if status has been requested no
22819     * matter what.
22820     */
22821    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22822            final boolean reportStatus) {
22823        if (DEBUG_SD_INSTALL)
22824            Log.i(TAG, "unloading media packages");
22825        ArrayList<String> pkgList = new ArrayList<String>();
22826        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22827        final Set<AsecInstallArgs> keys = processCids.keySet();
22828        for (AsecInstallArgs args : keys) {
22829            String pkgName = args.getPackageName();
22830            if (DEBUG_SD_INSTALL)
22831                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22832            // Delete package internally
22833            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22834            synchronized (mInstallLock) {
22835                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22836                final boolean res;
22837                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22838                        "unloadMediaPackages")) {
22839                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22840                            null);
22841                }
22842                if (res) {
22843                    pkgList.add(pkgName);
22844                } else {
22845                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22846                    failedList.add(args);
22847                }
22848            }
22849        }
22850
22851        // reader
22852        synchronized (mPackages) {
22853            // We didn't update the settings after removing each package;
22854            // write them now for all packages.
22855            mSettings.writeLPr();
22856        }
22857
22858        // We have to absolutely send UPDATED_MEDIA_STATUS only
22859        // after confirming that all the receivers processed the ordered
22860        // broadcast when packages get disabled, force a gc to clean things up.
22861        // and unload all the containers.
22862        if (pkgList.size() > 0) {
22863            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22864                    new IIntentReceiver.Stub() {
22865                public void performReceive(Intent intent, int resultCode, String data,
22866                        Bundle extras, boolean ordered, boolean sticky,
22867                        int sendingUser) throws RemoteException {
22868                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22869                            reportStatus ? 1 : 0, 1, keys);
22870                    mHandler.sendMessage(msg);
22871                }
22872            });
22873        } else {
22874            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22875                    keys);
22876            mHandler.sendMessage(msg);
22877        }
22878    }
22879
22880    private void loadPrivatePackages(final VolumeInfo vol) {
22881        mHandler.post(new Runnable() {
22882            @Override
22883            public void run() {
22884                loadPrivatePackagesInner(vol);
22885            }
22886        });
22887    }
22888
22889    private void loadPrivatePackagesInner(VolumeInfo vol) {
22890        final String volumeUuid = vol.fsUuid;
22891        if (TextUtils.isEmpty(volumeUuid)) {
22892            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22893            return;
22894        }
22895
22896        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22897        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22898        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22899
22900        final VersionInfo ver;
22901        final List<PackageSetting> packages;
22902        synchronized (mPackages) {
22903            ver = mSettings.findOrCreateVersion(volumeUuid);
22904            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22905        }
22906
22907        for (PackageSetting ps : packages) {
22908            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22909            synchronized (mInstallLock) {
22910                final PackageParser.Package pkg;
22911                try {
22912                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22913                    loaded.add(pkg.applicationInfo);
22914
22915                } catch (PackageManagerException e) {
22916                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22917                }
22918
22919                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22920                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22921                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22922                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22923                }
22924            }
22925        }
22926
22927        // Reconcile app data for all started/unlocked users
22928        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22929        final UserManager um = mContext.getSystemService(UserManager.class);
22930        UserManagerInternal umInternal = getUserManagerInternal();
22931        for (UserInfo user : um.getUsers()) {
22932            final int flags;
22933            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22934                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22935            } else if (umInternal.isUserRunning(user.id)) {
22936                flags = StorageManager.FLAG_STORAGE_DE;
22937            } else {
22938                continue;
22939            }
22940
22941            try {
22942                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22943                synchronized (mInstallLock) {
22944                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22945                }
22946            } catch (IllegalStateException e) {
22947                // Device was probably ejected, and we'll process that event momentarily
22948                Slog.w(TAG, "Failed to prepare storage: " + e);
22949            }
22950        }
22951
22952        synchronized (mPackages) {
22953            int updateFlags = UPDATE_PERMISSIONS_ALL;
22954            if (ver.sdkVersion != mSdkVersion) {
22955                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22956                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22957                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22958            }
22959            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22960
22961            // Yay, everything is now upgraded
22962            ver.forceCurrent();
22963
22964            mSettings.writeLPr();
22965        }
22966
22967        for (PackageFreezer freezer : freezers) {
22968            freezer.close();
22969        }
22970
22971        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22972        sendResourcesChangedBroadcast(true, false, loaded, null);
22973    }
22974
22975    private void unloadPrivatePackages(final VolumeInfo vol) {
22976        mHandler.post(new Runnable() {
22977            @Override
22978            public void run() {
22979                unloadPrivatePackagesInner(vol);
22980            }
22981        });
22982    }
22983
22984    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22985        final String volumeUuid = vol.fsUuid;
22986        if (TextUtils.isEmpty(volumeUuid)) {
22987            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22988            return;
22989        }
22990
22991        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22992        synchronized (mInstallLock) {
22993        synchronized (mPackages) {
22994            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22995            for (PackageSetting ps : packages) {
22996                if (ps.pkg == null) continue;
22997
22998                final ApplicationInfo info = ps.pkg.applicationInfo;
22999                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23000                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23001
23002                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23003                        "unloadPrivatePackagesInner")) {
23004                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23005                            false, null)) {
23006                        unloaded.add(info);
23007                    } else {
23008                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23009                    }
23010                }
23011
23012                // Try very hard to release any references to this package
23013                // so we don't risk the system server being killed due to
23014                // open FDs
23015                AttributeCache.instance().removePackage(ps.name);
23016            }
23017
23018            mSettings.writeLPr();
23019        }
23020        }
23021
23022        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23023        sendResourcesChangedBroadcast(false, false, unloaded, null);
23024
23025        // Try very hard to release any references to this path so we don't risk
23026        // the system server being killed due to open FDs
23027        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23028
23029        for (int i = 0; i < 3; i++) {
23030            System.gc();
23031            System.runFinalization();
23032        }
23033    }
23034
23035    private void assertPackageKnown(String volumeUuid, String packageName)
23036            throws PackageManagerException {
23037        synchronized (mPackages) {
23038            // Normalize package name to handle renamed packages
23039            packageName = normalizePackageNameLPr(packageName);
23040
23041            final PackageSetting ps = mSettings.mPackages.get(packageName);
23042            if (ps == null) {
23043                throw new PackageManagerException("Package " + packageName + " is unknown");
23044            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23045                throw new PackageManagerException(
23046                        "Package " + packageName + " found on unknown volume " + volumeUuid
23047                                + "; expected volume " + ps.volumeUuid);
23048            }
23049        }
23050    }
23051
23052    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23053            throws PackageManagerException {
23054        synchronized (mPackages) {
23055            // Normalize package name to handle renamed packages
23056            packageName = normalizePackageNameLPr(packageName);
23057
23058            final PackageSetting ps = mSettings.mPackages.get(packageName);
23059            if (ps == null) {
23060                throw new PackageManagerException("Package " + packageName + " is unknown");
23061            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23062                throw new PackageManagerException(
23063                        "Package " + packageName + " found on unknown volume " + volumeUuid
23064                                + "; expected volume " + ps.volumeUuid);
23065            } else if (!ps.getInstalled(userId)) {
23066                throw new PackageManagerException(
23067                        "Package " + packageName + " not installed for user " + userId);
23068            }
23069        }
23070    }
23071
23072    private List<String> collectAbsoluteCodePaths() {
23073        synchronized (mPackages) {
23074            List<String> codePaths = new ArrayList<>();
23075            final int packageCount = mSettings.mPackages.size();
23076            for (int i = 0; i < packageCount; i++) {
23077                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23078                codePaths.add(ps.codePath.getAbsolutePath());
23079            }
23080            return codePaths;
23081        }
23082    }
23083
23084    /**
23085     * Examine all apps present on given mounted volume, and destroy apps that
23086     * aren't expected, either due to uninstallation or reinstallation on
23087     * another volume.
23088     */
23089    private void reconcileApps(String volumeUuid) {
23090        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23091        List<File> filesToDelete = null;
23092
23093        final File[] files = FileUtils.listFilesOrEmpty(
23094                Environment.getDataAppDirectory(volumeUuid));
23095        for (File file : files) {
23096            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23097                    && !PackageInstallerService.isStageName(file.getName());
23098            if (!isPackage) {
23099                // Ignore entries which are not packages
23100                continue;
23101            }
23102
23103            String absolutePath = file.getAbsolutePath();
23104
23105            boolean pathValid = false;
23106            final int absoluteCodePathCount = absoluteCodePaths.size();
23107            for (int i = 0; i < absoluteCodePathCount; i++) {
23108                String absoluteCodePath = absoluteCodePaths.get(i);
23109                if (absolutePath.startsWith(absoluteCodePath)) {
23110                    pathValid = true;
23111                    break;
23112                }
23113            }
23114
23115            if (!pathValid) {
23116                if (filesToDelete == null) {
23117                    filesToDelete = new ArrayList<>();
23118                }
23119                filesToDelete.add(file);
23120            }
23121        }
23122
23123        if (filesToDelete != null) {
23124            final int fileToDeleteCount = filesToDelete.size();
23125            for (int i = 0; i < fileToDeleteCount; i++) {
23126                File fileToDelete = filesToDelete.get(i);
23127                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23128                synchronized (mInstallLock) {
23129                    removeCodePathLI(fileToDelete);
23130                }
23131            }
23132        }
23133    }
23134
23135    /**
23136     * Reconcile all app data for the given user.
23137     * <p>
23138     * Verifies that directories exist and that ownership and labeling is
23139     * correct for all installed apps on all mounted volumes.
23140     */
23141    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23142        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23143        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23144            final String volumeUuid = vol.getFsUuid();
23145            synchronized (mInstallLock) {
23146                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23147            }
23148        }
23149    }
23150
23151    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23152            boolean migrateAppData) {
23153        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23154    }
23155
23156    /**
23157     * Reconcile all app data on given mounted volume.
23158     * <p>
23159     * Destroys app data that isn't expected, either due to uninstallation or
23160     * reinstallation on another volume.
23161     * <p>
23162     * Verifies that directories exist and that ownership and labeling is
23163     * correct for all installed apps.
23164     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23165     */
23166    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23167            boolean migrateAppData, boolean onlyCoreApps) {
23168        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23169                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23170        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23171
23172        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23173        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23174
23175        // First look for stale data that doesn't belong, and check if things
23176        // have changed since we did our last restorecon
23177        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23178            if (StorageManager.isFileEncryptedNativeOrEmulated()
23179                    && !StorageManager.isUserKeyUnlocked(userId)) {
23180                throw new RuntimeException(
23181                        "Yikes, someone asked us to reconcile CE storage while " + userId
23182                                + " was still locked; this would have caused massive data loss!");
23183            }
23184
23185            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23186            for (File file : files) {
23187                final String packageName = file.getName();
23188                try {
23189                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23190                } catch (PackageManagerException e) {
23191                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23192                    try {
23193                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23194                                StorageManager.FLAG_STORAGE_CE, 0);
23195                    } catch (InstallerException e2) {
23196                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23197                    }
23198                }
23199            }
23200        }
23201        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23202            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23203            for (File file : files) {
23204                final String packageName = file.getName();
23205                try {
23206                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23207                } catch (PackageManagerException e) {
23208                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23209                    try {
23210                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23211                                StorageManager.FLAG_STORAGE_DE, 0);
23212                    } catch (InstallerException e2) {
23213                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23214                    }
23215                }
23216            }
23217        }
23218
23219        // Ensure that data directories are ready to roll for all packages
23220        // installed for this volume and user
23221        final List<PackageSetting> packages;
23222        synchronized (mPackages) {
23223            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23224        }
23225        int preparedCount = 0;
23226        for (PackageSetting ps : packages) {
23227            final String packageName = ps.name;
23228            if (ps.pkg == null) {
23229                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23230                // TODO: might be due to legacy ASEC apps; we should circle back
23231                // and reconcile again once they're scanned
23232                continue;
23233            }
23234            // Skip non-core apps if requested
23235            if (onlyCoreApps && !ps.pkg.coreApp) {
23236                result.add(packageName);
23237                continue;
23238            }
23239
23240            if (ps.getInstalled(userId)) {
23241                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23242                preparedCount++;
23243            }
23244        }
23245
23246        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23247        return result;
23248    }
23249
23250    /**
23251     * Prepare app data for the given app just after it was installed or
23252     * upgraded. This method carefully only touches users that it's installed
23253     * for, and it forces a restorecon to handle any seinfo changes.
23254     * <p>
23255     * Verifies that directories exist and that ownership and labeling is
23256     * correct for all installed apps. If there is an ownership mismatch, it
23257     * will try recovering system apps by wiping data; third-party app data is
23258     * left intact.
23259     * <p>
23260     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23261     */
23262    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23263        final PackageSetting ps;
23264        synchronized (mPackages) {
23265            ps = mSettings.mPackages.get(pkg.packageName);
23266            mSettings.writeKernelMappingLPr(ps);
23267        }
23268
23269        final UserManager um = mContext.getSystemService(UserManager.class);
23270        UserManagerInternal umInternal = getUserManagerInternal();
23271        for (UserInfo user : um.getUsers()) {
23272            final int flags;
23273            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23274                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23275            } else if (umInternal.isUserRunning(user.id)) {
23276                flags = StorageManager.FLAG_STORAGE_DE;
23277            } else {
23278                continue;
23279            }
23280
23281            if (ps.getInstalled(user.id)) {
23282                // TODO: when user data is locked, mark that we're still dirty
23283                prepareAppDataLIF(pkg, user.id, flags);
23284            }
23285        }
23286    }
23287
23288    /**
23289     * Prepare app data for the given app.
23290     * <p>
23291     * Verifies that directories exist and that ownership and labeling is
23292     * correct for all installed apps. If there is an ownership mismatch, this
23293     * will try recovering system apps by wiping data; third-party app data is
23294     * left intact.
23295     */
23296    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23297        if (pkg == null) {
23298            Slog.wtf(TAG, "Package was null!", new Throwable());
23299            return;
23300        }
23301        prepareAppDataLeafLIF(pkg, userId, flags);
23302        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23303        for (int i = 0; i < childCount; i++) {
23304            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23305        }
23306    }
23307
23308    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23309            boolean maybeMigrateAppData) {
23310        prepareAppDataLIF(pkg, userId, flags);
23311
23312        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23313            // We may have just shuffled around app data directories, so
23314            // prepare them one more time
23315            prepareAppDataLIF(pkg, userId, flags);
23316        }
23317    }
23318
23319    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23320        if (DEBUG_APP_DATA) {
23321            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23322                    + Integer.toHexString(flags));
23323        }
23324
23325        final String volumeUuid = pkg.volumeUuid;
23326        final String packageName = pkg.packageName;
23327        final ApplicationInfo app = pkg.applicationInfo;
23328        final int appId = UserHandle.getAppId(app.uid);
23329
23330        Preconditions.checkNotNull(app.seInfo);
23331
23332        long ceDataInode = -1;
23333        try {
23334            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23335                    appId, app.seInfo, app.targetSdkVersion);
23336        } catch (InstallerException e) {
23337            if (app.isSystemApp()) {
23338                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23339                        + ", but trying to recover: " + e);
23340                destroyAppDataLeafLIF(pkg, userId, flags);
23341                try {
23342                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23343                            appId, app.seInfo, app.targetSdkVersion);
23344                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23345                } catch (InstallerException e2) {
23346                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23347                }
23348            } else {
23349                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23350            }
23351        }
23352
23353        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23354            // TODO: mark this structure as dirty so we persist it!
23355            synchronized (mPackages) {
23356                final PackageSetting ps = mSettings.mPackages.get(packageName);
23357                if (ps != null) {
23358                    ps.setCeDataInode(ceDataInode, userId);
23359                }
23360            }
23361        }
23362
23363        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23364    }
23365
23366    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23367        if (pkg == null) {
23368            Slog.wtf(TAG, "Package was null!", new Throwable());
23369            return;
23370        }
23371        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23372        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23373        for (int i = 0; i < childCount; i++) {
23374            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23375        }
23376    }
23377
23378    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23379        final String volumeUuid = pkg.volumeUuid;
23380        final String packageName = pkg.packageName;
23381        final ApplicationInfo app = pkg.applicationInfo;
23382
23383        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23384            // Create a native library symlink only if we have native libraries
23385            // and if the native libraries are 32 bit libraries. We do not provide
23386            // this symlink for 64 bit libraries.
23387            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23388                final String nativeLibPath = app.nativeLibraryDir;
23389                try {
23390                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23391                            nativeLibPath, userId);
23392                } catch (InstallerException e) {
23393                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23394                }
23395            }
23396        }
23397    }
23398
23399    /**
23400     * For system apps on non-FBE devices, this method migrates any existing
23401     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23402     * requested by the app.
23403     */
23404    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23405        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23406                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23407            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23408                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23409            try {
23410                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23411                        storageTarget);
23412            } catch (InstallerException e) {
23413                logCriticalInfo(Log.WARN,
23414                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23415            }
23416            return true;
23417        } else {
23418            return false;
23419        }
23420    }
23421
23422    public PackageFreezer freezePackage(String packageName, String killReason) {
23423        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23424    }
23425
23426    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23427        return new PackageFreezer(packageName, userId, killReason);
23428    }
23429
23430    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23431            String killReason) {
23432        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23433    }
23434
23435    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23436            String killReason) {
23437        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23438            return new PackageFreezer();
23439        } else {
23440            return freezePackage(packageName, userId, killReason);
23441        }
23442    }
23443
23444    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23445            String killReason) {
23446        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23447    }
23448
23449    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23450            String killReason) {
23451        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23452            return new PackageFreezer();
23453        } else {
23454            return freezePackage(packageName, userId, killReason);
23455        }
23456    }
23457
23458    /**
23459     * Class that freezes and kills the given package upon creation, and
23460     * unfreezes it upon closing. This is typically used when doing surgery on
23461     * app code/data to prevent the app from running while you're working.
23462     */
23463    private class PackageFreezer implements AutoCloseable {
23464        private final String mPackageName;
23465        private final PackageFreezer[] mChildren;
23466
23467        private final boolean mWeFroze;
23468
23469        private final AtomicBoolean mClosed = new AtomicBoolean();
23470        private final CloseGuard mCloseGuard = CloseGuard.get();
23471
23472        /**
23473         * Create and return a stub freezer that doesn't actually do anything,
23474         * typically used when someone requested
23475         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23476         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23477         */
23478        public PackageFreezer() {
23479            mPackageName = null;
23480            mChildren = null;
23481            mWeFroze = false;
23482            mCloseGuard.open("close");
23483        }
23484
23485        public PackageFreezer(String packageName, int userId, String killReason) {
23486            synchronized (mPackages) {
23487                mPackageName = packageName;
23488                mWeFroze = mFrozenPackages.add(mPackageName);
23489
23490                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23491                if (ps != null) {
23492                    killApplication(ps.name, ps.appId, userId, killReason);
23493                }
23494
23495                final PackageParser.Package p = mPackages.get(packageName);
23496                if (p != null && p.childPackages != null) {
23497                    final int N = p.childPackages.size();
23498                    mChildren = new PackageFreezer[N];
23499                    for (int i = 0; i < N; i++) {
23500                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23501                                userId, killReason);
23502                    }
23503                } else {
23504                    mChildren = null;
23505                }
23506            }
23507            mCloseGuard.open("close");
23508        }
23509
23510        @Override
23511        protected void finalize() throws Throwable {
23512            try {
23513                mCloseGuard.warnIfOpen();
23514                close();
23515            } finally {
23516                super.finalize();
23517            }
23518        }
23519
23520        @Override
23521        public void close() {
23522            mCloseGuard.close();
23523            if (mClosed.compareAndSet(false, true)) {
23524                synchronized (mPackages) {
23525                    if (mWeFroze) {
23526                        mFrozenPackages.remove(mPackageName);
23527                    }
23528
23529                    if (mChildren != null) {
23530                        for (PackageFreezer freezer : mChildren) {
23531                            freezer.close();
23532                        }
23533                    }
23534                }
23535            }
23536        }
23537    }
23538
23539    /**
23540     * Verify that given package is currently frozen.
23541     */
23542    private void checkPackageFrozen(String packageName) {
23543        synchronized (mPackages) {
23544            if (!mFrozenPackages.contains(packageName)) {
23545                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23546            }
23547        }
23548    }
23549
23550    @Override
23551    public int movePackage(final String packageName, final String volumeUuid) {
23552        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23553
23554        final int callingUid = Binder.getCallingUid();
23555        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23556        final int moveId = mNextMoveId.getAndIncrement();
23557        mHandler.post(new Runnable() {
23558            @Override
23559            public void run() {
23560                try {
23561                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23562                } catch (PackageManagerException e) {
23563                    Slog.w(TAG, "Failed to move " + packageName, e);
23564                    mMoveCallbacks.notifyStatusChanged(moveId,
23565                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23566                }
23567            }
23568        });
23569        return moveId;
23570    }
23571
23572    private void movePackageInternal(final String packageName, final String volumeUuid,
23573            final int moveId, final int callingUid, UserHandle user)
23574                    throws PackageManagerException {
23575        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23576        final PackageManager pm = mContext.getPackageManager();
23577
23578        final boolean currentAsec;
23579        final String currentVolumeUuid;
23580        final File codeFile;
23581        final String installerPackageName;
23582        final String packageAbiOverride;
23583        final int appId;
23584        final String seinfo;
23585        final String label;
23586        final int targetSdkVersion;
23587        final PackageFreezer freezer;
23588        final int[] installedUserIds;
23589
23590        // reader
23591        synchronized (mPackages) {
23592            final PackageParser.Package pkg = mPackages.get(packageName);
23593            final PackageSetting ps = mSettings.mPackages.get(packageName);
23594            if (pkg == null
23595                    || ps == null
23596                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23597                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23598            }
23599            if (pkg.applicationInfo.isSystemApp()) {
23600                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23601                        "Cannot move system application");
23602            }
23603
23604            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23605            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23606                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23607            if (isInternalStorage && !allow3rdPartyOnInternal) {
23608                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23609                        "3rd party apps are not allowed on internal storage");
23610            }
23611
23612            if (pkg.applicationInfo.isExternalAsec()) {
23613                currentAsec = true;
23614                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23615            } else if (pkg.applicationInfo.isForwardLocked()) {
23616                currentAsec = true;
23617                currentVolumeUuid = "forward_locked";
23618            } else {
23619                currentAsec = false;
23620                currentVolumeUuid = ps.volumeUuid;
23621
23622                final File probe = new File(pkg.codePath);
23623                final File probeOat = new File(probe, "oat");
23624                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23625                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23626                            "Move only supported for modern cluster style installs");
23627                }
23628            }
23629
23630            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23631                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23632                        "Package already moved to " + volumeUuid);
23633            }
23634            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23635                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23636                        "Device admin cannot be moved");
23637            }
23638
23639            if (mFrozenPackages.contains(packageName)) {
23640                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23641                        "Failed to move already frozen package");
23642            }
23643
23644            codeFile = new File(pkg.codePath);
23645            installerPackageName = ps.installerPackageName;
23646            packageAbiOverride = ps.cpuAbiOverrideString;
23647            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23648            seinfo = pkg.applicationInfo.seInfo;
23649            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23650            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23651            freezer = freezePackage(packageName, "movePackageInternal");
23652            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23653        }
23654
23655        final Bundle extras = new Bundle();
23656        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23657        extras.putString(Intent.EXTRA_TITLE, label);
23658        mMoveCallbacks.notifyCreated(moveId, extras);
23659
23660        int installFlags;
23661        final boolean moveCompleteApp;
23662        final File measurePath;
23663
23664        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23665            installFlags = INSTALL_INTERNAL;
23666            moveCompleteApp = !currentAsec;
23667            measurePath = Environment.getDataAppDirectory(volumeUuid);
23668        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23669            installFlags = INSTALL_EXTERNAL;
23670            moveCompleteApp = false;
23671            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23672        } else {
23673            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23674            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23675                    || !volume.isMountedWritable()) {
23676                freezer.close();
23677                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23678                        "Move location not mounted private volume");
23679            }
23680
23681            Preconditions.checkState(!currentAsec);
23682
23683            installFlags = INSTALL_INTERNAL;
23684            moveCompleteApp = true;
23685            measurePath = Environment.getDataAppDirectory(volumeUuid);
23686        }
23687
23688        final PackageStats stats = new PackageStats(null, -1);
23689        synchronized (mInstaller) {
23690            for (int userId : installedUserIds) {
23691                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23692                    freezer.close();
23693                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23694                            "Failed to measure package size");
23695                }
23696            }
23697        }
23698
23699        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23700                + stats.dataSize);
23701
23702        final long startFreeBytes = measurePath.getUsableSpace();
23703        final long sizeBytes;
23704        if (moveCompleteApp) {
23705            sizeBytes = stats.codeSize + stats.dataSize;
23706        } else {
23707            sizeBytes = stats.codeSize;
23708        }
23709
23710        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23711            freezer.close();
23712            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23713                    "Not enough free space to move");
23714        }
23715
23716        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23717
23718        final CountDownLatch installedLatch = new CountDownLatch(1);
23719        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23720            @Override
23721            public void onUserActionRequired(Intent intent) throws RemoteException {
23722                throw new IllegalStateException();
23723            }
23724
23725            @Override
23726            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23727                    Bundle extras) throws RemoteException {
23728                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23729                        + PackageManager.installStatusToString(returnCode, msg));
23730
23731                installedLatch.countDown();
23732                freezer.close();
23733
23734                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23735                switch (status) {
23736                    case PackageInstaller.STATUS_SUCCESS:
23737                        mMoveCallbacks.notifyStatusChanged(moveId,
23738                                PackageManager.MOVE_SUCCEEDED);
23739                        break;
23740                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23741                        mMoveCallbacks.notifyStatusChanged(moveId,
23742                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23743                        break;
23744                    default:
23745                        mMoveCallbacks.notifyStatusChanged(moveId,
23746                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23747                        break;
23748                }
23749            }
23750        };
23751
23752        final MoveInfo move;
23753        if (moveCompleteApp) {
23754            // Kick off a thread to report progress estimates
23755            new Thread() {
23756                @Override
23757                public void run() {
23758                    while (true) {
23759                        try {
23760                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23761                                break;
23762                            }
23763                        } catch (InterruptedException ignored) {
23764                        }
23765
23766                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23767                        final int progress = 10 + (int) MathUtils.constrain(
23768                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23769                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23770                    }
23771                }
23772            }.start();
23773
23774            final String dataAppName = codeFile.getName();
23775            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23776                    dataAppName, appId, seinfo, targetSdkVersion);
23777        } else {
23778            move = null;
23779        }
23780
23781        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23782
23783        final Message msg = mHandler.obtainMessage(INIT_COPY);
23784        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23785        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23786                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23787                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23788                PackageManager.INSTALL_REASON_UNKNOWN);
23789        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23790        msg.obj = params;
23791
23792        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23793                System.identityHashCode(msg.obj));
23794        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23795                System.identityHashCode(msg.obj));
23796
23797        mHandler.sendMessage(msg);
23798    }
23799
23800    @Override
23801    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23802        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23803
23804        final int realMoveId = mNextMoveId.getAndIncrement();
23805        final Bundle extras = new Bundle();
23806        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23807        mMoveCallbacks.notifyCreated(realMoveId, extras);
23808
23809        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23810            @Override
23811            public void onCreated(int moveId, Bundle extras) {
23812                // Ignored
23813            }
23814
23815            @Override
23816            public void onStatusChanged(int moveId, int status, long estMillis) {
23817                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23818            }
23819        };
23820
23821        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23822        storage.setPrimaryStorageUuid(volumeUuid, callback);
23823        return realMoveId;
23824    }
23825
23826    @Override
23827    public int getMoveStatus(int moveId) {
23828        mContext.enforceCallingOrSelfPermission(
23829                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23830        return mMoveCallbacks.mLastStatus.get(moveId);
23831    }
23832
23833    @Override
23834    public void registerMoveCallback(IPackageMoveObserver callback) {
23835        mContext.enforceCallingOrSelfPermission(
23836                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23837        mMoveCallbacks.register(callback);
23838    }
23839
23840    @Override
23841    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23842        mContext.enforceCallingOrSelfPermission(
23843                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23844        mMoveCallbacks.unregister(callback);
23845    }
23846
23847    @Override
23848    public boolean setInstallLocation(int loc) {
23849        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23850                null);
23851        if (getInstallLocation() == loc) {
23852            return true;
23853        }
23854        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23855                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23856            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23857                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23858            return true;
23859        }
23860        return false;
23861   }
23862
23863    @Override
23864    public int getInstallLocation() {
23865        // allow instant app access
23866        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23867                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23868                PackageHelper.APP_INSTALL_AUTO);
23869    }
23870
23871    /** Called by UserManagerService */
23872    void cleanUpUser(UserManagerService userManager, int userHandle) {
23873        synchronized (mPackages) {
23874            mDirtyUsers.remove(userHandle);
23875            mUserNeedsBadging.delete(userHandle);
23876            mSettings.removeUserLPw(userHandle);
23877            mPendingBroadcasts.remove(userHandle);
23878            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23879            removeUnusedPackagesLPw(userManager, userHandle);
23880        }
23881    }
23882
23883    /**
23884     * We're removing userHandle and would like to remove any downloaded packages
23885     * that are no longer in use by any other user.
23886     * @param userHandle the user being removed
23887     */
23888    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23889        final boolean DEBUG_CLEAN_APKS = false;
23890        int [] users = userManager.getUserIds();
23891        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23892        while (psit.hasNext()) {
23893            PackageSetting ps = psit.next();
23894            if (ps.pkg == null) {
23895                continue;
23896            }
23897            final String packageName = ps.pkg.packageName;
23898            // Skip over if system app
23899            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23900                continue;
23901            }
23902            if (DEBUG_CLEAN_APKS) {
23903                Slog.i(TAG, "Checking package " + packageName);
23904            }
23905            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23906            if (keep) {
23907                if (DEBUG_CLEAN_APKS) {
23908                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23909                }
23910            } else {
23911                for (int i = 0; i < users.length; i++) {
23912                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23913                        keep = true;
23914                        if (DEBUG_CLEAN_APKS) {
23915                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23916                                    + users[i]);
23917                        }
23918                        break;
23919                    }
23920                }
23921            }
23922            if (!keep) {
23923                if (DEBUG_CLEAN_APKS) {
23924                    Slog.i(TAG, "  Removing package " + packageName);
23925                }
23926                mHandler.post(new Runnable() {
23927                    public void run() {
23928                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23929                                userHandle, 0);
23930                    } //end run
23931                });
23932            }
23933        }
23934    }
23935
23936    /** Called by UserManagerService */
23937    void createNewUser(int userId, String[] disallowedPackages) {
23938        synchronized (mInstallLock) {
23939            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23940        }
23941        synchronized (mPackages) {
23942            scheduleWritePackageRestrictionsLocked(userId);
23943            scheduleWritePackageListLocked(userId);
23944            applyFactoryDefaultBrowserLPw(userId);
23945            primeDomainVerificationsLPw(userId);
23946        }
23947    }
23948
23949    void onNewUserCreated(final int userId) {
23950        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23951        // If permission review for legacy apps is required, we represent
23952        // dagerous permissions for such apps as always granted runtime
23953        // permissions to keep per user flag state whether review is needed.
23954        // Hence, if a new user is added we have to propagate dangerous
23955        // permission grants for these legacy apps.
23956        if (mPermissionReviewRequired) {
23957            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23958                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23959        }
23960    }
23961
23962    @Override
23963    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23964        mContext.enforceCallingOrSelfPermission(
23965                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23966                "Only package verification agents can read the verifier device identity");
23967
23968        synchronized (mPackages) {
23969            return mSettings.getVerifierDeviceIdentityLPw();
23970        }
23971    }
23972
23973    @Override
23974    public void setPermissionEnforced(String permission, boolean enforced) {
23975        // TODO: Now that we no longer change GID for storage, this should to away.
23976        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23977                "setPermissionEnforced");
23978        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23979            synchronized (mPackages) {
23980                if (mSettings.mReadExternalStorageEnforced == null
23981                        || mSettings.mReadExternalStorageEnforced != enforced) {
23982                    mSettings.mReadExternalStorageEnforced = enforced;
23983                    mSettings.writeLPr();
23984                }
23985            }
23986            // kill any non-foreground processes so we restart them and
23987            // grant/revoke the GID.
23988            final IActivityManager am = ActivityManager.getService();
23989            if (am != null) {
23990                final long token = Binder.clearCallingIdentity();
23991                try {
23992                    am.killProcessesBelowForeground("setPermissionEnforcement");
23993                } catch (RemoteException e) {
23994                } finally {
23995                    Binder.restoreCallingIdentity(token);
23996                }
23997            }
23998        } else {
23999            throw new IllegalArgumentException("No selective enforcement for " + permission);
24000        }
24001    }
24002
24003    @Override
24004    @Deprecated
24005    public boolean isPermissionEnforced(String permission) {
24006        // allow instant applications
24007        return true;
24008    }
24009
24010    @Override
24011    public boolean isStorageLow() {
24012        // allow instant applications
24013        final long token = Binder.clearCallingIdentity();
24014        try {
24015            final DeviceStorageMonitorInternal
24016                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24017            if (dsm != null) {
24018                return dsm.isMemoryLow();
24019            } else {
24020                return false;
24021            }
24022        } finally {
24023            Binder.restoreCallingIdentity(token);
24024        }
24025    }
24026
24027    @Override
24028    public IPackageInstaller getPackageInstaller() {
24029        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24030            return null;
24031        }
24032        return mInstallerService;
24033    }
24034
24035    private boolean userNeedsBadging(int userId) {
24036        int index = mUserNeedsBadging.indexOfKey(userId);
24037        if (index < 0) {
24038            final UserInfo userInfo;
24039            final long token = Binder.clearCallingIdentity();
24040            try {
24041                userInfo = sUserManager.getUserInfo(userId);
24042            } finally {
24043                Binder.restoreCallingIdentity(token);
24044            }
24045            final boolean b;
24046            if (userInfo != null && userInfo.isManagedProfile()) {
24047                b = true;
24048            } else {
24049                b = false;
24050            }
24051            mUserNeedsBadging.put(userId, b);
24052            return b;
24053        }
24054        return mUserNeedsBadging.valueAt(index);
24055    }
24056
24057    @Override
24058    public KeySet getKeySetByAlias(String packageName, String alias) {
24059        if (packageName == null || alias == null) {
24060            return null;
24061        }
24062        synchronized(mPackages) {
24063            final PackageParser.Package pkg = mPackages.get(packageName);
24064            if (pkg == null) {
24065                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24066                throw new IllegalArgumentException("Unknown package: " + packageName);
24067            }
24068            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24069            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24070                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24071                throw new IllegalArgumentException("Unknown package: " + packageName);
24072            }
24073            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24074            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24075        }
24076    }
24077
24078    @Override
24079    public KeySet getSigningKeySet(String packageName) {
24080        if (packageName == null) {
24081            return null;
24082        }
24083        synchronized(mPackages) {
24084            final int callingUid = Binder.getCallingUid();
24085            final int callingUserId = UserHandle.getUserId(callingUid);
24086            final PackageParser.Package pkg = mPackages.get(packageName);
24087            if (pkg == null) {
24088                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24089                throw new IllegalArgumentException("Unknown package: " + packageName);
24090            }
24091            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24092            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24093                // filter and pretend the package doesn't exist
24094                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24095                        + ", uid:" + callingUid);
24096                throw new IllegalArgumentException("Unknown package: " + packageName);
24097            }
24098            if (pkg.applicationInfo.uid != callingUid
24099                    && Process.SYSTEM_UID != callingUid) {
24100                throw new SecurityException("May not access signing KeySet of other apps.");
24101            }
24102            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24103            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24104        }
24105    }
24106
24107    @Override
24108    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24109        final int callingUid = Binder.getCallingUid();
24110        if (getInstantAppPackageName(callingUid) != null) {
24111            return false;
24112        }
24113        if (packageName == null || ks == null) {
24114            return false;
24115        }
24116        synchronized(mPackages) {
24117            final PackageParser.Package pkg = mPackages.get(packageName);
24118            if (pkg == null
24119                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24120                            UserHandle.getUserId(callingUid))) {
24121                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24122                throw new IllegalArgumentException("Unknown package: " + packageName);
24123            }
24124            IBinder ksh = ks.getToken();
24125            if (ksh instanceof KeySetHandle) {
24126                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24127                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24128            }
24129            return false;
24130        }
24131    }
24132
24133    @Override
24134    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24135        final int callingUid = Binder.getCallingUid();
24136        if (getInstantAppPackageName(callingUid) != null) {
24137            return false;
24138        }
24139        if (packageName == null || ks == null) {
24140            return false;
24141        }
24142        synchronized(mPackages) {
24143            final PackageParser.Package pkg = mPackages.get(packageName);
24144            if (pkg == null
24145                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24146                            UserHandle.getUserId(callingUid))) {
24147                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24148                throw new IllegalArgumentException("Unknown package: " + packageName);
24149            }
24150            IBinder ksh = ks.getToken();
24151            if (ksh instanceof KeySetHandle) {
24152                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24153                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24154            }
24155            return false;
24156        }
24157    }
24158
24159    private void deletePackageIfUnusedLPr(final String packageName) {
24160        PackageSetting ps = mSettings.mPackages.get(packageName);
24161        if (ps == null) {
24162            return;
24163        }
24164        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24165            // TODO Implement atomic delete if package is unused
24166            // It is currently possible that the package will be deleted even if it is installed
24167            // after this method returns.
24168            mHandler.post(new Runnable() {
24169                public void run() {
24170                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24171                            0, PackageManager.DELETE_ALL_USERS);
24172                }
24173            });
24174        }
24175    }
24176
24177    /**
24178     * Check and throw if the given before/after packages would be considered a
24179     * downgrade.
24180     */
24181    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24182            throws PackageManagerException {
24183        if (after.versionCode < before.mVersionCode) {
24184            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24185                    "Update version code " + after.versionCode + " is older than current "
24186                    + before.mVersionCode);
24187        } else if (after.versionCode == before.mVersionCode) {
24188            if (after.baseRevisionCode < before.baseRevisionCode) {
24189                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24190                        "Update base revision code " + after.baseRevisionCode
24191                        + " is older than current " + before.baseRevisionCode);
24192            }
24193
24194            if (!ArrayUtils.isEmpty(after.splitNames)) {
24195                for (int i = 0; i < after.splitNames.length; i++) {
24196                    final String splitName = after.splitNames[i];
24197                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24198                    if (j != -1) {
24199                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24200                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24201                                    "Update split " + splitName + " revision code "
24202                                    + after.splitRevisionCodes[i] + " is older than current "
24203                                    + before.splitRevisionCodes[j]);
24204                        }
24205                    }
24206                }
24207            }
24208        }
24209    }
24210
24211    private static class MoveCallbacks extends Handler {
24212        private static final int MSG_CREATED = 1;
24213        private static final int MSG_STATUS_CHANGED = 2;
24214
24215        private final RemoteCallbackList<IPackageMoveObserver>
24216                mCallbacks = new RemoteCallbackList<>();
24217
24218        private final SparseIntArray mLastStatus = new SparseIntArray();
24219
24220        public MoveCallbacks(Looper looper) {
24221            super(looper);
24222        }
24223
24224        public void register(IPackageMoveObserver callback) {
24225            mCallbacks.register(callback);
24226        }
24227
24228        public void unregister(IPackageMoveObserver callback) {
24229            mCallbacks.unregister(callback);
24230        }
24231
24232        @Override
24233        public void handleMessage(Message msg) {
24234            final SomeArgs args = (SomeArgs) msg.obj;
24235            final int n = mCallbacks.beginBroadcast();
24236            for (int i = 0; i < n; i++) {
24237                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24238                try {
24239                    invokeCallback(callback, msg.what, args);
24240                } catch (RemoteException ignored) {
24241                }
24242            }
24243            mCallbacks.finishBroadcast();
24244            args.recycle();
24245        }
24246
24247        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24248                throws RemoteException {
24249            switch (what) {
24250                case MSG_CREATED: {
24251                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24252                    break;
24253                }
24254                case MSG_STATUS_CHANGED: {
24255                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24256                    break;
24257                }
24258            }
24259        }
24260
24261        private void notifyCreated(int moveId, Bundle extras) {
24262            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24263
24264            final SomeArgs args = SomeArgs.obtain();
24265            args.argi1 = moveId;
24266            args.arg2 = extras;
24267            obtainMessage(MSG_CREATED, args).sendToTarget();
24268        }
24269
24270        private void notifyStatusChanged(int moveId, int status) {
24271            notifyStatusChanged(moveId, status, -1);
24272        }
24273
24274        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24275            Slog.v(TAG, "Move " + moveId + " status " + status);
24276
24277            final SomeArgs args = SomeArgs.obtain();
24278            args.argi1 = moveId;
24279            args.argi2 = status;
24280            args.arg3 = estMillis;
24281            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24282
24283            synchronized (mLastStatus) {
24284                mLastStatus.put(moveId, status);
24285            }
24286        }
24287    }
24288
24289    private final static class OnPermissionChangeListeners extends Handler {
24290        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24291
24292        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24293                new RemoteCallbackList<>();
24294
24295        public OnPermissionChangeListeners(Looper looper) {
24296            super(looper);
24297        }
24298
24299        @Override
24300        public void handleMessage(Message msg) {
24301            switch (msg.what) {
24302                case MSG_ON_PERMISSIONS_CHANGED: {
24303                    final int uid = msg.arg1;
24304                    handleOnPermissionsChanged(uid);
24305                } break;
24306            }
24307        }
24308
24309        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24310            mPermissionListeners.register(listener);
24311
24312        }
24313
24314        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24315            mPermissionListeners.unregister(listener);
24316        }
24317
24318        public void onPermissionsChanged(int uid) {
24319            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24320                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24321            }
24322        }
24323
24324        private void handleOnPermissionsChanged(int uid) {
24325            final int count = mPermissionListeners.beginBroadcast();
24326            try {
24327                for (int i = 0; i < count; i++) {
24328                    IOnPermissionsChangeListener callback = mPermissionListeners
24329                            .getBroadcastItem(i);
24330                    try {
24331                        callback.onPermissionsChanged(uid);
24332                    } catch (RemoteException e) {
24333                        Log.e(TAG, "Permission listener is dead", e);
24334                    }
24335                }
24336            } finally {
24337                mPermissionListeners.finishBroadcast();
24338            }
24339        }
24340    }
24341
24342    private class PackageManagerInternalImpl extends PackageManagerInternal {
24343        @Override
24344        public void setLocationPackagesProvider(PackagesProvider provider) {
24345            synchronized (mPackages) {
24346                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24347            }
24348        }
24349
24350        @Override
24351        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24352            synchronized (mPackages) {
24353                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24354            }
24355        }
24356
24357        @Override
24358        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24359            synchronized (mPackages) {
24360                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24361            }
24362        }
24363
24364        @Override
24365        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24366            synchronized (mPackages) {
24367                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24368            }
24369        }
24370
24371        @Override
24372        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24373            synchronized (mPackages) {
24374                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24375            }
24376        }
24377
24378        @Override
24379        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24380            synchronized (mPackages) {
24381                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24382            }
24383        }
24384
24385        @Override
24386        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24387            synchronized (mPackages) {
24388                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24389                        packageName, userId);
24390            }
24391        }
24392
24393        @Override
24394        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24395            synchronized (mPackages) {
24396                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24397                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24398                        packageName, userId);
24399            }
24400        }
24401
24402        @Override
24403        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24404            synchronized (mPackages) {
24405                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24406                        packageName, userId);
24407            }
24408        }
24409
24410        @Override
24411        public void setKeepUninstalledPackages(final List<String> packageList) {
24412            Preconditions.checkNotNull(packageList);
24413            List<String> removedFromList = null;
24414            synchronized (mPackages) {
24415                if (mKeepUninstalledPackages != null) {
24416                    final int packagesCount = mKeepUninstalledPackages.size();
24417                    for (int i = 0; i < packagesCount; i++) {
24418                        String oldPackage = mKeepUninstalledPackages.get(i);
24419                        if (packageList != null && packageList.contains(oldPackage)) {
24420                            continue;
24421                        }
24422                        if (removedFromList == null) {
24423                            removedFromList = new ArrayList<>();
24424                        }
24425                        removedFromList.add(oldPackage);
24426                    }
24427                }
24428                mKeepUninstalledPackages = new ArrayList<>(packageList);
24429                if (removedFromList != null) {
24430                    final int removedCount = removedFromList.size();
24431                    for (int i = 0; i < removedCount; i++) {
24432                        deletePackageIfUnusedLPr(removedFromList.get(i));
24433                    }
24434                }
24435            }
24436        }
24437
24438        @Override
24439        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24440            synchronized (mPackages) {
24441                // If we do not support permission review, done.
24442                if (!mPermissionReviewRequired) {
24443                    return false;
24444                }
24445
24446                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24447                if (packageSetting == null) {
24448                    return false;
24449                }
24450
24451                // Permission review applies only to apps not supporting the new permission model.
24452                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24453                    return false;
24454                }
24455
24456                // Legacy apps have the permission and get user consent on launch.
24457                PermissionsState permissionsState = packageSetting.getPermissionsState();
24458                return permissionsState.isPermissionReviewRequired(userId);
24459            }
24460        }
24461
24462        @Override
24463        public PackageInfo getPackageInfo(
24464                String packageName, int flags, int filterCallingUid, int userId) {
24465            return PackageManagerService.this
24466                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24467                            flags, filterCallingUid, userId);
24468        }
24469
24470        @Override
24471        public ApplicationInfo getApplicationInfo(
24472                String packageName, int flags, int filterCallingUid, int userId) {
24473            return PackageManagerService.this
24474                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24475        }
24476
24477        @Override
24478        public ActivityInfo getActivityInfo(
24479                ComponentName component, int flags, int filterCallingUid, int userId) {
24480            return PackageManagerService.this
24481                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24482        }
24483
24484        @Override
24485        public List<ResolveInfo> queryIntentActivities(
24486                Intent intent, int flags, int filterCallingUid, int userId) {
24487            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24488            return PackageManagerService.this
24489                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24490                            userId, false /*resolveForStart*/);
24491        }
24492
24493        @Override
24494        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24495                int userId) {
24496            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24497        }
24498
24499        @Override
24500        public void setDeviceAndProfileOwnerPackages(
24501                int deviceOwnerUserId, String deviceOwnerPackage,
24502                SparseArray<String> profileOwnerPackages) {
24503            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24504                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24505        }
24506
24507        @Override
24508        public boolean isPackageDataProtected(int userId, String packageName) {
24509            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24510        }
24511
24512        @Override
24513        public boolean isPackageEphemeral(int userId, String packageName) {
24514            synchronized (mPackages) {
24515                final PackageSetting ps = mSettings.mPackages.get(packageName);
24516                return ps != null ? ps.getInstantApp(userId) : false;
24517            }
24518        }
24519
24520        @Override
24521        public boolean wasPackageEverLaunched(String packageName, int userId) {
24522            synchronized (mPackages) {
24523                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24524            }
24525        }
24526
24527        @Override
24528        public void grantRuntimePermission(String packageName, String name, int userId,
24529                boolean overridePolicy) {
24530            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24531                    overridePolicy);
24532        }
24533
24534        @Override
24535        public void revokeRuntimePermission(String packageName, String name, int userId,
24536                boolean overridePolicy) {
24537            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24538                    overridePolicy);
24539        }
24540
24541        @Override
24542        public String getNameForUid(int uid) {
24543            return PackageManagerService.this.getNameForUid(uid);
24544        }
24545
24546        @Override
24547        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24548                Intent origIntent, String resolvedType, String callingPackage,
24549                Bundle verificationBundle, int userId) {
24550            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24551                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24552                    userId);
24553        }
24554
24555        @Override
24556        public void grantEphemeralAccess(int userId, Intent intent,
24557                int targetAppId, int ephemeralAppId) {
24558            synchronized (mPackages) {
24559                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24560                        targetAppId, ephemeralAppId);
24561            }
24562        }
24563
24564        @Override
24565        public boolean isInstantAppInstallerComponent(ComponentName component) {
24566            synchronized (mPackages) {
24567                return mInstantAppInstallerActivity != null
24568                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24569            }
24570        }
24571
24572        @Override
24573        public void pruneInstantApps() {
24574            mInstantAppRegistry.pruneInstantApps();
24575        }
24576
24577        @Override
24578        public String getSetupWizardPackageName() {
24579            return mSetupWizardPackage;
24580        }
24581
24582        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24583            if (policy != null) {
24584                mExternalSourcesPolicy = policy;
24585            }
24586        }
24587
24588        @Override
24589        public boolean isPackagePersistent(String packageName) {
24590            synchronized (mPackages) {
24591                PackageParser.Package pkg = mPackages.get(packageName);
24592                return pkg != null
24593                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24594                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24595                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24596                        : false;
24597            }
24598        }
24599
24600        @Override
24601        public List<PackageInfo> getOverlayPackages(int userId) {
24602            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24603            synchronized (mPackages) {
24604                for (PackageParser.Package p : mPackages.values()) {
24605                    if (p.mOverlayTarget != null) {
24606                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24607                        if (pkg != null) {
24608                            overlayPackages.add(pkg);
24609                        }
24610                    }
24611                }
24612            }
24613            return overlayPackages;
24614        }
24615
24616        @Override
24617        public List<String> getTargetPackageNames(int userId) {
24618            List<String> targetPackages = new ArrayList<>();
24619            synchronized (mPackages) {
24620                for (PackageParser.Package p : mPackages.values()) {
24621                    if (p.mOverlayTarget == null) {
24622                        targetPackages.add(p.packageName);
24623                    }
24624                }
24625            }
24626            return targetPackages;
24627        }
24628
24629        @Override
24630        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24631                @Nullable List<String> overlayPackageNames) {
24632            synchronized (mPackages) {
24633                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24634                    Slog.e(TAG, "failed to find package " + targetPackageName);
24635                    return false;
24636                }
24637                ArrayList<String> overlayPaths = null;
24638                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24639                    final int N = overlayPackageNames.size();
24640                    overlayPaths = new ArrayList<>(N);
24641                    for (int i = 0; i < N; i++) {
24642                        final String packageName = overlayPackageNames.get(i);
24643                        final PackageParser.Package pkg = mPackages.get(packageName);
24644                        if (pkg == null) {
24645                            Slog.e(TAG, "failed to find package " + packageName);
24646                            return false;
24647                        }
24648                        overlayPaths.add(pkg.baseCodePath);
24649                    }
24650                }
24651
24652                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24653                ps.setOverlayPaths(overlayPaths, userId);
24654                return true;
24655            }
24656        }
24657
24658        @Override
24659        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24660                int flags, int userId) {
24661            return resolveIntentInternal(
24662                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24663        }
24664
24665        @Override
24666        public ResolveInfo resolveService(Intent intent, String resolvedType,
24667                int flags, int userId, int callingUid) {
24668            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24669        }
24670
24671        @Override
24672        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24673            synchronized (mPackages) {
24674                mIsolatedOwners.put(isolatedUid, ownerUid);
24675            }
24676        }
24677
24678        @Override
24679        public void removeIsolatedUid(int isolatedUid) {
24680            synchronized (mPackages) {
24681                mIsolatedOwners.delete(isolatedUid);
24682            }
24683        }
24684
24685        @Override
24686        public int getUidTargetSdkVersion(int uid) {
24687            synchronized (mPackages) {
24688                return getUidTargetSdkVersionLockedLPr(uid);
24689            }
24690        }
24691
24692        @Override
24693        public boolean canAccessInstantApps(int callingUid, int userId) {
24694            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24695        }
24696    }
24697
24698    @Override
24699    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24700        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24701        synchronized (mPackages) {
24702            final long identity = Binder.clearCallingIdentity();
24703            try {
24704                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24705                        packageNames, userId);
24706            } finally {
24707                Binder.restoreCallingIdentity(identity);
24708            }
24709        }
24710    }
24711
24712    @Override
24713    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24714        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24715        synchronized (mPackages) {
24716            final long identity = Binder.clearCallingIdentity();
24717            try {
24718                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24719                        packageNames, userId);
24720            } finally {
24721                Binder.restoreCallingIdentity(identity);
24722            }
24723        }
24724    }
24725
24726    private static void enforceSystemOrPhoneCaller(String tag) {
24727        int callingUid = Binder.getCallingUid();
24728        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24729            throw new SecurityException(
24730                    "Cannot call " + tag + " from UID " + callingUid);
24731        }
24732    }
24733
24734    boolean isHistoricalPackageUsageAvailable() {
24735        return mPackageUsage.isHistoricalPackageUsageAvailable();
24736    }
24737
24738    /**
24739     * Return a <b>copy</b> of the collection of packages known to the package manager.
24740     * @return A copy of the values of mPackages.
24741     */
24742    Collection<PackageParser.Package> getPackages() {
24743        synchronized (mPackages) {
24744            return new ArrayList<>(mPackages.values());
24745        }
24746    }
24747
24748    /**
24749     * Logs process start information (including base APK hash) to the security log.
24750     * @hide
24751     */
24752    @Override
24753    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24754            String apkFile, int pid) {
24755        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24756            return;
24757        }
24758        if (!SecurityLog.isLoggingEnabled()) {
24759            return;
24760        }
24761        Bundle data = new Bundle();
24762        data.putLong("startTimestamp", System.currentTimeMillis());
24763        data.putString("processName", processName);
24764        data.putInt("uid", uid);
24765        data.putString("seinfo", seinfo);
24766        data.putString("apkFile", apkFile);
24767        data.putInt("pid", pid);
24768        Message msg = mProcessLoggingHandler.obtainMessage(
24769                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24770        msg.setData(data);
24771        mProcessLoggingHandler.sendMessage(msg);
24772    }
24773
24774    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24775        return mCompilerStats.getPackageStats(pkgName);
24776    }
24777
24778    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24779        return getOrCreateCompilerPackageStats(pkg.packageName);
24780    }
24781
24782    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24783        return mCompilerStats.getOrCreatePackageStats(pkgName);
24784    }
24785
24786    public void deleteCompilerPackageStats(String pkgName) {
24787        mCompilerStats.deletePackageStats(pkgName);
24788    }
24789
24790    @Override
24791    public int getInstallReason(String packageName, int userId) {
24792        final int callingUid = Binder.getCallingUid();
24793        enforceCrossUserPermission(callingUid, userId,
24794                true /* requireFullPermission */, false /* checkShell */,
24795                "get install reason");
24796        synchronized (mPackages) {
24797            final PackageSetting ps = mSettings.mPackages.get(packageName);
24798            if (filterAppAccessLPr(ps, callingUid, userId)) {
24799                return PackageManager.INSTALL_REASON_UNKNOWN;
24800            }
24801            if (ps != null) {
24802                return ps.getInstallReason(userId);
24803            }
24804        }
24805        return PackageManager.INSTALL_REASON_UNKNOWN;
24806    }
24807
24808    @Override
24809    public boolean canRequestPackageInstalls(String packageName, int userId) {
24810        return canRequestPackageInstallsInternal(packageName, 0, userId,
24811                true /* throwIfPermNotDeclared*/);
24812    }
24813
24814    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24815            boolean throwIfPermNotDeclared) {
24816        int callingUid = Binder.getCallingUid();
24817        int uid = getPackageUid(packageName, 0, userId);
24818        if (callingUid != uid && callingUid != Process.ROOT_UID
24819                && callingUid != Process.SYSTEM_UID) {
24820            throw new SecurityException(
24821                    "Caller uid " + callingUid + " does not own package " + packageName);
24822        }
24823        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24824        if (info == null) {
24825            return false;
24826        }
24827        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24828            return false;
24829        }
24830        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24831        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24832        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24833            if (throwIfPermNotDeclared) {
24834                throw new SecurityException("Need to declare " + appOpPermission
24835                        + " to call this api");
24836            } else {
24837                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24838                return false;
24839            }
24840        }
24841        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24842            return false;
24843        }
24844        if (mExternalSourcesPolicy != null) {
24845            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24846            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24847                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24848            }
24849        }
24850        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24851    }
24852
24853    @Override
24854    public ComponentName getInstantAppResolverSettingsComponent() {
24855        return mInstantAppResolverSettingsComponent;
24856    }
24857
24858    @Override
24859    public ComponentName getInstantAppInstallerComponent() {
24860        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24861            return null;
24862        }
24863        return mInstantAppInstallerActivity == null
24864                ? null : mInstantAppInstallerActivity.getComponentName();
24865    }
24866
24867    @Override
24868    public String getInstantAppAndroidId(String packageName, int userId) {
24869        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24870                "getInstantAppAndroidId");
24871        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24872                true /* requireFullPermission */, false /* checkShell */,
24873                "getInstantAppAndroidId");
24874        // Make sure the target is an Instant App.
24875        if (!isInstantApp(packageName, userId)) {
24876            return null;
24877        }
24878        synchronized (mPackages) {
24879            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24880        }
24881    }
24882}
24883
24884interface PackageSender {
24885    void sendPackageBroadcast(final String action, final String pkg,
24886        final Bundle extras, final int flags, final String targetPkg,
24887        final IIntentReceiver finishedReceiver, final int[] userIds);
24888    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24889        int appId, int... userIds);
24890}
24891