PackageManagerService.java revision a18e992770149989311c23b5222791be50b49a5d
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.IDexModuleRegisterCallback;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstantAppInfo;
146import android.content.pm.InstantAppRequest;
147import android.content.pm.InstantAppResolveInfo;
148import android.content.pm.InstrumentationInfo;
149import android.content.pm.IntentFilterVerificationInfo;
150import android.content.pm.KeySet;
151import android.content.pm.PackageCleanItem;
152import android.content.pm.PackageInfo;
153import android.content.pm.PackageInfoLite;
154import android.content.pm.PackageInstaller;
155import android.content.pm.PackageManager;
156import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
157import android.content.pm.PackageManagerInternal;
158import android.content.pm.PackageParser;
159import android.content.pm.PackageParser.ActivityIntentInfo;
160import android.content.pm.PackageParser.PackageLite;
161import android.content.pm.PackageParser.PackageParserException;
162import android.content.pm.PackageStats;
163import android.content.pm.PackageUserState;
164import android.content.pm.ParceledListSlice;
165import android.content.pm.PermissionGroupInfo;
166import android.content.pm.PermissionInfo;
167import android.content.pm.ProviderInfo;
168import android.content.pm.ResolveInfo;
169import android.content.pm.ServiceInfo;
170import android.content.pm.SharedLibraryInfo;
171import android.content.pm.Signature;
172import android.content.pm.UserInfo;
173import android.content.pm.VerifierDeviceIdentity;
174import android.content.pm.VerifierInfo;
175import android.content.pm.VersionedPackage;
176import android.content.res.Resources;
177import android.database.ContentObserver;
178import android.graphics.Bitmap;
179import android.hardware.display.DisplayManager;
180import android.net.Uri;
181import android.os.Binder;
182import android.os.Build;
183import android.os.Bundle;
184import android.os.Debug;
185import android.os.Environment;
186import android.os.Environment.UserEnvironment;
187import android.os.FileUtils;
188import android.os.Handler;
189import android.os.IBinder;
190import android.os.Looper;
191import android.os.Message;
192import android.os.Parcel;
193import android.os.ParcelFileDescriptor;
194import android.os.PatternMatcher;
195import android.os.Process;
196import android.os.RemoteCallbackList;
197import android.os.RemoteException;
198import android.os.ResultReceiver;
199import android.os.SELinux;
200import android.os.ServiceManager;
201import android.os.ShellCallback;
202import android.os.SystemClock;
203import android.os.SystemProperties;
204import android.os.Trace;
205import android.os.UserHandle;
206import android.os.UserManager;
207import android.os.UserManagerInternal;
208import android.os.storage.IStorageManager;
209import android.os.storage.StorageEventListener;
210import android.os.storage.StorageManager;
211import android.os.storage.StorageManagerInternal;
212import android.os.storage.VolumeInfo;
213import android.os.storage.VolumeRecord;
214import android.provider.Settings.Global;
215import android.provider.Settings.Secure;
216import android.security.KeyStore;
217import android.security.SystemKeyStore;
218import android.service.pm.PackageServiceDumpProto;
219import android.system.ErrnoException;
220import android.system.Os;
221import android.text.TextUtils;
222import android.text.format.DateUtils;
223import android.util.ArrayMap;
224import android.util.ArraySet;
225import android.util.Base64;
226import android.util.BootTimingsTraceLog;
227import android.util.DisplayMetrics;
228import android.util.EventLog;
229import android.util.ExceptionUtils;
230import android.util.Log;
231import android.util.LogPrinter;
232import android.util.MathUtils;
233import android.util.PackageUtils;
234import android.util.Pair;
235import android.util.PrintStreamPrinter;
236import android.util.Slog;
237import android.util.SparseArray;
238import android.util.SparseBooleanArray;
239import android.util.SparseIntArray;
240import android.util.Xml;
241import android.util.jar.StrictJarFile;
242import android.util.proto.ProtoOutputStream;
243import android.view.Display;
244
245import com.android.internal.R;
246import com.android.internal.annotations.GuardedBy;
247import com.android.internal.app.IMediaContainerService;
248import com.android.internal.app.ResolverActivity;
249import com.android.internal.content.NativeLibraryHelper;
250import com.android.internal.content.PackageHelper;
251import com.android.internal.logging.MetricsLogger;
252import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
253import com.android.internal.os.IParcelFileDescriptorFactory;
254import com.android.internal.os.RoSystemProperties;
255import com.android.internal.os.SomeArgs;
256import com.android.internal.os.Zygote;
257import com.android.internal.telephony.CarrierAppUtils;
258import com.android.internal.util.ArrayUtils;
259import com.android.internal.util.ConcurrentUtils;
260import com.android.internal.util.DumpUtils;
261import com.android.internal.util.FastPrintWriter;
262import com.android.internal.util.FastXmlSerializer;
263import com.android.internal.util.IndentingPrintWriter;
264import com.android.internal.util.Preconditions;
265import com.android.internal.util.XmlUtils;
266import com.android.server.AttributeCache;
267import com.android.server.DeviceIdleController;
268import com.android.server.EventLogTags;
269import com.android.server.FgThread;
270import com.android.server.IntentResolver;
271import com.android.server.LocalServices;
272import com.android.server.LockGuard;
273import com.android.server.ServiceThread;
274import com.android.server.SystemConfig;
275import com.android.server.SystemServerInitThreadPool;
276import com.android.server.Watchdog;
277import com.android.server.net.NetworkPolicyManagerInternal;
278import com.android.server.pm.Installer.InstallerException;
279import com.android.server.pm.PermissionsState.PermissionState;
280import com.android.server.pm.Settings.DatabaseVersion;
281import com.android.server.pm.Settings.VersionInfo;
282import com.android.server.pm.dex.DexManager;
283import com.android.server.pm.dex.DexoptOptions;
284import com.android.server.pm.dex.PackageDexUsage;
285import com.android.server.storage.DeviceStorageMonitorInternal;
286
287import dalvik.system.CloseGuard;
288import dalvik.system.DexFile;
289import dalvik.system.VMRuntime;
290
291import libcore.io.IoUtils;
292import libcore.util.EmptyArray;
293
294import org.xmlpull.v1.XmlPullParser;
295import org.xmlpull.v1.XmlPullParserException;
296import org.xmlpull.v1.XmlSerializer;
297
298import java.io.BufferedOutputStream;
299import java.io.BufferedReader;
300import java.io.ByteArrayInputStream;
301import java.io.ByteArrayOutputStream;
302import java.io.File;
303import java.io.FileDescriptor;
304import java.io.FileInputStream;
305import java.io.FileOutputStream;
306import java.io.FileReader;
307import java.io.FilenameFilter;
308import java.io.IOException;
309import java.io.PrintWriter;
310import java.lang.annotation.Retention;
311import java.lang.annotation.RetentionPolicy;
312import java.nio.charset.StandardCharsets;
313import java.security.DigestInputStream;
314import java.security.MessageDigest;
315import java.security.NoSuchAlgorithmException;
316import java.security.PublicKey;
317import java.security.SecureRandom;
318import java.security.cert.Certificate;
319import java.security.cert.CertificateEncodingException;
320import java.security.cert.CertificateException;
321import java.text.SimpleDateFormat;
322import java.util.ArrayList;
323import java.util.Arrays;
324import java.util.Collection;
325import java.util.Collections;
326import java.util.Comparator;
327import java.util.Date;
328import java.util.HashMap;
329import java.util.HashSet;
330import java.util.Iterator;
331import java.util.LinkedHashSet;
332import java.util.List;
333import java.util.Map;
334import java.util.Objects;
335import java.util.Set;
336import java.util.concurrent.CountDownLatch;
337import java.util.concurrent.Future;
338import java.util.concurrent.TimeUnit;
339import java.util.concurrent.atomic.AtomicBoolean;
340import java.util.concurrent.atomic.AtomicInteger;
341
342/**
343 * Keep track of all those APKs everywhere.
344 * <p>
345 * Internally there are two important locks:
346 * <ul>
347 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
348 * and other related state. It is a fine-grained lock that should only be held
349 * momentarily, as it's one of the most contended locks in the system.
350 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
351 * operations typically involve heavy lifting of application data on disk. Since
352 * {@code installd} is single-threaded, and it's operations can often be slow,
353 * this lock should never be acquired while already holding {@link #mPackages}.
354 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
355 * holding {@link #mInstallLock}.
356 * </ul>
357 * Many internal methods rely on the caller to hold the appropriate locks, and
358 * this contract is expressed through method name suffixes:
359 * <ul>
360 * <li>fooLI(): the caller must hold {@link #mInstallLock}
361 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
362 * being modified must be frozen
363 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
364 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
365 * </ul>
366 * <p>
367 * Because this class is very central to the platform's security; please run all
368 * CTS and unit tests whenever making modifications:
369 *
370 * <pre>
371 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
372 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
373 * </pre>
374 */
375public class PackageManagerService extends IPackageManager.Stub
376        implements PackageSender {
377    static final String TAG = "PackageManager";
378    static final boolean DEBUG_SETTINGS = false;
379    static final boolean DEBUG_PREFERRED = false;
380    static final boolean DEBUG_UPGRADE = false;
381    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
382    private static final boolean DEBUG_BACKUP = false;
383    private static final boolean DEBUG_INSTALL = false;
384    private static final boolean DEBUG_REMOVE = false;
385    private static final boolean DEBUG_BROADCASTS = false;
386    private static final boolean DEBUG_SHOW_INFO = false;
387    private static final boolean DEBUG_PACKAGE_INFO = false;
388    private static final boolean DEBUG_INTENT_MATCHING = false;
389    private static final boolean DEBUG_PACKAGE_SCANNING = false;
390    private static final boolean DEBUG_VERIFY = false;
391    private static final boolean DEBUG_FILTERS = false;
392    private static final boolean DEBUG_PERMISSIONS = false;
393    private static final boolean DEBUG_SHARED_LIBRARIES = false;
394
395    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
396    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
397    // user, but by default initialize to this.
398    public static final boolean DEBUG_DEXOPT = false;
399
400    private static final boolean DEBUG_ABI_SELECTION = false;
401    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
402    private static final boolean DEBUG_TRIAGED_MISSING = false;
403    private static final boolean DEBUG_APP_DATA = false;
404
405    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
406    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
407
408    private static final boolean HIDE_EPHEMERAL_APIS = false;
409
410    private static final boolean ENABLE_FREE_CACHE_V2 =
411            SystemProperties.getBoolean("fw.free_cache_v2", true);
412
413    private static final int RADIO_UID = Process.PHONE_UID;
414    private static final int LOG_UID = Process.LOG_UID;
415    private static final int NFC_UID = Process.NFC_UID;
416    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
417    private static final int SHELL_UID = Process.SHELL_UID;
418
419    // Cap the size of permission trees that 3rd party apps can define
420    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
421
422    // Suffix used during package installation when copying/moving
423    // package apks to install directory.
424    private static final String INSTALL_PACKAGE_SUFFIX = "-";
425
426    static final int SCAN_NO_DEX = 1<<1;
427    static final int SCAN_FORCE_DEX = 1<<2;
428    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
429    static final int SCAN_NEW_INSTALL = 1<<4;
430    static final int SCAN_UPDATE_TIME = 1<<5;
431    static final int SCAN_BOOTING = 1<<6;
432    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
433    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
434    static final int SCAN_REPLACING = 1<<9;
435    static final int SCAN_REQUIRE_KNOWN = 1<<10;
436    static final int SCAN_MOVE = 1<<11;
437    static final int SCAN_INITIAL = 1<<12;
438    static final int SCAN_CHECK_ONLY = 1<<13;
439    static final int SCAN_DONT_KILL_APP = 1<<14;
440    static final int SCAN_IGNORE_FROZEN = 1<<15;
441    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
442    static final int SCAN_AS_INSTANT_APP = 1<<17;
443    static final int SCAN_AS_FULL_APP = 1<<18;
444    /** Should not be with the scan flags */
445    static final int FLAGS_REMOVE_CHATTY = 1<<31;
446
447    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
448
449    private static final int[] EMPTY_INT_ARRAY = new int[0];
450
451    private static final int TYPE_UNKNOWN = 0;
452    private static final int TYPE_ACTIVITY = 1;
453    private static final int TYPE_RECEIVER = 2;
454    private static final int TYPE_SERVICE = 3;
455    private static final int TYPE_PROVIDER = 4;
456    @IntDef(prefix = { "TYPE_" }, value = {
457            TYPE_UNKNOWN,
458            TYPE_ACTIVITY,
459            TYPE_RECEIVER,
460            TYPE_SERVICE,
461            TYPE_PROVIDER,
462    })
463    @Retention(RetentionPolicy.SOURCE)
464    public @interface ComponentType {}
465
466    /**
467     * Timeout (in milliseconds) after which the watchdog should declare that
468     * our handler thread is wedged.  The usual default for such things is one
469     * minute but we sometimes do very lengthy I/O operations on this thread,
470     * such as installing multi-gigabyte applications, so ours needs to be longer.
471     */
472    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
473
474    /**
475     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
476     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
477     * settings entry if available, otherwise we use the hardcoded default.  If it's been
478     * more than this long since the last fstrim, we force one during the boot sequence.
479     *
480     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
481     * one gets run at the next available charging+idle time.  This final mandatory
482     * no-fstrim check kicks in only of the other scheduling criteria is never met.
483     */
484    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
485
486    /**
487     * Whether verification is enabled by default.
488     */
489    private static final boolean DEFAULT_VERIFY_ENABLE = true;
490
491    /**
492     * The default maximum time to wait for the verification agent to return in
493     * milliseconds.
494     */
495    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
496
497    /**
498     * The default response for package verification timeout.
499     *
500     * This can be either PackageManager.VERIFICATION_ALLOW or
501     * PackageManager.VERIFICATION_REJECT.
502     */
503    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
504
505    static final String PLATFORM_PACKAGE_NAME = "android";
506
507    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
508
509    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
510            DEFAULT_CONTAINER_PACKAGE,
511            "com.android.defcontainer.DefaultContainerService");
512
513    private static final String KILL_APP_REASON_GIDS_CHANGED =
514            "permission grant or revoke changed gids";
515
516    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
517            "permissions revoked";
518
519    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
520
521    private static final String PACKAGE_SCHEME = "package";
522
523    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
524
525    /** Permission grant: not grant the permission. */
526    private static final int GRANT_DENIED = 1;
527
528    /** Permission grant: grant the permission as an install permission. */
529    private static final int GRANT_INSTALL = 2;
530
531    /** Permission grant: grant the permission as a runtime one. */
532    private static final int GRANT_RUNTIME = 3;
533
534    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
535    private static final int GRANT_UPGRADE = 4;
536
537    /** Canonical intent used to identify what counts as a "web browser" app */
538    private static final Intent sBrowserIntent;
539    static {
540        sBrowserIntent = new Intent();
541        sBrowserIntent.setAction(Intent.ACTION_VIEW);
542        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
543        sBrowserIntent.setData(Uri.parse("http:"));
544    }
545
546    /**
547     * The set of all protected actions [i.e. those actions for which a high priority
548     * intent filter is disallowed].
549     */
550    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
551    static {
552        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
553        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
554        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
555        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
556    }
557
558    // Compilation reasons.
559    public static final int REASON_FIRST_BOOT = 0;
560    public static final int REASON_BOOT = 1;
561    public static final int REASON_INSTALL = 2;
562    public static final int REASON_BACKGROUND_DEXOPT = 3;
563    public static final int REASON_AB_OTA = 4;
564    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
565
566    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
567
568    /** All dangerous permission names in the same order as the events in MetricsEvent */
569    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
570            Manifest.permission.READ_CALENDAR,
571            Manifest.permission.WRITE_CALENDAR,
572            Manifest.permission.CAMERA,
573            Manifest.permission.READ_CONTACTS,
574            Manifest.permission.WRITE_CONTACTS,
575            Manifest.permission.GET_ACCOUNTS,
576            Manifest.permission.ACCESS_FINE_LOCATION,
577            Manifest.permission.ACCESS_COARSE_LOCATION,
578            Manifest.permission.RECORD_AUDIO,
579            Manifest.permission.READ_PHONE_STATE,
580            Manifest.permission.CALL_PHONE,
581            Manifest.permission.READ_CALL_LOG,
582            Manifest.permission.WRITE_CALL_LOG,
583            Manifest.permission.ADD_VOICEMAIL,
584            Manifest.permission.USE_SIP,
585            Manifest.permission.PROCESS_OUTGOING_CALLS,
586            Manifest.permission.READ_CELL_BROADCASTS,
587            Manifest.permission.BODY_SENSORS,
588            Manifest.permission.SEND_SMS,
589            Manifest.permission.RECEIVE_SMS,
590            Manifest.permission.READ_SMS,
591            Manifest.permission.RECEIVE_WAP_PUSH,
592            Manifest.permission.RECEIVE_MMS,
593            Manifest.permission.READ_EXTERNAL_STORAGE,
594            Manifest.permission.WRITE_EXTERNAL_STORAGE,
595            Manifest.permission.READ_PHONE_NUMBERS,
596            Manifest.permission.ANSWER_PHONE_CALLS);
597
598
599    /**
600     * Version number for the package parser cache. Increment this whenever the format or
601     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
602     */
603    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
604
605    /**
606     * Whether the package parser cache is enabled.
607     */
608    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
609
610    final ServiceThread mHandlerThread;
611
612    final PackageHandler mHandler;
613
614    private final ProcessLoggingHandler mProcessLoggingHandler;
615
616    /**
617     * Messages for {@link #mHandler} that need to wait for system ready before
618     * being dispatched.
619     */
620    private ArrayList<Message> mPostSystemReadyMessages;
621
622    final int mSdkVersion = Build.VERSION.SDK_INT;
623
624    final Context mContext;
625    final boolean mFactoryTest;
626    final boolean mOnlyCore;
627    final DisplayMetrics mMetrics;
628    final int mDefParseFlags;
629    final String[] mSeparateProcesses;
630    final boolean mIsUpgrade;
631    final boolean mIsPreNUpgrade;
632    final boolean mIsPreNMR1Upgrade;
633
634    // Have we told the Activity Manager to whitelist the default container service by uid yet?
635    @GuardedBy("mPackages")
636    boolean mDefaultContainerWhitelisted = false;
637
638    @GuardedBy("mPackages")
639    private boolean mDexOptDialogShown;
640
641    /** The location for ASEC container files on internal storage. */
642    final String mAsecInternalPath;
643
644    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
645    // LOCK HELD.  Can be called with mInstallLock held.
646    @GuardedBy("mInstallLock")
647    final Installer mInstaller;
648
649    /** Directory where installed third-party apps stored */
650    final File mAppInstallDir;
651
652    /**
653     * Directory to which applications installed internally have their
654     * 32 bit native libraries copied.
655     */
656    private File mAppLib32InstallDir;
657
658    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
659    // apps.
660    final File mDrmAppPrivateInstallDir;
661
662    // ----------------------------------------------------------------
663
664    // Lock for state used when installing and doing other long running
665    // operations.  Methods that must be called with this lock held have
666    // the suffix "LI".
667    final Object mInstallLock = new Object();
668
669    // ----------------------------------------------------------------
670
671    // Keys are String (package name), values are Package.  This also serves
672    // as the lock for the global state.  Methods that must be called with
673    // this lock held have the prefix "LP".
674    @GuardedBy("mPackages")
675    final ArrayMap<String, PackageParser.Package> mPackages =
676            new ArrayMap<String, PackageParser.Package>();
677
678    final ArrayMap<String, Set<String>> mKnownCodebase =
679            new ArrayMap<String, Set<String>>();
680
681    // Keys are isolated uids and values are the uid of the application
682    // that created the isolated proccess.
683    @GuardedBy("mPackages")
684    final SparseIntArray mIsolatedOwners = new SparseIntArray();
685
686    /**
687     * Tracks new system packages [received in an OTA] that we expect to
688     * find updated user-installed versions. Keys are package name, values
689     * are package location.
690     */
691    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
692    /**
693     * Tracks high priority intent filters for protected actions. During boot, certain
694     * filter actions are protected and should never be allowed to have a high priority
695     * intent filter for them. However, there is one, and only one exception -- the
696     * setup wizard. It must be able to define a high priority intent filter for these
697     * actions to ensure there are no escapes from the wizard. We need to delay processing
698     * of these during boot as we need to look at all of the system packages in order
699     * to know which component is the setup wizard.
700     */
701    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
702    /**
703     * Whether or not processing protected filters should be deferred.
704     */
705    private boolean mDeferProtectedFilters = true;
706
707    /**
708     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
709     */
710    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
711    /**
712     * Whether or not system app permissions should be promoted from install to runtime.
713     */
714    boolean mPromoteSystemApps;
715
716    @GuardedBy("mPackages")
717    final Settings mSettings;
718
719    /**
720     * Set of package names that are currently "frozen", which means active
721     * surgery is being done on the code/data for that package. The platform
722     * will refuse to launch frozen packages to avoid race conditions.
723     *
724     * @see PackageFreezer
725     */
726    @GuardedBy("mPackages")
727    final ArraySet<String> mFrozenPackages = new ArraySet<>();
728
729    final ProtectedPackages mProtectedPackages;
730
731    boolean mFirstBoot;
732
733    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
734
735    // System configuration read by SystemConfig.
736    final int[] mGlobalGids;
737    final SparseArray<ArraySet<String>> mSystemPermissions;
738    @GuardedBy("mAvailableFeatures")
739    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
740
741    // If mac_permissions.xml was found for seinfo labeling.
742    boolean mFoundPolicyFile;
743
744    private final InstantAppRegistry mInstantAppRegistry;
745
746    @GuardedBy("mPackages")
747    int mChangedPackagesSequenceNumber;
748    /**
749     * List of changed [installed, removed or updated] packages.
750     * mapping from user id -> sequence number -> package name
751     */
752    @GuardedBy("mPackages")
753    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
754    /**
755     * The sequence number of the last change to a package.
756     * mapping from user id -> package name -> sequence number
757     */
758    @GuardedBy("mPackages")
759    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
760
761    class PackageParserCallback implements PackageParser.Callback {
762        @Override public final boolean hasFeature(String feature) {
763            return PackageManagerService.this.hasSystemFeature(feature, 0);
764        }
765
766        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
767                Collection<PackageParser.Package> allPackages, String targetPackageName) {
768            List<PackageParser.Package> overlayPackages = null;
769            for (PackageParser.Package p : allPackages) {
770                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
771                    if (overlayPackages == null) {
772                        overlayPackages = new ArrayList<PackageParser.Package>();
773                    }
774                    overlayPackages.add(p);
775                }
776            }
777            if (overlayPackages != null) {
778                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
779                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
780                        return p1.mOverlayPriority - p2.mOverlayPriority;
781                    }
782                };
783                Collections.sort(overlayPackages, cmp);
784            }
785            return overlayPackages;
786        }
787
788        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
789                String targetPackageName, String targetPath) {
790            if ("android".equals(targetPackageName)) {
791                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
792                // native AssetManager.
793                return null;
794            }
795            List<PackageParser.Package> overlayPackages =
796                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
797            if (overlayPackages == null || overlayPackages.isEmpty()) {
798                return null;
799            }
800            List<String> overlayPathList = null;
801            for (PackageParser.Package overlayPackage : overlayPackages) {
802                if (targetPath == null) {
803                    if (overlayPathList == null) {
804                        overlayPathList = new ArrayList<String>();
805                    }
806                    overlayPathList.add(overlayPackage.baseCodePath);
807                    continue;
808                }
809
810                try {
811                    // Creates idmaps for system to parse correctly the Android manifest of the
812                    // target package.
813                    //
814                    // OverlayManagerService will update each of them with a correct gid from its
815                    // target package app id.
816                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
817                            UserHandle.getSharedAppGid(
818                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
819                    if (overlayPathList == null) {
820                        overlayPathList = new ArrayList<String>();
821                    }
822                    overlayPathList.add(overlayPackage.baseCodePath);
823                } catch (InstallerException e) {
824                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
825                            overlayPackage.baseCodePath);
826                }
827            }
828            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
829        }
830
831        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
832            synchronized (mPackages) {
833                return getStaticOverlayPathsLocked(
834                        mPackages.values(), targetPackageName, targetPath);
835            }
836        }
837
838        @Override public final String[] getOverlayApks(String targetPackageName) {
839            return getStaticOverlayPaths(targetPackageName, null);
840        }
841
842        @Override public final String[] getOverlayPaths(String targetPackageName,
843                String targetPath) {
844            return getStaticOverlayPaths(targetPackageName, targetPath);
845        }
846    };
847
848    class ParallelPackageParserCallback extends PackageParserCallback {
849        List<PackageParser.Package> mOverlayPackages = null;
850
851        void findStaticOverlayPackages() {
852            synchronized (mPackages) {
853                for (PackageParser.Package p : mPackages.values()) {
854                    if (p.mIsStaticOverlay) {
855                        if (mOverlayPackages == null) {
856                            mOverlayPackages = new ArrayList<PackageParser.Package>();
857                        }
858                        mOverlayPackages.add(p);
859                    }
860                }
861            }
862        }
863
864        @Override
865        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
866            // We can trust mOverlayPackages without holding mPackages because package uninstall
867            // can't happen while running parallel parsing.
868            // Moreover holding mPackages on each parsing thread causes dead-lock.
869            return mOverlayPackages == null ? null :
870                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
871        }
872    }
873
874    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
875    final ParallelPackageParserCallback mParallelPackageParserCallback =
876            new ParallelPackageParserCallback();
877
878    public static final class SharedLibraryEntry {
879        public final @Nullable String path;
880        public final @Nullable String apk;
881        public final @NonNull SharedLibraryInfo info;
882
883        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
884                String declaringPackageName, int declaringPackageVersionCode) {
885            path = _path;
886            apk = _apk;
887            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
888                    declaringPackageName, declaringPackageVersionCode), null);
889        }
890    }
891
892    // Currently known shared libraries.
893    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
895            new ArrayMap<>();
896
897    // All available activities, for your resolving pleasure.
898    final ActivityIntentResolver mActivities =
899            new ActivityIntentResolver();
900
901    // All available receivers, for your resolving pleasure.
902    final ActivityIntentResolver mReceivers =
903            new ActivityIntentResolver();
904
905    // All available services, for your resolving pleasure.
906    final ServiceIntentResolver mServices = new ServiceIntentResolver();
907
908    // All available providers, for your resolving pleasure.
909    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
910
911    // Mapping from provider base names (first directory in content URI codePath)
912    // to the provider information.
913    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
914            new ArrayMap<String, PackageParser.Provider>();
915
916    // Mapping from instrumentation class names to info about them.
917    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
918            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
919
920    // Mapping from permission names to info about them.
921    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
922            new ArrayMap<String, PackageParser.PermissionGroup>();
923
924    // Packages whose data we have transfered into another package, thus
925    // should no longer exist.
926    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
927
928    // Broadcast actions that are only available to the system.
929    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
930
931    /** List of packages waiting for verification. */
932    final SparseArray<PackageVerificationState> mPendingVerification
933            = new SparseArray<PackageVerificationState>();
934
935    /** Set of packages associated with each app op permission. */
936    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
937
938    final PackageInstallerService mInstallerService;
939
940    private final PackageDexOptimizer mPackageDexOptimizer;
941    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
942    // is used by other apps).
943    private final DexManager mDexManager;
944
945    private AtomicInteger mNextMoveId = new AtomicInteger();
946    private final MoveCallbacks mMoveCallbacks;
947
948    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
949
950    // Cache of users who need badging.
951    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
952
953    /** Token for keys in mPendingVerification. */
954    private int mPendingVerificationToken = 0;
955
956    volatile boolean mSystemReady;
957    volatile boolean mSafeMode;
958    volatile boolean mHasSystemUidErrors;
959    private volatile boolean mEphemeralAppsDisabled;
960
961    ApplicationInfo mAndroidApplication;
962    final ActivityInfo mResolveActivity = new ActivityInfo();
963    final ResolveInfo mResolveInfo = new ResolveInfo();
964    ComponentName mResolveComponentName;
965    PackageParser.Package mPlatformPackage;
966    ComponentName mCustomResolverComponentName;
967
968    boolean mResolverReplaced = false;
969
970    private final @Nullable ComponentName mIntentFilterVerifierComponent;
971    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
972
973    private int mIntentFilterVerificationToken = 0;
974
975    /** The service connection to the ephemeral resolver */
976    final EphemeralResolverConnection mInstantAppResolverConnection;
977    /** Component used to show resolver settings for Instant Apps */
978    final ComponentName mInstantAppResolverSettingsComponent;
979
980    /** Activity used to install instant applications */
981    ActivityInfo mInstantAppInstallerActivity;
982    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
983
984    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
985            = new SparseArray<IntentFilterVerificationState>();
986
987    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
988
989    // List of packages names to keep cached, even if they are uninstalled for all users
990    private List<String> mKeepUninstalledPackages;
991
992    private UserManagerInternal mUserManagerInternal;
993
994    private DeviceIdleController.LocalService mDeviceIdleController;
995
996    private File mCacheDir;
997
998    private ArraySet<String> mPrivappPermissionsViolations;
999
1000    private Future<?> mPrepareAppDataFuture;
1001
1002    private static class IFVerificationParams {
1003        PackageParser.Package pkg;
1004        boolean replacing;
1005        int userId;
1006        int verifierUid;
1007
1008        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1009                int _userId, int _verifierUid) {
1010            pkg = _pkg;
1011            replacing = _replacing;
1012            userId = _userId;
1013            replacing = _replacing;
1014            verifierUid = _verifierUid;
1015        }
1016    }
1017
1018    private interface IntentFilterVerifier<T extends IntentFilter> {
1019        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1020                                               T filter, String packageName);
1021        void startVerifications(int userId);
1022        void receiveVerificationResponse(int verificationId);
1023    }
1024
1025    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1026        private Context mContext;
1027        private ComponentName mIntentFilterVerifierComponent;
1028        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1029
1030        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1031            mContext = context;
1032            mIntentFilterVerifierComponent = verifierComponent;
1033        }
1034
1035        private String getDefaultScheme() {
1036            return IntentFilter.SCHEME_HTTPS;
1037        }
1038
1039        @Override
1040        public void startVerifications(int userId) {
1041            // Launch verifications requests
1042            int count = mCurrentIntentFilterVerifications.size();
1043            for (int n=0; n<count; n++) {
1044                int verificationId = mCurrentIntentFilterVerifications.get(n);
1045                final IntentFilterVerificationState ivs =
1046                        mIntentFilterVerificationStates.get(verificationId);
1047
1048                String packageName = ivs.getPackageName();
1049
1050                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1051                final int filterCount = filters.size();
1052                ArraySet<String> domainsSet = new ArraySet<>();
1053                for (int m=0; m<filterCount; m++) {
1054                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1055                    domainsSet.addAll(filter.getHostsList());
1056                }
1057                synchronized (mPackages) {
1058                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1059                            packageName, domainsSet) != null) {
1060                        scheduleWriteSettingsLocked();
1061                    }
1062                }
1063                sendVerificationRequest(userId, verificationId, ivs);
1064            }
1065            mCurrentIntentFilterVerifications.clear();
1066        }
1067
1068        private void sendVerificationRequest(int userId, int verificationId,
1069                IntentFilterVerificationState ivs) {
1070
1071            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1072            verificationIntent.putExtra(
1073                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1074                    verificationId);
1075            verificationIntent.putExtra(
1076                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1077                    getDefaultScheme());
1078            verificationIntent.putExtra(
1079                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1080                    ivs.getHostsString());
1081            verificationIntent.putExtra(
1082                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1083                    ivs.getPackageName());
1084            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1085            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1086
1087            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1088            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1089                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1090                    userId, false, "intent filter verifier");
1091
1092            UserHandle user = new UserHandle(userId);
1093            mContext.sendBroadcastAsUser(verificationIntent, user);
1094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1095                    "Sending IntentFilter verification broadcast");
1096        }
1097
1098        public void receiveVerificationResponse(int verificationId) {
1099            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1100
1101            final boolean verified = ivs.isVerified();
1102
1103            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1104            final int count = filters.size();
1105            if (DEBUG_DOMAIN_VERIFICATION) {
1106                Slog.i(TAG, "Received verification response " + verificationId
1107                        + " for " + count + " filters, verified=" + verified);
1108            }
1109            for (int n=0; n<count; n++) {
1110                PackageParser.ActivityIntentInfo filter = filters.get(n);
1111                filter.setVerified(verified);
1112
1113                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1114                        + " verified with result:" + verified + " and hosts:"
1115                        + ivs.getHostsString());
1116            }
1117
1118            mIntentFilterVerificationStates.remove(verificationId);
1119
1120            final String packageName = ivs.getPackageName();
1121            IntentFilterVerificationInfo ivi = null;
1122
1123            synchronized (mPackages) {
1124                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1125            }
1126            if (ivi == null) {
1127                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1128                        + verificationId + " packageName:" + packageName);
1129                return;
1130            }
1131            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1132                    "Updating IntentFilterVerificationInfo for package " + packageName
1133                            +" verificationId:" + verificationId);
1134
1135            synchronized (mPackages) {
1136                if (verified) {
1137                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1138                } else {
1139                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1140                }
1141                scheduleWriteSettingsLocked();
1142
1143                final int userId = ivs.getUserId();
1144                if (userId != UserHandle.USER_ALL) {
1145                    final int userStatus =
1146                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1147
1148                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1149                    boolean needUpdate = false;
1150
1151                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1152                    // already been set by the User thru the Disambiguation dialog
1153                    switch (userStatus) {
1154                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1155                            if (verified) {
1156                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1157                            } else {
1158                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1159                            }
1160                            needUpdate = true;
1161                            break;
1162
1163                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1164                            if (verified) {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1166                                needUpdate = true;
1167                            }
1168                            break;
1169
1170                        default:
1171                            // Nothing to do
1172                    }
1173
1174                    if (needUpdate) {
1175                        mSettings.updateIntentFilterVerificationStatusLPw(
1176                                packageName, updatedStatus, userId);
1177                        scheduleWritePackageRestrictionsLocked(userId);
1178                    }
1179                }
1180            }
1181        }
1182
1183        @Override
1184        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1185                    ActivityIntentInfo filter, String packageName) {
1186            if (!hasValidDomains(filter)) {
1187                return false;
1188            }
1189            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1190            if (ivs == null) {
1191                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1192                        packageName);
1193            }
1194            if (DEBUG_DOMAIN_VERIFICATION) {
1195                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1196            }
1197            ivs.addFilter(filter);
1198            return true;
1199        }
1200
1201        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1202                int userId, int verificationId, String packageName) {
1203            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1204                    verifierUid, userId, packageName);
1205            ivs.setPendingState();
1206            synchronized (mPackages) {
1207                mIntentFilterVerificationStates.append(verificationId, ivs);
1208                mCurrentIntentFilterVerifications.add(verificationId);
1209            }
1210            return ivs;
1211        }
1212    }
1213
1214    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1215        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1216                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1217                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1218    }
1219
1220    // Set of pending broadcasts for aggregating enable/disable of components.
1221    static class PendingPackageBroadcasts {
1222        // for each user id, a map of <package name -> components within that package>
1223        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1224
1225        public PendingPackageBroadcasts() {
1226            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1227        }
1228
1229        public ArrayList<String> get(int userId, String packageName) {
1230            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231            return packages.get(packageName);
1232        }
1233
1234        public void put(int userId, String packageName, ArrayList<String> components) {
1235            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1236            packages.put(packageName, components);
1237        }
1238
1239        public void remove(int userId, String packageName) {
1240            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1241            if (packages != null) {
1242                packages.remove(packageName);
1243            }
1244        }
1245
1246        public void remove(int userId) {
1247            mUidMap.remove(userId);
1248        }
1249
1250        public int userIdCount() {
1251            return mUidMap.size();
1252        }
1253
1254        public int userIdAt(int n) {
1255            return mUidMap.keyAt(n);
1256        }
1257
1258        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1259            return mUidMap.get(userId);
1260        }
1261
1262        public int size() {
1263            // total number of pending broadcast entries across all userIds
1264            int num = 0;
1265            for (int i = 0; i< mUidMap.size(); i++) {
1266                num += mUidMap.valueAt(i).size();
1267            }
1268            return num;
1269        }
1270
1271        public void clear() {
1272            mUidMap.clear();
1273        }
1274
1275        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1276            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1277            if (map == null) {
1278                map = new ArrayMap<String, ArrayList<String>>();
1279                mUidMap.put(userId, map);
1280            }
1281            return map;
1282        }
1283    }
1284    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1285
1286    // Service Connection to remote media container service to copy
1287    // package uri's from external media onto secure containers
1288    // or internal storage.
1289    private IMediaContainerService mContainerService = null;
1290
1291    static final int SEND_PENDING_BROADCAST = 1;
1292    static final int MCS_BOUND = 3;
1293    static final int END_COPY = 4;
1294    static final int INIT_COPY = 5;
1295    static final int MCS_UNBIND = 6;
1296    static final int START_CLEANING_PACKAGE = 7;
1297    static final int FIND_INSTALL_LOC = 8;
1298    static final int POST_INSTALL = 9;
1299    static final int MCS_RECONNECT = 10;
1300    static final int MCS_GIVE_UP = 11;
1301    static final int UPDATED_MEDIA_STATUS = 12;
1302    static final int WRITE_SETTINGS = 13;
1303    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1304    static final int PACKAGE_VERIFIED = 15;
1305    static final int CHECK_PENDING_VERIFICATION = 16;
1306    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1307    static final int INTENT_FILTER_VERIFIED = 18;
1308    static final int WRITE_PACKAGE_LIST = 19;
1309    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1310
1311    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1312
1313    // Delay time in millisecs
1314    static final int BROADCAST_DELAY = 10 * 1000;
1315
1316    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1317            2 * 60 * 60 * 1000L; /* two hours */
1318
1319    static UserManagerService sUserManager;
1320
1321    // Stores a list of users whose package restrictions file needs to be updated
1322    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1323
1324    final private DefaultContainerConnection mDefContainerConn =
1325            new DefaultContainerConnection();
1326    class DefaultContainerConnection implements ServiceConnection {
1327        public void onServiceConnected(ComponentName name, IBinder service) {
1328            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1329            final IMediaContainerService imcs = IMediaContainerService.Stub
1330                    .asInterface(Binder.allowBlocking(service));
1331            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1332        }
1333
1334        public void onServiceDisconnected(ComponentName name) {
1335            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1336        }
1337    }
1338
1339    // Recordkeeping of restore-after-install operations that are currently in flight
1340    // between the Package Manager and the Backup Manager
1341    static class PostInstallData {
1342        public InstallArgs args;
1343        public PackageInstalledInfo res;
1344
1345        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1346            args = _a;
1347            res = _r;
1348        }
1349    }
1350
1351    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1352    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1353
1354    // XML tags for backup/restore of various bits of state
1355    private static final String TAG_PREFERRED_BACKUP = "pa";
1356    private static final String TAG_DEFAULT_APPS = "da";
1357    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1358
1359    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1360    private static final String TAG_ALL_GRANTS = "rt-grants";
1361    private static final String TAG_GRANT = "grant";
1362    private static final String ATTR_PACKAGE_NAME = "pkg";
1363
1364    private static final String TAG_PERMISSION = "perm";
1365    private static final String ATTR_PERMISSION_NAME = "name";
1366    private static final String ATTR_IS_GRANTED = "g";
1367    private static final String ATTR_USER_SET = "set";
1368    private static final String ATTR_USER_FIXED = "fixed";
1369    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1370
1371    // System/policy permission grants are not backed up
1372    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1373            FLAG_PERMISSION_POLICY_FIXED
1374            | FLAG_PERMISSION_SYSTEM_FIXED
1375            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1376
1377    // And we back up these user-adjusted states
1378    private static final int USER_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_USER_SET
1380            | FLAG_PERMISSION_USER_FIXED
1381            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1382
1383    final @Nullable String mRequiredVerifierPackage;
1384    final @NonNull String mRequiredInstallerPackage;
1385    final @NonNull String mRequiredUninstallerPackage;
1386    final @Nullable String mSetupWizardPackage;
1387    final @Nullable String mStorageManagerPackage;
1388    final @NonNull String mServicesSystemSharedLibraryPackageName;
1389    final @NonNull String mSharedSystemSharedLibraryPackageName;
1390
1391    final boolean mPermissionReviewRequired;
1392
1393    private final PackageUsage mPackageUsage = new PackageUsage();
1394    private final CompilerStats mCompilerStats = new CompilerStats();
1395
1396    class PackageHandler extends Handler {
1397        private boolean mBound = false;
1398        final ArrayList<HandlerParams> mPendingInstalls =
1399            new ArrayList<HandlerParams>();
1400
1401        private boolean connectToService() {
1402            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1403                    " DefaultContainerService");
1404            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1405            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1406            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1407                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1408                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1409                mBound = true;
1410                return true;
1411            }
1412            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            return false;
1414        }
1415
1416        private void disconnectService() {
1417            mContainerService = null;
1418            mBound = false;
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            mContext.unbindService(mDefContainerConn);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1422        }
1423
1424        PackageHandler(Looper looper) {
1425            super(looper);
1426        }
1427
1428        public void handleMessage(Message msg) {
1429            try {
1430                doHandleMessage(msg);
1431            } finally {
1432                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433            }
1434        }
1435
1436        void doHandleMessage(Message msg) {
1437            switch (msg.what) {
1438                case INIT_COPY: {
1439                    HandlerParams params = (HandlerParams) msg.obj;
1440                    int idx = mPendingInstalls.size();
1441                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1442                    // If a bind was already initiated we dont really
1443                    // need to do anything. The pending install
1444                    // will be processed later on.
1445                    if (!mBound) {
1446                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1447                                System.identityHashCode(mHandler));
1448                        // If this is the only one pending we might
1449                        // have to bind to the service again.
1450                        if (!connectToService()) {
1451                            Slog.e(TAG, "Failed to bind to media container service");
1452                            params.serviceError();
1453                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1454                                    System.identityHashCode(mHandler));
1455                            if (params.traceMethod != null) {
1456                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1457                                        params.traceCookie);
1458                            }
1459                            return;
1460                        } else {
1461                            // Once we bind to the service, the first
1462                            // pending request will be processed.
1463                            mPendingInstalls.add(idx, params);
1464                        }
1465                    } else {
1466                        mPendingInstalls.add(idx, params);
1467                        // Already bound to the service. Just make
1468                        // sure we trigger off processing the first request.
1469                        if (idx == 0) {
1470                            mHandler.sendEmptyMessage(MCS_BOUND);
1471                        }
1472                    }
1473                    break;
1474                }
1475                case MCS_BOUND: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1477                    if (msg.obj != null) {
1478                        mContainerService = (IMediaContainerService) msg.obj;
1479                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1480                                System.identityHashCode(mHandler));
1481                    }
1482                    if (mContainerService == null) {
1483                        if (!mBound) {
1484                            // Something seriously wrong since we are not bound and we are not
1485                            // waiting for connection. Bail out.
1486                            Slog.e(TAG, "Cannot bind to media container service");
1487                            for (HandlerParams params : mPendingInstalls) {
1488                                // Indicate service bind error
1489                                params.serviceError();
1490                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1491                                        System.identityHashCode(params));
1492                                if (params.traceMethod != null) {
1493                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1494                                            params.traceMethod, params.traceCookie);
1495                                }
1496                                return;
1497                            }
1498                            mPendingInstalls.clear();
1499                        } else {
1500                            Slog.w(TAG, "Waiting to connect to media container service");
1501                        }
1502                    } else if (mPendingInstalls.size() > 0) {
1503                        HandlerParams params = mPendingInstalls.get(0);
1504                        if (params != null) {
1505                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1506                                    System.identityHashCode(params));
1507                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1508                            if (params.startCopy()) {
1509                                // We are done...  look for more work or to
1510                                // go idle.
1511                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                        "Checking for more work or unbind...");
1513                                // Delete pending install
1514                                if (mPendingInstalls.size() > 0) {
1515                                    mPendingInstalls.remove(0);
1516                                }
1517                                if (mPendingInstalls.size() == 0) {
1518                                    if (mBound) {
1519                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1520                                                "Posting delayed MCS_UNBIND");
1521                                        removeMessages(MCS_UNBIND);
1522                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1523                                        // Unbind after a little delay, to avoid
1524                                        // continual thrashing.
1525                                        sendMessageDelayed(ubmsg, 10000);
1526                                    }
1527                                } else {
1528                                    // There are more pending requests in queue.
1529                                    // Just post MCS_BOUND message to trigger processing
1530                                    // of next pending install.
1531                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                            "Posting MCS_BOUND for next work");
1533                                    mHandler.sendEmptyMessage(MCS_BOUND);
1534                                }
1535                            }
1536                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1537                        }
1538                    } else {
1539                        // Should never happen ideally.
1540                        Slog.w(TAG, "Empty queue");
1541                    }
1542                    break;
1543                }
1544                case MCS_RECONNECT: {
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1546                    if (mPendingInstalls.size() > 0) {
1547                        if (mBound) {
1548                            disconnectService();
1549                        }
1550                        if (!connectToService()) {
1551                            Slog.e(TAG, "Failed to bind to media container service");
1552                            for (HandlerParams params : mPendingInstalls) {
1553                                // Indicate service bind error
1554                                params.serviceError();
1555                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1556                                        System.identityHashCode(params));
1557                            }
1558                            mPendingInstalls.clear();
1559                        }
1560                    }
1561                    break;
1562                }
1563                case MCS_UNBIND: {
1564                    // If there is no actual work left, then time to unbind.
1565                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1566
1567                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1568                        if (mBound) {
1569                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1570
1571                            disconnectService();
1572                        }
1573                    } else if (mPendingInstalls.size() > 0) {
1574                        // There are more pending requests in queue.
1575                        // Just post MCS_BOUND message to trigger processing
1576                        // of next pending install.
1577                        mHandler.sendEmptyMessage(MCS_BOUND);
1578                    }
1579
1580                    break;
1581                }
1582                case MCS_GIVE_UP: {
1583                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1584                    HandlerParams params = mPendingInstalls.remove(0);
1585                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1586                            System.identityHashCode(params));
1587                    break;
1588                }
1589                case SEND_PENDING_BROADCAST: {
1590                    String packages[];
1591                    ArrayList<String> components[];
1592                    int size = 0;
1593                    int uids[];
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1595                    synchronized (mPackages) {
1596                        if (mPendingBroadcasts == null) {
1597                            return;
1598                        }
1599                        size = mPendingBroadcasts.size();
1600                        if (size <= 0) {
1601                            // Nothing to be done. Just return
1602                            return;
1603                        }
1604                        packages = new String[size];
1605                        components = new ArrayList[size];
1606                        uids = new int[size];
1607                        int i = 0;  // filling out the above arrays
1608
1609                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1610                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1611                            Iterator<Map.Entry<String, ArrayList<String>>> it
1612                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1613                                            .entrySet().iterator();
1614                            while (it.hasNext() && i < size) {
1615                                Map.Entry<String, ArrayList<String>> ent = it.next();
1616                                packages[i] = ent.getKey();
1617                                components[i] = ent.getValue();
1618                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1619                                uids[i] = (ps != null)
1620                                        ? UserHandle.getUid(packageUserId, ps.appId)
1621                                        : -1;
1622                                i++;
1623                            }
1624                        }
1625                        size = i;
1626                        mPendingBroadcasts.clear();
1627                    }
1628                    // Send broadcasts
1629                    for (int i = 0; i < size; i++) {
1630                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    break;
1634                }
1635                case START_CLEANING_PACKAGE: {
1636                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1637                    final String packageName = (String)msg.obj;
1638                    final int userId = msg.arg1;
1639                    final boolean andCode = msg.arg2 != 0;
1640                    synchronized (mPackages) {
1641                        if (userId == UserHandle.USER_ALL) {
1642                            int[] users = sUserManager.getUserIds();
1643                            for (int user : users) {
1644                                mSettings.addPackageToCleanLPw(
1645                                        new PackageCleanItem(user, packageName, andCode));
1646                            }
1647                        } else {
1648                            mSettings.addPackageToCleanLPw(
1649                                    new PackageCleanItem(userId, packageName, andCode));
1650                        }
1651                    }
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1653                    startCleaningPackages();
1654                } break;
1655                case POST_INSTALL: {
1656                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1657
1658                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1659                    final boolean didRestore = (msg.arg2 != 0);
1660                    mRunningInstalls.delete(msg.arg1);
1661
1662                    if (data != null) {
1663                        InstallArgs args = data.args;
1664                        PackageInstalledInfo parentRes = data.res;
1665
1666                        final boolean grantPermissions = (args.installFlags
1667                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1668                        final boolean killApp = (args.installFlags
1669                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1670                        final String[] grantedPermissions = args.installGrantPermissions;
1671
1672                        // Handle the parent package
1673                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1674                                grantedPermissions, didRestore, args.installerPackageName,
1675                                args.observer);
1676
1677                        // Handle the child packages
1678                        final int childCount = (parentRes.addedChildPackages != null)
1679                                ? parentRes.addedChildPackages.size() : 0;
1680                        for (int i = 0; i < childCount; i++) {
1681                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1682                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1683                                    grantedPermissions, false, args.installerPackageName,
1684                                    args.observer);
1685                        }
1686
1687                        // Log tracing if needed
1688                        if (args.traceMethod != null) {
1689                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1690                                    args.traceCookie);
1691                        }
1692                    } else {
1693                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1694                    }
1695
1696                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1697                } break;
1698                case UPDATED_MEDIA_STATUS: {
1699                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1700                    boolean reportStatus = msg.arg1 == 1;
1701                    boolean doGc = msg.arg2 == 1;
1702                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1703                    if (doGc) {
1704                        // Force a gc to clear up stale containers.
1705                        Runtime.getRuntime().gc();
1706                    }
1707                    if (msg.obj != null) {
1708                        @SuppressWarnings("unchecked")
1709                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1710                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1711                        // Unload containers
1712                        unloadAllContainers(args);
1713                    }
1714                    if (reportStatus) {
1715                        try {
1716                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1717                                    "Invoking StorageManagerService call back");
1718                            PackageHelper.getStorageManager().finishMediaUpdate();
1719                        } catch (RemoteException e) {
1720                            Log.e(TAG, "StorageManagerService not running?");
1721                        }
1722                    }
1723                } break;
1724                case WRITE_SETTINGS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_SETTINGS);
1728                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1729                        mSettings.writeLPr();
1730                        mDirtyUsers.clear();
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case WRITE_PACKAGE_RESTRICTIONS: {
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1736                    synchronized (mPackages) {
1737                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1738                        for (int userId : mDirtyUsers) {
1739                            mSettings.writePackageRestrictionsLPr(userId);
1740                        }
1741                        mDirtyUsers.clear();
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case WRITE_PACKAGE_LIST: {
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1747                    synchronized (mPackages) {
1748                        removeMessages(WRITE_PACKAGE_LIST);
1749                        mSettings.writePackageListLPr(msg.arg1);
1750                    }
1751                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1752                } break;
1753                case CHECK_PENDING_VERIFICATION: {
1754                    final int verificationId = msg.arg1;
1755                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1756
1757                    if ((state != null) && !state.timeoutExtended()) {
1758                        final InstallArgs args = state.getInstallArgs();
1759                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1760
1761                        Slog.i(TAG, "Verification timed out for " + originUri);
1762                        mPendingVerification.remove(verificationId);
1763
1764                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1765
1766                        final UserHandle user = args.getUser();
1767                        if (getDefaultVerificationResponse(user)
1768                                == PackageManager.VERIFICATION_ALLOW) {
1769                            Slog.i(TAG, "Continuing with installation of " + originUri);
1770                            state.setVerifierResponse(Binder.getCallingUid(),
1771                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_ALLOW, user);
1774                            try {
1775                                ret = args.copyApk(mContainerService, true);
1776                            } catch (RemoteException e) {
1777                                Slog.e(TAG, "Could not contact the ContainerService");
1778                            }
1779                        } else {
1780                            broadcastPackageVerified(verificationId, originUri,
1781                                    PackageManager.VERIFICATION_REJECT, user);
1782                        }
1783
1784                        Trace.asyncTraceEnd(
1785                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1786
1787                        processPendingInstall(args, ret);
1788                        mHandler.sendEmptyMessage(MCS_UNBIND);
1789                    }
1790                    break;
1791                }
1792                case PACKAGE_VERIFIED: {
1793                    final int verificationId = msg.arg1;
1794
1795                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1796                    if (state == null) {
1797                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1798                        break;
1799                    }
1800
1801                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1802
1803                    state.setVerifierResponse(response.callerUid, response.code);
1804
1805                    if (state.isVerificationComplete()) {
1806                        mPendingVerification.remove(verificationId);
1807
1808                        final InstallArgs args = state.getInstallArgs();
1809                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1810
1811                        int ret;
1812                        if (state.isInstallAllowed()) {
1813                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1814                            broadcastPackageVerified(verificationId, originUri,
1815                                    response.code, state.getInstallArgs().getUser());
1816                            try {
1817                                ret = args.copyApk(mContainerService, true);
1818                            } catch (RemoteException e) {
1819                                Slog.e(TAG, "Could not contact the ContainerService");
1820                            }
1821                        } else {
1822                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1823                        }
1824
1825                        Trace.asyncTraceEnd(
1826                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1827
1828                        processPendingInstall(args, ret);
1829                        mHandler.sendEmptyMessage(MCS_UNBIND);
1830                    }
1831
1832                    break;
1833                }
1834                case START_INTENT_FILTER_VERIFICATIONS: {
1835                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1836                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1837                            params.replacing, params.pkg);
1838                    break;
1839                }
1840                case INTENT_FILTER_VERIFIED: {
1841                    final int verificationId = msg.arg1;
1842
1843                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1844                            verificationId);
1845                    if (state == null) {
1846                        Slog.w(TAG, "Invalid IntentFilter verification token "
1847                                + verificationId + " received");
1848                        break;
1849                    }
1850
1851                    final int userId = state.getUserId();
1852
1853                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1854                            "Processing IntentFilter verification with token:"
1855                            + verificationId + " and userId:" + userId);
1856
1857                    final IntentFilterVerificationResponse response =
1858                            (IntentFilterVerificationResponse) msg.obj;
1859
1860                    state.setVerifierResponse(response.callerUid, response.code);
1861
1862                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1863                            "IntentFilter verification with token:" + verificationId
1864                            + " and userId:" + userId
1865                            + " is settings verifier response with response code:"
1866                            + response.code);
1867
1868                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1869                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1870                                + response.getFailedDomainsString());
1871                    }
1872
1873                    if (state.isVerificationComplete()) {
1874                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1875                    } else {
1876                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                                "IntentFilter verification with token:" + verificationId
1878                                + " was not said to be complete");
1879                    }
1880
1881                    break;
1882                }
1883                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1884                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1885                            mInstantAppResolverConnection,
1886                            (InstantAppRequest) msg.obj,
1887                            mInstantAppInstallerActivity,
1888                            mHandler);
1889                }
1890            }
1891        }
1892    }
1893
1894    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1895            boolean killApp, String[] grantedPermissions,
1896            boolean launchedForRestore, String installerPackage,
1897            IPackageInstallObserver2 installObserver) {
1898        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1899            // Send the removed broadcasts
1900            if (res.removedInfo != null) {
1901                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1902            }
1903
1904            // Now that we successfully installed the package, grant runtime
1905            // permissions if requested before broadcasting the install. Also
1906            // for legacy apps in permission review mode we clear the permission
1907            // review flag which is used to emulate runtime permissions for
1908            // legacy apps.
1909            if (grantPermissions) {
1910                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1911            }
1912
1913            final boolean update = res.removedInfo != null
1914                    && res.removedInfo.removedPackage != null;
1915            final String origInstallerPackageName = res.removedInfo != null
1916                    ? res.removedInfo.installerPackageName : null;
1917
1918            // If this is the first time we have child packages for a disabled privileged
1919            // app that had no children, we grant requested runtime permissions to the new
1920            // children if the parent on the system image had them already granted.
1921            if (res.pkg.parentPackage != null) {
1922                synchronized (mPackages) {
1923                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1924                }
1925            }
1926
1927            synchronized (mPackages) {
1928                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1929            }
1930
1931            final String packageName = res.pkg.applicationInfo.packageName;
1932
1933            // Determine the set of users who are adding this package for
1934            // the first time vs. those who are seeing an update.
1935            int[] firstUsers = EMPTY_INT_ARRAY;
1936            int[] updateUsers = EMPTY_INT_ARRAY;
1937            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1938            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1939            for (int newUser : res.newUsers) {
1940                if (ps.getInstantApp(newUser)) {
1941                    continue;
1942                }
1943                if (allNewUsers) {
1944                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1945                    continue;
1946                }
1947                boolean isNew = true;
1948                for (int origUser : res.origUsers) {
1949                    if (origUser == newUser) {
1950                        isNew = false;
1951                        break;
1952                    }
1953                }
1954                if (isNew) {
1955                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1956                } else {
1957                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1958                }
1959            }
1960
1961            // Send installed broadcasts if the package is not a static shared lib.
1962            if (res.pkg.staticSharedLibName == null) {
1963                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1964
1965                // Send added for users that see the package for the first time
1966                // sendPackageAddedForNewUsers also deals with system apps
1967                int appId = UserHandle.getAppId(res.uid);
1968                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1969                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1970
1971                // Send added for users that don't see the package for the first time
1972                Bundle extras = new Bundle(1);
1973                extras.putInt(Intent.EXTRA_UID, res.uid);
1974                if (update) {
1975                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1976                }
1977                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1978                        extras, 0 /*flags*/,
1979                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1980                if (origInstallerPackageName != null) {
1981                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1982                            extras, 0 /*flags*/,
1983                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1984                }
1985
1986                // Send replaced for users that don't see the package for the first time
1987                if (update) {
1988                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1989                            packageName, extras, 0 /*flags*/,
1990                            null /*targetPackage*/, null /*finishedReceiver*/,
1991                            updateUsers);
1992                    if (origInstallerPackageName != null) {
1993                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1994                                extras, 0 /*flags*/,
1995                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1996                    }
1997                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1998                            null /*package*/, null /*extras*/, 0 /*flags*/,
1999                            packageName /*targetPackage*/,
2000                            null /*finishedReceiver*/, updateUsers);
2001                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2002                    // First-install and we did a restore, so we're responsible for the
2003                    // first-launch broadcast.
2004                    if (DEBUG_BACKUP) {
2005                        Slog.i(TAG, "Post-restore of " + packageName
2006                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2007                    }
2008                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2009                }
2010
2011                // Send broadcast package appeared if forward locked/external for all users
2012                // treat asec-hosted packages like removable media on upgrade
2013                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2014                    if (DEBUG_INSTALL) {
2015                        Slog.i(TAG, "upgrading pkg " + res.pkg
2016                                + " is ASEC-hosted -> AVAILABLE");
2017                    }
2018                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2019                    ArrayList<String> pkgList = new ArrayList<>(1);
2020                    pkgList.add(packageName);
2021                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2022                }
2023            }
2024
2025            // Work that needs to happen on first install within each user
2026            if (firstUsers != null && firstUsers.length > 0) {
2027                synchronized (mPackages) {
2028                    for (int userId : firstUsers) {
2029                        // If this app is a browser and it's newly-installed for some
2030                        // users, clear any default-browser state in those users. The
2031                        // app's nature doesn't depend on the user, so we can just check
2032                        // its browser nature in any user and generalize.
2033                        if (packageIsBrowser(packageName, userId)) {
2034                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2035                        }
2036
2037                        // We may also need to apply pending (restored) runtime
2038                        // permission grants within these users.
2039                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2040                    }
2041                }
2042            }
2043
2044            // Log current value of "unknown sources" setting
2045            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2046                    getUnknownSourcesSettings());
2047
2048            // Remove the replaced package's older resources safely now
2049            // We delete after a gc for applications  on sdcard.
2050            if (res.removedInfo != null && res.removedInfo.args != null) {
2051                Runtime.getRuntime().gc();
2052                synchronized (mInstallLock) {
2053                    res.removedInfo.args.doPostDeleteLI(true);
2054                }
2055            } else {
2056                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2057                // and not block here.
2058                VMRuntime.getRuntime().requestConcurrentGC();
2059            }
2060
2061            // Notify DexManager that the package was installed for new users.
2062            // The updated users should already be indexed and the package code paths
2063            // should not change.
2064            // Don't notify the manager for ephemeral apps as they are not expected to
2065            // survive long enough to benefit of background optimizations.
2066            for (int userId : firstUsers) {
2067                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2068                // There's a race currently where some install events may interleave with an uninstall.
2069                // This can lead to package info being null (b/36642664).
2070                if (info != null) {
2071                    mDexManager.notifyPackageInstalled(info, userId);
2072                }
2073            }
2074        }
2075
2076        // If someone is watching installs - notify them
2077        if (installObserver != null) {
2078            try {
2079                Bundle extras = extrasForInstallResult(res);
2080                installObserver.onPackageInstalled(res.name, res.returnCode,
2081                        res.returnMsg, extras);
2082            } catch (RemoteException e) {
2083                Slog.i(TAG, "Observer no longer exists.");
2084            }
2085        }
2086    }
2087
2088    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2089            PackageParser.Package pkg) {
2090        if (pkg.parentPackage == null) {
2091            return;
2092        }
2093        if (pkg.requestedPermissions == null) {
2094            return;
2095        }
2096        final PackageSetting disabledSysParentPs = mSettings
2097                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2098        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2099                || !disabledSysParentPs.isPrivileged()
2100                || (disabledSysParentPs.childPackageNames != null
2101                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2102            return;
2103        }
2104        final int[] allUserIds = sUserManager.getUserIds();
2105        final int permCount = pkg.requestedPermissions.size();
2106        for (int i = 0; i < permCount; i++) {
2107            String permission = pkg.requestedPermissions.get(i);
2108            BasePermission bp = mSettings.mPermissions.get(permission);
2109            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2110                continue;
2111            }
2112            for (int userId : allUserIds) {
2113                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2114                        permission, userId)) {
2115                    grantRuntimePermission(pkg.packageName, permission, userId);
2116                }
2117            }
2118        }
2119    }
2120
2121    private StorageEventListener mStorageListener = new StorageEventListener() {
2122        @Override
2123        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2124            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    final String volumeUuid = vol.getFsUuid();
2127
2128                    // Clean up any users or apps that were removed or recreated
2129                    // while this volume was missing
2130                    sUserManager.reconcileUsers(volumeUuid);
2131                    reconcileApps(volumeUuid);
2132
2133                    // Clean up any install sessions that expired or were
2134                    // cancelled while this volume was missing
2135                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2136
2137                    loadPrivatePackages(vol);
2138
2139                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2140                    unloadPrivatePackages(vol);
2141                }
2142            }
2143
2144            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2145                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2146                    updateExternalMediaStatus(true, false);
2147                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2148                    updateExternalMediaStatus(false, false);
2149                }
2150            }
2151        }
2152
2153        @Override
2154        public void onVolumeForgotten(String fsUuid) {
2155            if (TextUtils.isEmpty(fsUuid)) {
2156                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2157                return;
2158            }
2159
2160            // Remove any apps installed on the forgotten volume
2161            synchronized (mPackages) {
2162                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2163                for (PackageSetting ps : packages) {
2164                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2165                    deletePackageVersioned(new VersionedPackage(ps.name,
2166                            PackageManager.VERSION_CODE_HIGHEST),
2167                            new LegacyPackageDeleteObserver(null).getBinder(),
2168                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2169                    // Try very hard to release any references to this package
2170                    // so we don't risk the system server being killed due to
2171                    // open FDs
2172                    AttributeCache.instance().removePackage(ps.name);
2173                }
2174
2175                mSettings.onVolumeForgotten(fsUuid);
2176                mSettings.writeLPr();
2177            }
2178        }
2179    };
2180
2181    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2182            String[] grantedPermissions) {
2183        for (int userId : userIds) {
2184            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2185        }
2186    }
2187
2188    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2189            String[] grantedPermissions) {
2190        PackageSetting ps = (PackageSetting) pkg.mExtras;
2191        if (ps == null) {
2192            return;
2193        }
2194
2195        PermissionsState permissionsState = ps.getPermissionsState();
2196
2197        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2198                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2199
2200        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2201                >= Build.VERSION_CODES.M;
2202
2203        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2204
2205        for (String permission : pkg.requestedPermissions) {
2206            final BasePermission bp;
2207            synchronized (mPackages) {
2208                bp = mSettings.mPermissions.get(permission);
2209            }
2210            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2211                    && (!instantApp || bp.isInstant())
2212                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2213                    && (grantedPermissions == null
2214                           || ArrayUtils.contains(grantedPermissions, permission))) {
2215                final int flags = permissionsState.getPermissionFlags(permission, userId);
2216                if (supportsRuntimePermissions) {
2217                    // Installer cannot change immutable permissions.
2218                    if ((flags & immutableFlags) == 0) {
2219                        grantRuntimePermission(pkg.packageName, permission, userId);
2220                    }
2221                } else if (mPermissionReviewRequired) {
2222                    // In permission review mode we clear the review flag when we
2223                    // are asked to install the app with all permissions granted.
2224                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2225                        updatePermissionFlags(permission, pkg.packageName,
2226                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227                    }
2228                }
2229            }
2230        }
2231    }
2232
2233    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2234        Bundle extras = null;
2235        switch (res.returnCode) {
2236            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2237                extras = new Bundle();
2238                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2239                        res.origPermission);
2240                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2241                        res.origPackage);
2242                break;
2243            }
2244            case PackageManager.INSTALL_SUCCEEDED: {
2245                extras = new Bundle();
2246                extras.putBoolean(Intent.EXTRA_REPLACING,
2247                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2248                break;
2249            }
2250        }
2251        return extras;
2252    }
2253
2254    void scheduleWriteSettingsLocked() {
2255        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2256            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2257        }
2258    }
2259
2260    void scheduleWritePackageListLocked(int userId) {
2261        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2262            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2263            msg.arg1 = userId;
2264            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2265        }
2266    }
2267
2268    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2269        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2270        scheduleWritePackageRestrictionsLocked(userId);
2271    }
2272
2273    void scheduleWritePackageRestrictionsLocked(int userId) {
2274        final int[] userIds = (userId == UserHandle.USER_ALL)
2275                ? sUserManager.getUserIds() : new int[]{userId};
2276        for (int nextUserId : userIds) {
2277            if (!sUserManager.exists(nextUserId)) return;
2278            mDirtyUsers.add(nextUserId);
2279            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2280                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2281            }
2282        }
2283    }
2284
2285    public static PackageManagerService main(Context context, Installer installer,
2286            boolean factoryTest, boolean onlyCore) {
2287        // Self-check for initial settings.
2288        PackageManagerServiceCompilerMapping.checkProperties();
2289
2290        PackageManagerService m = new PackageManagerService(context, installer,
2291                factoryTest, onlyCore);
2292        m.enableSystemUserPackages();
2293        ServiceManager.addService("package", m);
2294        return m;
2295    }
2296
2297    private void enableSystemUserPackages() {
2298        if (!UserManager.isSplitSystemUser()) {
2299            return;
2300        }
2301        // For system user, enable apps based on the following conditions:
2302        // - app is whitelisted or belong to one of these groups:
2303        //   -- system app which has no launcher icons
2304        //   -- system app which has INTERACT_ACROSS_USERS permission
2305        //   -- system IME app
2306        // - app is not in the blacklist
2307        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2308        Set<String> enableApps = new ArraySet<>();
2309        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2310                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2311                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2312        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2313        enableApps.addAll(wlApps);
2314        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2315                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2316        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2317        enableApps.removeAll(blApps);
2318        Log.i(TAG, "Applications installed for system user: " + enableApps);
2319        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2320                UserHandle.SYSTEM);
2321        final int allAppsSize = allAps.size();
2322        synchronized (mPackages) {
2323            for (int i = 0; i < allAppsSize; i++) {
2324                String pName = allAps.get(i);
2325                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2326                // Should not happen, but we shouldn't be failing if it does
2327                if (pkgSetting == null) {
2328                    continue;
2329                }
2330                boolean install = enableApps.contains(pName);
2331                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2332                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2333                            + " for system user");
2334                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2335                }
2336            }
2337            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2338        }
2339    }
2340
2341    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2342        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2343                Context.DISPLAY_SERVICE);
2344        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2345    }
2346
2347    /**
2348     * Requests that files preopted on a secondary system partition be copied to the data partition
2349     * if possible.  Note that the actual copying of the files is accomplished by init for security
2350     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2351     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2352     */
2353    private static void requestCopyPreoptedFiles() {
2354        final int WAIT_TIME_MS = 100;
2355        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2356        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2357            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2358            // We will wait for up to 100 seconds.
2359            final long timeStart = SystemClock.uptimeMillis();
2360            final long timeEnd = timeStart + 100 * 1000;
2361            long timeNow = timeStart;
2362            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2363                try {
2364                    Thread.sleep(WAIT_TIME_MS);
2365                } catch (InterruptedException e) {
2366                    // Do nothing
2367                }
2368                timeNow = SystemClock.uptimeMillis();
2369                if (timeNow > timeEnd) {
2370                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2371                    Slog.wtf(TAG, "cppreopt did not finish!");
2372                    break;
2373                }
2374            }
2375
2376            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2377        }
2378    }
2379
2380    public PackageManagerService(Context context, Installer installer,
2381            boolean factoryTest, boolean onlyCore) {
2382        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2383        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2384        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2385                SystemClock.uptimeMillis());
2386
2387        if (mSdkVersion <= 0) {
2388            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2389        }
2390
2391        mContext = context;
2392
2393        mPermissionReviewRequired = context.getResources().getBoolean(
2394                R.bool.config_permissionReviewRequired);
2395
2396        mFactoryTest = factoryTest;
2397        mOnlyCore = onlyCore;
2398        mMetrics = new DisplayMetrics();
2399        mSettings = new Settings(mPackages);
2400        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412
2413        String separateProcesses = SystemProperties.get("debug.separate_processes");
2414        if (separateProcesses != null && separateProcesses.length() > 0) {
2415            if ("*".equals(separateProcesses)) {
2416                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2417                mSeparateProcesses = null;
2418                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2419            } else {
2420                mDefParseFlags = 0;
2421                mSeparateProcesses = separateProcesses.split(",");
2422                Slog.w(TAG, "Running with debug.separate_processes: "
2423                        + separateProcesses);
2424            }
2425        } else {
2426            mDefParseFlags = 0;
2427            mSeparateProcesses = null;
2428        }
2429
2430        mInstaller = installer;
2431        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2432                "*dexopt*");
2433        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2434        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2435
2436        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2437                FgThread.get().getLooper());
2438
2439        getDefaultDisplayMetrics(context, mMetrics);
2440
2441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2442        SystemConfig systemConfig = SystemConfig.getInstance();
2443        mGlobalGids = systemConfig.getGlobalGids();
2444        mSystemPermissions = systemConfig.getSystemPermissions();
2445        mAvailableFeatures = systemConfig.getAvailableFeatures();
2446        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2447
2448        mProtectedPackages = new ProtectedPackages(mContext);
2449
2450        synchronized (mInstallLock) {
2451        // writer
2452        synchronized (mPackages) {
2453            mHandlerThread = new ServiceThread(TAG,
2454                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2455            mHandlerThread.start();
2456            mHandler = new PackageHandler(mHandlerThread.getLooper());
2457            mProcessLoggingHandler = new ProcessLoggingHandler();
2458            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2459
2460            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2461            mInstantAppRegistry = new InstantAppRegistry(this);
2462
2463            File dataDir = Environment.getDataDirectory();
2464            mAppInstallDir = new File(dataDir, "app");
2465            mAppLib32InstallDir = new File(dataDir, "app-lib");
2466            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2467            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2468            sUserManager = new UserManagerService(context, this,
2469                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2470
2471            // Propagate permission configuration in to package manager.
2472            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2473                    = systemConfig.getPermissions();
2474            for (int i=0; i<permConfig.size(); i++) {
2475                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2476                BasePermission bp = mSettings.mPermissions.get(perm.name);
2477                if (bp == null) {
2478                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2479                    mSettings.mPermissions.put(perm.name, bp);
2480                }
2481                if (perm.gids != null) {
2482                    bp.setGids(perm.gids, perm.perUser);
2483                }
2484            }
2485
2486            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2487            final int builtInLibCount = libConfig.size();
2488            for (int i = 0; i < builtInLibCount; i++) {
2489                String name = libConfig.keyAt(i);
2490                String path = libConfig.valueAt(i);
2491                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2492                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2493            }
2494
2495            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2496
2497            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2498            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2500
2501            // Clean up orphaned packages for which the code path doesn't exist
2502            // and they are an update to a system app - caused by bug/32321269
2503            final int packageSettingCount = mSettings.mPackages.size();
2504            for (int i = packageSettingCount - 1; i >= 0; i--) {
2505                PackageSetting ps = mSettings.mPackages.valueAt(i);
2506                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2507                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2508                    mSettings.mPackages.removeAt(i);
2509                    mSettings.enableSystemPackageLPw(ps.name);
2510                }
2511            }
2512
2513            if (mFirstBoot) {
2514                requestCopyPreoptedFiles();
2515            }
2516
2517            String customResolverActivity = Resources.getSystem().getString(
2518                    R.string.config_customResolverActivity);
2519            if (TextUtils.isEmpty(customResolverActivity)) {
2520                customResolverActivity = null;
2521            } else {
2522                mCustomResolverComponentName = ComponentName.unflattenFromString(
2523                        customResolverActivity);
2524            }
2525
2526            long startTime = SystemClock.uptimeMillis();
2527
2528            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2529                    startTime);
2530
2531            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2532            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2533
2534            if (bootClassPath == null) {
2535                Slog.w(TAG, "No BOOTCLASSPATH found!");
2536            }
2537
2538            if (systemServerClassPath == null) {
2539                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2540            }
2541
2542            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2543
2544            final VersionInfo ver = mSettings.getInternalVersion();
2545            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2546            if (mIsUpgrade) {
2547                logCriticalInfo(Log.INFO,
2548                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2549            }
2550
2551            // when upgrading from pre-M, promote system app permissions from install to runtime
2552            mPromoteSystemApps =
2553                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2554
2555            // When upgrading from pre-N, we need to handle package extraction like first boot,
2556            // as there is no profiling data available.
2557            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2558
2559            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2560
2561            // save off the names of pre-existing system packages prior to scanning; we don't
2562            // want to automatically grant runtime permissions for new system apps
2563            if (mPromoteSystemApps) {
2564                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2565                while (pkgSettingIter.hasNext()) {
2566                    PackageSetting ps = pkgSettingIter.next();
2567                    if (isSystemApp(ps)) {
2568                        mExistingSystemPackages.add(ps.name);
2569                    }
2570                }
2571            }
2572
2573            mCacheDir = preparePackageParserCache(mIsUpgrade);
2574
2575            // Set flag to monitor and not change apk file paths when
2576            // scanning install directories.
2577            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2578
2579            if (mIsUpgrade || mFirstBoot) {
2580                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2581            }
2582
2583            // Collect vendor overlay packages. (Do this before scanning any apps.)
2584            // For security and version matching reason, only consider
2585            // overlay packages if they reside in the right directory.
2586            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2587                    | PackageParser.PARSE_IS_SYSTEM
2588                    | PackageParser.PARSE_IS_SYSTEM_DIR
2589                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2590
2591            mParallelPackageParserCallback.findStaticOverlayPackages();
2592
2593            // Find base frameworks (resource packages without code).
2594            scanDirTracedLI(frameworkDir, mDefParseFlags
2595                    | PackageParser.PARSE_IS_SYSTEM
2596                    | PackageParser.PARSE_IS_SYSTEM_DIR
2597                    | PackageParser.PARSE_IS_PRIVILEGED,
2598                    scanFlags | SCAN_NO_DEX, 0);
2599
2600            // Collected privileged system packages.
2601            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2602            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2606
2607            // Collect ordinary system packages.
2608            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2609            scanDirTracedLI(systemAppDir, mDefParseFlags
2610                    | PackageParser.PARSE_IS_SYSTEM
2611                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2612
2613            // Collect all vendor packages.
2614            File vendorAppDir = new File("/vendor/app");
2615            try {
2616                vendorAppDir = vendorAppDir.getCanonicalFile();
2617            } catch (IOException e) {
2618                // failed to look up canonical path, continue with original one
2619            }
2620            scanDirTracedLI(vendorAppDir, mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM
2622                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2623
2624            // Collect all OEM packages.
2625            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2626            scanDirTracedLI(oemAppDir, mDefParseFlags
2627                    | PackageParser.PARSE_IS_SYSTEM
2628                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2629
2630            // Prune any system packages that no longer exist.
2631            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2632            if (!mOnlyCore) {
2633                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2634                while (psit.hasNext()) {
2635                    PackageSetting ps = psit.next();
2636
2637                    /*
2638                     * If this is not a system app, it can't be a
2639                     * disable system app.
2640                     */
2641                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2642                        continue;
2643                    }
2644
2645                    /*
2646                     * If the package is scanned, it's not erased.
2647                     */
2648                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2649                    if (scannedPkg != null) {
2650                        /*
2651                         * If the system app is both scanned and in the
2652                         * disabled packages list, then it must have been
2653                         * added via OTA. Remove it from the currently
2654                         * scanned package so the previously user-installed
2655                         * application can be scanned.
2656                         */
2657                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2658                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2659                                    + ps.name + "; removing system app.  Last known codePath="
2660                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2661                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2662                                    + scannedPkg.mVersionCode);
2663                            removePackageLI(scannedPkg, true);
2664                            mExpectingBetter.put(ps.name, ps.codePath);
2665                        }
2666
2667                        continue;
2668                    }
2669
2670                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2671                        psit.remove();
2672                        logCriticalInfo(Log.WARN, "System package " + ps.name
2673                                + " no longer exists; it's data will be wiped");
2674                        // Actual deletion of code and data will be handled by later
2675                        // reconciliation step
2676                    } else {
2677                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2678                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2679                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2680                        }
2681                    }
2682                }
2683            }
2684
2685            //look for any incomplete package installations
2686            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2687            for (int i = 0; i < deletePkgsList.size(); i++) {
2688                // Actual deletion of code and data will be handled by later
2689                // reconciliation step
2690                final String packageName = deletePkgsList.get(i).name;
2691                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2692                synchronized (mPackages) {
2693                    mSettings.removePackageLPw(packageName);
2694                }
2695            }
2696
2697            //delete tmp files
2698            deleteTempPackageFiles();
2699
2700            // Remove any shared userIDs that have no associated packages
2701            mSettings.pruneSharedUsersLPw();
2702
2703            if (!mOnlyCore) {
2704                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2705                        SystemClock.uptimeMillis());
2706                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707
2708                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2709                        | PackageParser.PARSE_FORWARD_LOCK,
2710                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2711
2712                /**
2713                 * Remove disable package settings for any updated system
2714                 * apps that were removed via an OTA. If they're not a
2715                 * previously-updated app, remove them completely.
2716                 * Otherwise, just revoke their system-level permissions.
2717                 */
2718                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2719                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2720                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2721
2722                    String msg;
2723                    if (deletedPkg == null) {
2724                        msg = "Updated system package " + deletedAppName
2725                                + " no longer exists; it's data will be wiped";
2726                        // Actual deletion of code and data will be handled by later
2727                        // reconciliation step
2728                    } else {
2729                        msg = "Updated system app + " + deletedAppName
2730                                + " no longer present; removing system privileges for "
2731                                + deletedAppName;
2732
2733                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2734
2735                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2736                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2737                    }
2738                    logCriticalInfo(Log.WARN, msg);
2739                }
2740
2741                /**
2742                 * Make sure all system apps that we expected to appear on
2743                 * the userdata partition actually showed up. If they never
2744                 * appeared, crawl back and revive the system version.
2745                 */
2746                for (int i = 0; i < mExpectingBetter.size(); i++) {
2747                    final String packageName = mExpectingBetter.keyAt(i);
2748                    if (!mPackages.containsKey(packageName)) {
2749                        final File scanFile = mExpectingBetter.valueAt(i);
2750
2751                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2752                                + " but never showed up; reverting to system");
2753
2754                        int reparseFlags = mDefParseFlags;
2755                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2756                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2757                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2758                                    | PackageParser.PARSE_IS_PRIVILEGED;
2759                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2760                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2762                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2763                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2764                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2765                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2766                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2767                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2768                        } else {
2769                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2770                            continue;
2771                        }
2772
2773                        mSettings.enableSystemPackageLPw(packageName);
2774
2775                        try {
2776                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2777                        } catch (PackageManagerException e) {
2778                            Slog.e(TAG, "Failed to parse original system package: "
2779                                    + e.getMessage());
2780                        }
2781                    }
2782                }
2783            }
2784            mExpectingBetter.clear();
2785
2786            // Resolve the storage manager.
2787            mStorageManagerPackage = getStorageManagerPackageName();
2788
2789            // Resolve protected action filters. Only the setup wizard is allowed to
2790            // have a high priority filter for these actions.
2791            mSetupWizardPackage = getSetupWizardPackageName();
2792            if (mProtectedFilters.size() > 0) {
2793                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2794                    Slog.i(TAG, "No setup wizard;"
2795                        + " All protected intents capped to priority 0");
2796                }
2797                for (ActivityIntentInfo filter : mProtectedFilters) {
2798                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2799                        if (DEBUG_FILTERS) {
2800                            Slog.i(TAG, "Found setup wizard;"
2801                                + " allow priority " + filter.getPriority() + ";"
2802                                + " package: " + filter.activity.info.packageName
2803                                + " activity: " + filter.activity.className
2804                                + " priority: " + filter.getPriority());
2805                        }
2806                        // skip setup wizard; allow it to keep the high priority filter
2807                        continue;
2808                    }
2809                    if (DEBUG_FILTERS) {
2810                        Slog.i(TAG, "Protected action; cap priority to 0;"
2811                                + " package: " + filter.activity.info.packageName
2812                                + " activity: " + filter.activity.className
2813                                + " origPrio: " + filter.getPriority());
2814                    }
2815                    filter.setPriority(0);
2816                }
2817            }
2818            mDeferProtectedFilters = false;
2819            mProtectedFilters.clear();
2820
2821            // Now that we know all of the shared libraries, update all clients to have
2822            // the correct library paths.
2823            updateAllSharedLibrariesLPw(null);
2824
2825            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2826                // NOTE: We ignore potential failures here during a system scan (like
2827                // the rest of the commands above) because there's precious little we
2828                // can do about it. A settings error is reported, though.
2829                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2830            }
2831
2832            // Now that we know all the packages we are keeping,
2833            // read and update their last usage times.
2834            mPackageUsage.read(mPackages);
2835            mCompilerStats.read();
2836
2837            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2838                    SystemClock.uptimeMillis());
2839            Slog.i(TAG, "Time to scan packages: "
2840                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2841                    + " seconds");
2842
2843            // If the platform SDK has changed since the last time we booted,
2844            // we need to re-grant app permission to catch any new ones that
2845            // appear.  This is really a hack, and means that apps can in some
2846            // cases get permissions that the user didn't initially explicitly
2847            // allow...  it would be nice to have some better way to handle
2848            // this situation.
2849            int updateFlags = UPDATE_PERMISSIONS_ALL;
2850            if (ver.sdkVersion != mSdkVersion) {
2851                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2852                        + mSdkVersion + "; regranting permissions for internal storage");
2853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2854            }
2855            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2856            ver.sdkVersion = mSdkVersion;
2857
2858            // If this is the first boot or an update from pre-M, and it is a normal
2859            // boot, then we need to initialize the default preferred apps across
2860            // all defined users.
2861            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2862                for (UserInfo user : sUserManager.getUsers(true)) {
2863                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2864                    applyFactoryDefaultBrowserLPw(user.id);
2865                    primeDomainVerificationsLPw(user.id);
2866                }
2867            }
2868
2869            // Prepare storage for system user really early during boot,
2870            // since core system apps like SettingsProvider and SystemUI
2871            // can't wait for user to start
2872            final int storageFlags;
2873            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2874                storageFlags = StorageManager.FLAG_STORAGE_DE;
2875            } else {
2876                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2877            }
2878            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2879                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2880                    true /* onlyCoreApps */);
2881            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2882                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2883                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2884                traceLog.traceBegin("AppDataFixup");
2885                try {
2886                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2887                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2888                } catch (InstallerException e) {
2889                    Slog.w(TAG, "Trouble fixing GIDs", e);
2890                }
2891                traceLog.traceEnd();
2892
2893                traceLog.traceBegin("AppDataPrepare");
2894                if (deferPackages == null || deferPackages.isEmpty()) {
2895                    return;
2896                }
2897                int count = 0;
2898                for (String pkgName : deferPackages) {
2899                    PackageParser.Package pkg = null;
2900                    synchronized (mPackages) {
2901                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2902                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2903                            pkg = ps.pkg;
2904                        }
2905                    }
2906                    if (pkg != null) {
2907                        synchronized (mInstallLock) {
2908                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2909                                    true /* maybeMigrateAppData */);
2910                        }
2911                        count++;
2912                    }
2913                }
2914                traceLog.traceEnd();
2915                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2916            }, "prepareAppData");
2917
2918            // If this is first boot after an OTA, and a normal boot, then
2919            // we need to clear code cache directories.
2920            // Note that we do *not* clear the application profiles. These remain valid
2921            // across OTAs and are used to drive profile verification (post OTA) and
2922            // profile compilation (without waiting to collect a fresh set of profiles).
2923            if (mIsUpgrade && !onlyCore) {
2924                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2925                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2926                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2927                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2928                        // No apps are running this early, so no need to freeze
2929                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2930                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2931                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2932                    }
2933                }
2934                ver.fingerprint = Build.FINGERPRINT;
2935            }
2936
2937            checkDefaultBrowser();
2938
2939            // clear only after permissions and other defaults have been updated
2940            mExistingSystemPackages.clear();
2941            mPromoteSystemApps = false;
2942
2943            // All the changes are done during package scanning.
2944            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2945
2946            // can downgrade to reader
2947            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2948            mSettings.writeLPr();
2949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2950            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2951                    SystemClock.uptimeMillis());
2952
2953            if (!mOnlyCore) {
2954                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2955                mRequiredInstallerPackage = getRequiredInstallerLPr();
2956                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2957                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2958                if (mIntentFilterVerifierComponent != null) {
2959                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2960                            mIntentFilterVerifierComponent);
2961                } else {
2962                    mIntentFilterVerifier = null;
2963                }
2964                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970            } else {
2971                mRequiredVerifierPackage = null;
2972                mRequiredInstallerPackage = null;
2973                mRequiredUninstallerPackage = null;
2974                mIntentFilterVerifierComponent = null;
2975                mIntentFilterVerifier = null;
2976                mServicesSystemSharedLibraryPackageName = null;
2977                mSharedSystemSharedLibraryPackageName = null;
2978            }
2979
2980            mInstallerService = new PackageInstallerService(context, this);
2981            final Pair<ComponentName, String> instantAppResolverComponent =
2982                    getInstantAppResolverLPr();
2983            if (instantAppResolverComponent != null) {
2984                if (DEBUG_EPHEMERAL) {
2985                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2986                }
2987                mInstantAppResolverConnection = new EphemeralResolverConnection(
2988                        mContext, instantAppResolverComponent.first,
2989                        instantAppResolverComponent.second);
2990                mInstantAppResolverSettingsComponent =
2991                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2992            } else {
2993                mInstantAppResolverConnection = null;
2994                mInstantAppResolverSettingsComponent = null;
2995            }
2996            updateInstantAppInstallerLocked(null);
2997
2998            // Read and update the usage of dex files.
2999            // Do this at the end of PM init so that all the packages have their
3000            // data directory reconciled.
3001            // At this point we know the code paths of the packages, so we can validate
3002            // the disk file and build the internal cache.
3003            // The usage file is expected to be small so loading and verifying it
3004            // should take a fairly small time compare to the other activities (e.g. package
3005            // scanning).
3006            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3007            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3008            for (int userId : currentUserIds) {
3009                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3010            }
3011            mDexManager.load(userPackages);
3012        } // synchronized (mPackages)
3013        } // synchronized (mInstallLock)
3014
3015        // Now after opening every single application zip, make sure they
3016        // are all flushed.  Not really needed, but keeps things nice and
3017        // tidy.
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3019        Runtime.getRuntime().gc();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3023        FallbackCategoryProvider.loadFallbacks();
3024        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3025
3026        // The initial scanning above does many calls into installd while
3027        // holding the mPackages lock, but we're mostly interested in yelling
3028        // once we have a booted system.
3029        mInstaller.setWarnIfHeld(mPackages);
3030
3031        // Expose private service for system components to use.
3032        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034    }
3035
3036    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3037        // we're only interested in updating the installer appliction when 1) it's not
3038        // already set or 2) the modified package is the installer
3039        if (mInstantAppInstallerActivity != null
3040                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3041                        .equals(modifiedPackage)) {
3042            return;
3043        }
3044        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3045    }
3046
3047    private static File preparePackageParserCache(boolean isUpgrade) {
3048        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3049            return null;
3050        }
3051
3052        // Disable package parsing on eng builds to allow for faster incremental development.
3053        if ("eng".equals(Build.TYPE)) {
3054            return null;
3055        }
3056
3057        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3058            Slog.i(TAG, "Disabling package parser cache due to system property.");
3059            return null;
3060        }
3061
3062        // The base directory for the package parser cache lives under /data/system/.
3063        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3064                "package_cache");
3065        if (cacheBaseDir == null) {
3066            return null;
3067        }
3068
3069        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3070        // This also serves to "GC" unused entries when the package cache version changes (which
3071        // can only happen during upgrades).
3072        if (isUpgrade) {
3073            FileUtils.deleteContents(cacheBaseDir);
3074        }
3075
3076
3077        // Return the versioned package cache directory. This is something like
3078        // "/data/system/package_cache/1"
3079        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080
3081        // The following is a workaround to aid development on non-numbered userdebug
3082        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3083        // the system partition is newer.
3084        //
3085        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3086        // that starts with "eng." to signify that this is an engineering build and not
3087        // destined for release.
3088        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3089            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3090
3091            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3092            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3093            // in general and should not be used for production changes. In this specific case,
3094            // we know that they will work.
3095            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3096            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3097                FileUtils.deleteContents(cacheBaseDir);
3098                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3099            }
3100        }
3101
3102        return cacheDir;
3103    }
3104
3105    @Override
3106    public boolean isFirstBoot() {
3107        // allow instant applications
3108        return mFirstBoot;
3109    }
3110
3111    @Override
3112    public boolean isOnlyCoreApps() {
3113        // allow instant applications
3114        return mOnlyCore;
3115    }
3116
3117    @Override
3118    public boolean isUpgrade() {
3119        // allow instant applications
3120        return mIsUpgrade;
3121    }
3122
3123    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3125
3126        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            return matches.get(0).getComponentInfo().packageName;
3131        } else if (matches.size() == 0) {
3132            Log.e(TAG, "There should probably be a verifier, but, none were found");
3133            return null;
3134        }
3135        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3136    }
3137
3138    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3139        synchronized (mPackages) {
3140            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3141            if (libraryEntry == null) {
3142                throw new IllegalStateException("Missing required shared library:" + name);
3143            }
3144            return libraryEntry.apk;
3145        }
3146    }
3147
3148    private @NonNull String getRequiredInstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3152
3153        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (matches.size() == 1) {
3157            ResolveInfo resolveInfo = matches.get(0);
3158            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3159                throw new RuntimeException("The installer must be a privileged app");
3160            }
3161            return matches.get(0).getComponentInfo().packageName;
3162        } else {
3163            throw new RuntimeException("There must be exactly one installer; found " + matches);
3164        }
3165    }
3166
3167    private @NonNull String getRequiredUninstallerLPr() {
3168        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3169        intent.addCategory(Intent.CATEGORY_DEFAULT);
3170        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3171
3172        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3173                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3174                UserHandle.USER_SYSTEM);
3175        if (resolveInfo == null ||
3176                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3177            throw new RuntimeException("There must be exactly one uninstaller; found "
3178                    + resolveInfo);
3179        }
3180        return resolveInfo.getComponentInfo().packageName;
3181    }
3182
3183    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3184        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3185
3186        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3187                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3188                UserHandle.USER_SYSTEM);
3189        ResolveInfo best = null;
3190        final int N = matches.size();
3191        for (int i = 0; i < N; i++) {
3192            final ResolveInfo cur = matches.get(i);
3193            final String packageName = cur.getComponentInfo().packageName;
3194            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3195                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3196                continue;
3197            }
3198
3199            if (best == null || cur.priority > best.priority) {
3200                best = cur;
3201            }
3202        }
3203
3204        if (best != null) {
3205            return best.getComponentInfo().getComponentName();
3206        }
3207        Slog.w(TAG, "Intent filter verifier not found");
3208        return null;
3209    }
3210
3211    @Override
3212    public @Nullable ComponentName getInstantAppResolverComponent() {
3213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3214            return null;
3215        }
3216        synchronized (mPackages) {
3217            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3218            if (instantAppResolver == null) {
3219                return null;
3220            }
3221            return instantAppResolver.first;
3222        }
3223    }
3224
3225    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3226        final String[] packageArray =
3227                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3228        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3229            if (DEBUG_EPHEMERAL) {
3230                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231            }
3232            return null;
3233        }
3234
3235        final int callingUid = Binder.getCallingUid();
3236        final int resolveFlags =
3237                MATCH_DIRECT_BOOT_AWARE
3238                | MATCH_DIRECT_BOOT_UNAWARE
3239                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3240        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3241        final Intent resolverIntent = new Intent(actionName);
3242        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3243                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3244        // temporarily look for the old action
3245        if (resolvers.size() == 0) {
3246            if (DEBUG_EPHEMERAL) {
3247                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3248            }
3249            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3250            resolverIntent.setAction(actionName);
3251            resolvers = queryIntentServicesInternal(resolverIntent, null,
3252                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3253        }
3254        final int N = resolvers.size();
3255        if (N == 0) {
3256            if (DEBUG_EPHEMERAL) {
3257                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258            }
3259            return null;
3260        }
3261
3262        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3263        for (int i = 0; i < N; i++) {
3264            final ResolveInfo info = resolvers.get(i);
3265
3266            if (info.serviceInfo == null) {
3267                continue;
3268            }
3269
3270            final String packageName = info.serviceInfo.packageName;
3271            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3272                if (DEBUG_EPHEMERAL) {
3273                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3274                            + " pkg: " + packageName + ", info:" + info);
3275                }
3276                continue;
3277            }
3278
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.v(TAG, "Ephemeral resolver found;"
3281                        + " pkg: " + packageName + ", info:" + info);
3282            }
3283            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3284        }
3285        if (DEBUG_EPHEMERAL) {
3286            Slog.v(TAG, "Ephemeral resolver NOT found");
3287        }
3288        return null;
3289    }
3290
3291    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3292        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3293        intent.addCategory(Intent.CATEGORY_DEFAULT);
3294        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3295
3296        final int resolveFlags =
3297                MATCH_DIRECT_BOOT_AWARE
3298                | MATCH_DIRECT_BOOT_UNAWARE
3299                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3300        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3301                resolveFlags, UserHandle.USER_SYSTEM);
3302        // temporarily look for the old action
3303        if (matches.isEmpty()) {
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3306            }
3307            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3308            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3309                    resolveFlags, UserHandle.USER_SYSTEM);
3310        }
3311        Iterator<ResolveInfo> iter = matches.iterator();
3312        while (iter.hasNext()) {
3313            final ResolveInfo rInfo = iter.next();
3314            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3315            if (ps != null) {
3316                final PermissionsState permissionsState = ps.getPermissionsState();
3317                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318                    continue;
3319                }
3320            }
3321            iter.remove();
3322        }
3323        if (matches.size() == 0) {
3324            return null;
3325        } else if (matches.size() == 1) {
3326            return (ActivityInfo) matches.get(0).getComponentInfo();
3327        } else {
3328            throw new RuntimeException(
3329                    "There must be at most one ephemeral installer; found " + matches);
3330        }
3331    }
3332
3333    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3334            @NonNull ComponentName resolver) {
3335        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3336                .addCategory(Intent.CATEGORY_DEFAULT)
3337                .setPackage(resolver.getPackageName());
3338        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3339        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3340                UserHandle.USER_SYSTEM);
3341        // temporarily look for the old action
3342        if (matches.isEmpty()) {
3343            if (DEBUG_EPHEMERAL) {
3344                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3345            }
3346            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3347            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3348                    UserHandle.USER_SYSTEM);
3349        }
3350        if (matches.isEmpty()) {
3351            return null;
3352        }
3353        return matches.get(0).getComponentInfo().getComponentName();
3354    }
3355
3356    private void primeDomainVerificationsLPw(int userId) {
3357        if (DEBUG_DOMAIN_VERIFICATION) {
3358            Slog.d(TAG, "Priming domain verifications in user " + userId);
3359        }
3360
3361        SystemConfig systemConfig = SystemConfig.getInstance();
3362        ArraySet<String> packages = systemConfig.getLinkedApps();
3363
3364        for (String packageName : packages) {
3365            PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg != null) {
3367                if (!pkg.isSystemApp()) {
3368                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3369                    continue;
3370                }
3371
3372                ArraySet<String> domains = null;
3373                for (PackageParser.Activity a : pkg.activities) {
3374                    for (ActivityIntentInfo filter : a.intents) {
3375                        if (hasValidDomains(filter)) {
3376                            if (domains == null) {
3377                                domains = new ArraySet<String>();
3378                            }
3379                            domains.addAll(filter.getHostsList());
3380                        }
3381                    }
3382                }
3383
3384                if (domains != null && domains.size() > 0) {
3385                    if (DEBUG_DOMAIN_VERIFICATION) {
3386                        Slog.v(TAG, "      + " + packageName);
3387                    }
3388                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3389                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3390                    // and then 'always' in the per-user state actually used for intent resolution.
3391                    final IntentFilterVerificationInfo ivi;
3392                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3393                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3394                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3395                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3396                } else {
3397                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3398                            + "' does not handle web links");
3399                }
3400            } else {
3401                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3402            }
3403        }
3404
3405        scheduleWritePackageRestrictionsLocked(userId);
3406        scheduleWriteSettingsLocked();
3407    }
3408
3409    private void applyFactoryDefaultBrowserLPw(int userId) {
3410        // The default browser app's package name is stored in a string resource,
3411        // with a product-specific overlay used for vendor customization.
3412        String browserPkg = mContext.getResources().getString(
3413                com.android.internal.R.string.default_browser);
3414        if (!TextUtils.isEmpty(browserPkg)) {
3415            // non-empty string => required to be a known package
3416            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3417            if (ps == null) {
3418                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3419                browserPkg = null;
3420            } else {
3421                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3422            }
3423        }
3424
3425        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3426        // default.  If there's more than one, just leave everything alone.
3427        if (browserPkg == null) {
3428            calculateDefaultBrowserLPw(userId);
3429        }
3430    }
3431
3432    private void calculateDefaultBrowserLPw(int userId) {
3433        List<String> allBrowsers = resolveAllBrowserApps(userId);
3434        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3435        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3436    }
3437
3438    private List<String> resolveAllBrowserApps(int userId) {
3439        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3440        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3441                PackageManager.MATCH_ALL, userId);
3442
3443        final int count = list.size();
3444        List<String> result = new ArrayList<String>(count);
3445        for (int i=0; i<count; i++) {
3446            ResolveInfo info = list.get(i);
3447            if (info.activityInfo == null
3448                    || !info.handleAllWebDataURI
3449                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3450                    || result.contains(info.activityInfo.packageName)) {
3451                continue;
3452            }
3453            result.add(info.activityInfo.packageName);
3454        }
3455
3456        return result;
3457    }
3458
3459    private boolean packageIsBrowser(String packageName, int userId) {
3460        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3461                PackageManager.MATCH_ALL, userId);
3462        final int N = list.size();
3463        for (int i = 0; i < N; i++) {
3464            ResolveInfo info = list.get(i);
3465            if (packageName.equals(info.activityInfo.packageName)) {
3466                return true;
3467            }
3468        }
3469        return false;
3470    }
3471
3472    private void checkDefaultBrowser() {
3473        final int myUserId = UserHandle.myUserId();
3474        final String packageName = getDefaultBrowserPackageName(myUserId);
3475        if (packageName != null) {
3476            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3477            if (info == null) {
3478                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3479                synchronized (mPackages) {
3480                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3481                }
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3488            throws RemoteException {
3489        try {
3490            return super.onTransact(code, data, reply, flags);
3491        } catch (RuntimeException e) {
3492            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3493                Slog.wtf(TAG, "Package Manager Crash", e);
3494            }
3495            throw e;
3496        }
3497    }
3498
3499    static int[] appendInts(int[] cur, int[] add) {
3500        if (add == null) return cur;
3501        if (cur == null) return add;
3502        final int N = add.length;
3503        for (int i=0; i<N; i++) {
3504            cur = appendInt(cur, add[i]);
3505        }
3506        return cur;
3507    }
3508
3509    /**
3510     * Returns whether or not a full application can see an instant application.
3511     * <p>
3512     * Currently, there are three cases in which this can occur:
3513     * <ol>
3514     * <li>The calling application is a "special" process. The special
3515     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3516     *     and {@code 0}</li>
3517     * <li>The calling application has the permission
3518     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3519     * <li>The calling application is the default launcher on the
3520     *     system partition.</li>
3521     * </ol>
3522     */
3523    private boolean canViewInstantApps(int callingUid, int userId) {
3524        if (callingUid == Process.SYSTEM_UID
3525                || callingUid == Process.SHELL_UID
3526                || callingUid == Process.ROOT_UID) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            return true;
3532        }
3533        if (mContext.checkCallingOrSelfPermission(
3534                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3535            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3536            if (homeComponent != null
3537                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3538                return true;
3539            }
3540        }
3541        return false;
3542    }
3543
3544    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        if (ps == null) {
3547            return null;
3548        }
3549        PackageParser.Package p = ps.pkg;
3550        if (p == null) {
3551            return null;
3552        }
3553        final int callingUid = Binder.getCallingUid();
3554        // Filter out ephemeral app metadata:
3555        //   * The system/shell/root can see metadata for any app
3556        //   * An installed app can see metadata for 1) other installed apps
3557        //     and 2) ephemeral apps that have explicitly interacted with it
3558        //   * Ephemeral apps can only see their own data and exposed installed apps
3559        //   * Holding a signature permission allows seeing instant apps
3560        if (filterAppAccessLPr(ps, callingUid, userId)) {
3561            return null;
3562        }
3563
3564        final PermissionsState permissionsState = ps.getPermissionsState();
3565
3566        // Compute GIDs only if requested
3567        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3568                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3569        // Compute granted permissions only if package has requested permissions
3570        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3571                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3572        final PackageUserState state = ps.readUserState(userId);
3573
3574        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3575                && ps.isSystem()) {
3576            flags |= MATCH_ANY_USER;
3577        }
3578
3579        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3580                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3581
3582        if (packageInfo == null) {
3583            return null;
3584        }
3585
3586        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3587                resolveExternalPackageNameLPr(p);
3588
3589        return packageInfo;
3590    }
3591
3592    @Override
3593    public void checkPackageStartable(String packageName, int userId) {
3594        final int callingUid = Binder.getCallingUid();
3595        if (getInstantAppPackageName(callingUid) != null) {
3596            throw new SecurityException("Instant applications don't have access to this method");
3597        }
3598        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3599        synchronized (mPackages) {
3600            final PackageSetting ps = mSettings.mPackages.get(packageName);
3601            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3602                throw new SecurityException("Package " + packageName + " was not found!");
3603            }
3604
3605            if (!ps.getInstalled(userId)) {
3606                throw new SecurityException(
3607                        "Package " + packageName + " was not installed for user " + userId + "!");
3608            }
3609
3610            if (mSafeMode && !ps.isSystem()) {
3611                throw new SecurityException("Package " + packageName + " not a system app!");
3612            }
3613
3614            if (mFrozenPackages.contains(packageName)) {
3615                throw new SecurityException("Package " + packageName + " is currently frozen!");
3616            }
3617
3618            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3619                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3620                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3621            }
3622        }
3623    }
3624
3625    @Override
3626    public boolean isPackageAvailable(String packageName, int userId) {
3627        if (!sUserManager.exists(userId)) return false;
3628        final int callingUid = Binder.getCallingUid();
3629        enforceCrossUserPermission(callingUid, userId,
3630                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3631        synchronized (mPackages) {
3632            PackageParser.Package p = mPackages.get(packageName);
3633            if (p != null) {
3634                final PackageSetting ps = (PackageSetting) p.mExtras;
3635                if (filterAppAccessLPr(ps, callingUid, userId)) {
3636                    return false;
3637                }
3638                if (ps != null) {
3639                    final PackageUserState state = ps.readUserState(userId);
3640                    if (state != null) {
3641                        return PackageParser.isAvailable(state);
3642                    }
3643                }
3644            }
3645        }
3646        return false;
3647    }
3648
3649    @Override
3650    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3651        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3652                flags, Binder.getCallingUid(), userId);
3653    }
3654
3655    @Override
3656    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3657            int flags, int userId) {
3658        return getPackageInfoInternal(versionedPackage.getPackageName(),
3659                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3660    }
3661
3662    /**
3663     * Important: The provided filterCallingUid is used exclusively to filter out packages
3664     * that can be seen based on user state. It's typically the original caller uid prior
3665     * to clearing. Because it can only be provided by trusted code, it's value can be
3666     * trusted and will be used as-is; unlike userId which will be validated by this method.
3667     */
3668    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3669            int flags, int filterCallingUid, int userId) {
3670        if (!sUserManager.exists(userId)) return null;
3671        flags = updateFlagsForPackage(flags, userId, packageName);
3672        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3673                false /* requireFullPermission */, false /* checkShell */, "get package info");
3674
3675        // reader
3676        synchronized (mPackages) {
3677            // Normalize package name to handle renamed packages and static libs
3678            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3679
3680            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3681            if (matchFactoryOnly) {
3682                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3683                if (ps != null) {
3684                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3685                        return null;
3686                    }
3687                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3688                        return null;
3689                    }
3690                    return generatePackageInfo(ps, flags, userId);
3691                }
3692            }
3693
3694            PackageParser.Package p = mPackages.get(packageName);
3695            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3696                return null;
3697            }
3698            if (DEBUG_PACKAGE_INFO)
3699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3700            if (p != null) {
3701                final PackageSetting ps = (PackageSetting) p.mExtras;
3702                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3703                    return null;
3704                }
3705                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3706                    return null;
3707                }
3708                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3709            }
3710            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3711                final PackageSetting ps = mSettings.mPackages.get(packageName);
3712                if (ps == null) return null;
3713                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3714                    return null;
3715                }
3716                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3717                    return null;
3718                }
3719                return generatePackageInfo(ps, flags, userId);
3720            }
3721        }
3722        return null;
3723    }
3724
3725    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3726        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3727            return true;
3728        }
3729        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3733            return true;
3734        }
3735        return false;
3736    }
3737
3738    private boolean isComponentVisibleToInstantApp(
3739            @Nullable ComponentName component, @ComponentType int type) {
3740        if (type == TYPE_ACTIVITY) {
3741            final PackageParser.Activity activity = mActivities.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_RECEIVER) {
3746            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3747            return activity != null
3748                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3749                    : false;
3750        } else if (type == TYPE_SERVICE) {
3751            final PackageParser.Service service = mServices.mServices.get(component);
3752            return service != null
3753                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3754                    : false;
3755        } else if (type == TYPE_PROVIDER) {
3756            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3757            return provider != null
3758                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3759                    : false;
3760        } else if (type == TYPE_UNKNOWN) {
3761            return isComponentVisibleToInstantApp(component);
3762        }
3763        return false;
3764    }
3765
3766    /**
3767     * Returns whether or not access to the application should be filtered.
3768     * <p>
3769     * Access may be limited based upon whether the calling or target applications
3770     * are instant applications.
3771     *
3772     * @see #canAccessInstantApps(int)
3773     */
3774    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3775            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3776        // if we're in an isolated process, get the real calling UID
3777        if (Process.isIsolated(callingUid)) {
3778            callingUid = mIsolatedOwners.get(callingUid);
3779        }
3780        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3781        final boolean callerIsInstantApp = instantAppPkgName != null;
3782        if (ps == null) {
3783            if (callerIsInstantApp) {
3784                // pretend the application exists, but, needs to be filtered
3785                return true;
3786            }
3787            return false;
3788        }
3789        // if the target and caller are the same application, don't filter
3790        if (isCallerSameApp(ps.name, callingUid)) {
3791            return false;
3792        }
3793        if (callerIsInstantApp) {
3794            // request for a specific component; if it hasn't been explicitly exposed, filter
3795            if (component != null) {
3796                return !isComponentVisibleToInstantApp(component, componentType);
3797            }
3798            // request for application; if no components have been explicitly exposed, filter
3799            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3800        }
3801        if (ps.getInstantApp(userId)) {
3802            // caller can see all components of all instant applications, don't filter
3803            if (canViewInstantApps(callingUid, userId)) {
3804                return false;
3805            }
3806            // request for a specific instant application component, filter
3807            if (component != null) {
3808                return true;
3809            }
3810            // request for an instant application; if the caller hasn't been granted access, filter
3811            return !mInstantAppRegistry.isInstantAccessGranted(
3812                    userId, UserHandle.getAppId(callingUid), ps.appId);
3813        }
3814        return false;
3815    }
3816
3817    /**
3818     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3819     */
3820    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3821        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3822    }
3823
3824    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3825            int flags) {
3826        // Callers can access only the libs they depend on, otherwise they need to explicitly
3827        // ask for the shared libraries given the caller is allowed to access all static libs.
3828        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3829            // System/shell/root get to see all static libs
3830            final int appId = UserHandle.getAppId(uid);
3831            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3832                    || appId == Process.ROOT_UID) {
3833                return false;
3834            }
3835        }
3836
3837        // No package means no static lib as it is always on internal storage
3838        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3839            return false;
3840        }
3841
3842        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3843                ps.pkg.staticSharedLibVersion);
3844        if (libEntry == null) {
3845            return false;
3846        }
3847
3848        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3849        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3850        if (uidPackageNames == null) {
3851            return true;
3852        }
3853
3854        for (String uidPackageName : uidPackageNames) {
3855            if (ps.name.equals(uidPackageName)) {
3856                return false;
3857            }
3858            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3859            if (uidPs != null) {
3860                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3861                        libEntry.info.getName());
3862                if (index < 0) {
3863                    continue;
3864                }
3865                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3866                    return false;
3867                }
3868            }
3869        }
3870        return true;
3871    }
3872
3873    @Override
3874    public String[] currentToCanonicalPackageNames(String[] names) {
3875        final int callingUid = Binder.getCallingUid();
3876        if (getInstantAppPackageName(callingUid) != null) {
3877            return names;
3878        }
3879        final String[] out = new String[names.length];
3880        // reader
3881        synchronized (mPackages) {
3882            final int callingUserId = UserHandle.getUserId(callingUid);
3883            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3884            for (int i=names.length-1; i>=0; i--) {
3885                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3886                boolean translateName = false;
3887                if (ps != null && ps.realName != null) {
3888                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3889                    translateName = !targetIsInstantApp
3890                            || canViewInstantApps
3891                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3892                                    UserHandle.getAppId(callingUid), ps.appId);
3893                }
3894                out[i] = translateName ? ps.realName : names[i];
3895            }
3896        }
3897        return out;
3898    }
3899
3900    @Override
3901    public String[] canonicalToCurrentPackageNames(String[] names) {
3902        final int callingUid = Binder.getCallingUid();
3903        if (getInstantAppPackageName(callingUid) != null) {
3904            return names;
3905        }
3906        final String[] out = new String[names.length];
3907        // reader
3908        synchronized (mPackages) {
3909            final int callingUserId = UserHandle.getUserId(callingUid);
3910            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3911            for (int i=names.length-1; i>=0; i--) {
3912                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3913                boolean translateName = false;
3914                if (cur != null) {
3915                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3916                    final boolean targetIsInstantApp =
3917                            ps != null && ps.getInstantApp(callingUserId);
3918                    translateName = !targetIsInstantApp
3919                            || canViewInstantApps
3920                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3921                                    UserHandle.getAppId(callingUid), ps.appId);
3922                }
3923                out[i] = translateName ? cur : names[i];
3924            }
3925        }
3926        return out;
3927    }
3928
3929    @Override
3930    public int getPackageUid(String packageName, int flags, int userId) {
3931        if (!sUserManager.exists(userId)) return -1;
3932        final int callingUid = Binder.getCallingUid();
3933        flags = updateFlagsForPackage(flags, userId, packageName);
3934        enforceCrossUserPermission(callingUid, userId,
3935                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3936
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Package p = mPackages.get(packageName);
3940            if (p != null && p.isMatch(flags)) {
3941                PackageSetting ps = (PackageSetting) p.mExtras;
3942                if (filterAppAccessLPr(ps, callingUid, userId)) {
3943                    return -1;
3944                }
3945                return UserHandle.getUid(userId, p.applicationInfo.uid);
3946            }
3947            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3948                final PackageSetting ps = mSettings.mPackages.get(packageName);
3949                if (ps != null && ps.isMatch(flags)
3950                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3951                    return UserHandle.getUid(userId, ps.appId);
3952                }
3953            }
3954        }
3955
3956        return -1;
3957    }
3958
3959    @Override
3960    public int[] getPackageGids(String packageName, int flags, int userId) {
3961        if (!sUserManager.exists(userId)) return null;
3962        final int callingUid = Binder.getCallingUid();
3963        flags = updateFlagsForPackage(flags, userId, packageName);
3964        enforceCrossUserPermission(callingUid, userId,
3965                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3966
3967        // reader
3968        synchronized (mPackages) {
3969            final PackageParser.Package p = mPackages.get(packageName);
3970            if (p != null && p.isMatch(flags)) {
3971                PackageSetting ps = (PackageSetting) p.mExtras;
3972                if (filterAppAccessLPr(ps, callingUid, userId)) {
3973                    return null;
3974                }
3975                // TODO: Shouldn't this be checking for package installed state for userId and
3976                // return null?
3977                return ps.getPermissionsState().computeGids(userId);
3978            }
3979            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3980                final PackageSetting ps = mSettings.mPackages.get(packageName);
3981                if (ps != null && ps.isMatch(flags)
3982                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3983                    return ps.getPermissionsState().computeGids(userId);
3984                }
3985            }
3986        }
3987
3988        return null;
3989    }
3990
3991    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3992        if (bp.perm != null) {
3993            return PackageParser.generatePermissionInfo(bp.perm, flags);
3994        }
3995        PermissionInfo pi = new PermissionInfo();
3996        pi.name = bp.name;
3997        pi.packageName = bp.sourcePackage;
3998        pi.nonLocalizedLabel = bp.name;
3999        pi.protectionLevel = bp.protectionLevel;
4000        return pi;
4001    }
4002
4003    @Override
4004    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4005        final int callingUid = Binder.getCallingUid();
4006        if (getInstantAppPackageName(callingUid) != null) {
4007            return null;
4008        }
4009        // reader
4010        synchronized (mPackages) {
4011            final BasePermission p = mSettings.mPermissions.get(name);
4012            if (p == null) {
4013                return null;
4014            }
4015            // If the caller is an app that targets pre 26 SDK drop protection flags.
4016            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4017            if (permissionInfo != null) {
4018                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4019                        permissionInfo.protectionLevel, packageName, callingUid);
4020            }
4021            return permissionInfo;
4022        }
4023    }
4024
4025    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4026            String packageName, int uid) {
4027        // Signature permission flags area always reported
4028        final int protectionLevelMasked = protectionLevel
4029                & (PermissionInfo.PROTECTION_NORMAL
4030                | PermissionInfo.PROTECTION_DANGEROUS
4031                | PermissionInfo.PROTECTION_SIGNATURE);
4032        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4033            return protectionLevel;
4034        }
4035
4036        // System sees all flags.
4037        final int appId = UserHandle.getAppId(uid);
4038        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4039                || appId == Process.SHELL_UID) {
4040            return protectionLevel;
4041        }
4042
4043        // Normalize package name to handle renamed packages and static libs
4044        packageName = resolveInternalPackageNameLPr(packageName,
4045                PackageManager.VERSION_CODE_HIGHEST);
4046
4047        // Apps that target O see flags for all protection levels.
4048        final PackageSetting ps = mSettings.mPackages.get(packageName);
4049        if (ps == null) {
4050            return protectionLevel;
4051        }
4052        if (ps.appId != appId) {
4053            return protectionLevel;
4054        }
4055
4056        final PackageParser.Package pkg = mPackages.get(packageName);
4057        if (pkg == null) {
4058            return protectionLevel;
4059        }
4060        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4061            return protectionLevelMasked;
4062        }
4063
4064        return protectionLevel;
4065    }
4066
4067    @Override
4068    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4069            int flags) {
4070        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4071            return null;
4072        }
4073        // reader
4074        synchronized (mPackages) {
4075            if (group != null && !mPermissionGroups.containsKey(group)) {
4076                // This is thrown as NameNotFoundException
4077                return null;
4078            }
4079
4080            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4081            for (BasePermission p : mSettings.mPermissions.values()) {
4082                if (group == null) {
4083                    if (p.perm == null || p.perm.info.group == null) {
4084                        out.add(generatePermissionInfo(p, flags));
4085                    }
4086                } else {
4087                    if (p.perm != null && group.equals(p.perm.info.group)) {
4088                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4089                    }
4090                }
4091            }
4092            return new ParceledListSlice<>(out);
4093        }
4094    }
4095
4096    @Override
4097    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4098        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4099            return null;
4100        }
4101        // reader
4102        synchronized (mPackages) {
4103            return PackageParser.generatePermissionGroupInfo(
4104                    mPermissionGroups.get(name), flags);
4105        }
4106    }
4107
4108    @Override
4109    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4110        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4111            return ParceledListSlice.emptyList();
4112        }
4113        // reader
4114        synchronized (mPackages) {
4115            final int N = mPermissionGroups.size();
4116            ArrayList<PermissionGroupInfo> out
4117                    = new ArrayList<PermissionGroupInfo>(N);
4118            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4119                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4120            }
4121            return new ParceledListSlice<>(out);
4122        }
4123    }
4124
4125    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4126            int filterCallingUid, int userId) {
4127        if (!sUserManager.exists(userId)) return null;
4128        PackageSetting ps = mSettings.mPackages.get(packageName);
4129        if (ps != null) {
4130            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4131                return null;
4132            }
4133            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4134                return null;
4135            }
4136            if (ps.pkg == null) {
4137                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4138                if (pInfo != null) {
4139                    return pInfo.applicationInfo;
4140                }
4141                return null;
4142            }
4143            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4144                    ps.readUserState(userId), userId);
4145            if (ai != null) {
4146                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4147            }
4148            return ai;
4149        }
4150        return null;
4151    }
4152
4153    @Override
4154    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4155        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4156    }
4157
4158    /**
4159     * Important: The provided filterCallingUid is used exclusively to filter out applications
4160     * that can be seen based on user state. It's typically the original caller uid prior
4161     * to clearing. Because it can only be provided by trusted code, it's value can be
4162     * trusted and will be used as-is; unlike userId which will be validated by this method.
4163     */
4164    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4165            int filterCallingUid, int userId) {
4166        if (!sUserManager.exists(userId)) return null;
4167        flags = updateFlagsForApplication(flags, userId, packageName);
4168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4169                false /* requireFullPermission */, false /* checkShell */, "get application info");
4170
4171        // writer
4172        synchronized (mPackages) {
4173            // Normalize package name to handle renamed packages and static libs
4174            packageName = resolveInternalPackageNameLPr(packageName,
4175                    PackageManager.VERSION_CODE_HIGHEST);
4176
4177            PackageParser.Package p = mPackages.get(packageName);
4178            if (DEBUG_PACKAGE_INFO) Log.v(
4179                    TAG, "getApplicationInfo " + packageName
4180                    + ": " + p);
4181            if (p != null) {
4182                PackageSetting ps = mSettings.mPackages.get(packageName);
4183                if (ps == null) return null;
4184                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4185                    return null;
4186                }
4187                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4188                    return null;
4189                }
4190                // Note: isEnabledLP() does not apply here - always return info
4191                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4192                        p, flags, ps.readUserState(userId), userId);
4193                if (ai != null) {
4194                    ai.packageName = resolveExternalPackageNameLPr(p);
4195                }
4196                return ai;
4197            }
4198            if ("android".equals(packageName)||"system".equals(packageName)) {
4199                return mAndroidApplication;
4200            }
4201            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4202                // Already generates the external package name
4203                return generateApplicationInfoFromSettingsLPw(packageName,
4204                        flags, filterCallingUid, userId);
4205            }
4206        }
4207        return null;
4208    }
4209
4210    private String normalizePackageNameLPr(String packageName) {
4211        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4212        return normalizedPackageName != null ? normalizedPackageName : packageName;
4213    }
4214
4215    @Override
4216    public void deletePreloadsFileCache() {
4217        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4218            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4219        }
4220        File dir = Environment.getDataPreloadsFileCacheDirectory();
4221        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4222        FileUtils.deleteContents(dir);
4223    }
4224
4225    @Override
4226    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4227            final int storageFlags, final IPackageDataObserver observer) {
4228        mContext.enforceCallingOrSelfPermission(
4229                android.Manifest.permission.CLEAR_APP_CACHE, null);
4230        mHandler.post(() -> {
4231            boolean success = false;
4232            try {
4233                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4234                success = true;
4235            } catch (IOException e) {
4236                Slog.w(TAG, e);
4237            }
4238            if (observer != null) {
4239                try {
4240                    observer.onRemoveCompleted(null, success);
4241                } catch (RemoteException e) {
4242                    Slog.w(TAG, e);
4243                }
4244            }
4245        });
4246    }
4247
4248    @Override
4249    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4250            final int storageFlags, final IntentSender pi) {
4251        mContext.enforceCallingOrSelfPermission(
4252                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4253        mHandler.post(() -> {
4254            boolean success = false;
4255            try {
4256                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4257                success = true;
4258            } catch (IOException e) {
4259                Slog.w(TAG, e);
4260            }
4261            if (pi != null) {
4262                try {
4263                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4264                } catch (SendIntentException e) {
4265                    Slog.w(TAG, e);
4266                }
4267            }
4268        });
4269    }
4270
4271    /**
4272     * Blocking call to clear various types of cached data across the system
4273     * until the requested bytes are available.
4274     */
4275    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4276        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4277        final File file = storage.findPathForUuid(volumeUuid);
4278        if (file.getUsableSpace() >= bytes) return;
4279
4280        if (ENABLE_FREE_CACHE_V2) {
4281            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4282                    volumeUuid);
4283            final boolean aggressive = (storageFlags
4284                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4285            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4286
4287            // 1. Pre-flight to determine if we have any chance to succeed
4288            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4289            if (internalVolume && (aggressive || SystemProperties
4290                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4291                deletePreloadsFileCache();
4292                if (file.getUsableSpace() >= bytes) return;
4293            }
4294
4295            // 3. Consider parsed APK data (aggressive only)
4296            if (internalVolume && aggressive) {
4297                FileUtils.deleteContents(mCacheDir);
4298                if (file.getUsableSpace() >= bytes) return;
4299            }
4300
4301            // 4. Consider cached app data (above quotas)
4302            try {
4303                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4304                        Installer.FLAG_FREE_CACHE_V2);
4305            } catch (InstallerException ignored) {
4306            }
4307            if (file.getUsableSpace() >= bytes) return;
4308
4309            // 5. Consider shared libraries with refcount=0 and age>min cache period
4310            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4311                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4312                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4313                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4314                return;
4315            }
4316
4317            // 6. Consider dexopt output (aggressive only)
4318            // TODO: Implement
4319
4320            // 7. Consider installed instant apps unused longer than min cache period
4321            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4322                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4323                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4324                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4325                return;
4326            }
4327
4328            // 8. Consider cached app data (below quotas)
4329            try {
4330                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4331                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4332            } catch (InstallerException ignored) {
4333            }
4334            if (file.getUsableSpace() >= bytes) return;
4335
4336            // 9. Consider DropBox entries
4337            // TODO: Implement
4338
4339            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4340            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4341                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4342                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4343                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4344                return;
4345            }
4346        } else {
4347            try {
4348                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4349            } catch (InstallerException ignored) {
4350            }
4351            if (file.getUsableSpace() >= bytes) return;
4352        }
4353
4354        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4355    }
4356
4357    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4358            throws IOException {
4359        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4360        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4361
4362        List<VersionedPackage> packagesToDelete = null;
4363        final long now = System.currentTimeMillis();
4364
4365        synchronized (mPackages) {
4366            final int[] allUsers = sUserManager.getUserIds();
4367            final int libCount = mSharedLibraries.size();
4368            for (int i = 0; i < libCount; i++) {
4369                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4370                if (versionedLib == null) {
4371                    continue;
4372                }
4373                final int versionCount = versionedLib.size();
4374                for (int j = 0; j < versionCount; j++) {
4375                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4376                    // Skip packages that are not static shared libs.
4377                    if (!libInfo.isStatic()) {
4378                        break;
4379                    }
4380                    // Important: We skip static shared libs used for some user since
4381                    // in such a case we need to keep the APK on the device. The check for
4382                    // a lib being used for any user is performed by the uninstall call.
4383                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4384                    // Resolve the package name - we use synthetic package names internally
4385                    final String internalPackageName = resolveInternalPackageNameLPr(
4386                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4387                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4388                    // Skip unused static shared libs cached less than the min period
4389                    // to prevent pruning a lib needed by a subsequently installed package.
4390                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4391                        continue;
4392                    }
4393                    if (packagesToDelete == null) {
4394                        packagesToDelete = new ArrayList<>();
4395                    }
4396                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4397                            declaringPackage.getVersionCode()));
4398                }
4399            }
4400        }
4401
4402        if (packagesToDelete != null) {
4403            final int packageCount = packagesToDelete.size();
4404            for (int i = 0; i < packageCount; i++) {
4405                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4406                // Delete the package synchronously (will fail of the lib used for any user).
4407                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4408                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4409                                == PackageManager.DELETE_SUCCEEDED) {
4410                    if (volume.getUsableSpace() >= neededSpace) {
4411                        return true;
4412                    }
4413                }
4414            }
4415        }
4416
4417        return false;
4418    }
4419
4420    /**
4421     * Update given flags based on encryption status of current user.
4422     */
4423    private int updateFlags(int flags, int userId) {
4424        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4425                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4426            // Caller expressed an explicit opinion about what encryption
4427            // aware/unaware components they want to see, so fall through and
4428            // give them what they want
4429        } else {
4430            // Caller expressed no opinion, so match based on user state
4431            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4432                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4433            } else {
4434                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4435            }
4436        }
4437        return flags;
4438    }
4439
4440    private UserManagerInternal getUserManagerInternal() {
4441        if (mUserManagerInternal == null) {
4442            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4443        }
4444        return mUserManagerInternal;
4445    }
4446
4447    private DeviceIdleController.LocalService getDeviceIdleController() {
4448        if (mDeviceIdleController == null) {
4449            mDeviceIdleController =
4450                    LocalServices.getService(DeviceIdleController.LocalService.class);
4451        }
4452        return mDeviceIdleController;
4453    }
4454
4455    /**
4456     * Update given flags when being used to request {@link PackageInfo}.
4457     */
4458    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4459        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4460        boolean triaged = true;
4461        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4462                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4463            // Caller is asking for component details, so they'd better be
4464            // asking for specific encryption matching behavior, or be triaged
4465            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4466                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4467                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4468                triaged = false;
4469            }
4470        }
4471        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4472                | PackageManager.MATCH_SYSTEM_ONLY
4473                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4474            triaged = false;
4475        }
4476        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4477            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4478                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4479                    + Debug.getCallers(5));
4480        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4481                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4482            // If the caller wants all packages and has a restricted profile associated with it,
4483            // then match all users. This is to make sure that launchers that need to access work
4484            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4485            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4486            flags |= PackageManager.MATCH_ANY_USER;
4487        }
4488        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4489            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4490                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4491        }
4492        return updateFlags(flags, userId);
4493    }
4494
4495    /**
4496     * Update given flags when being used to request {@link ApplicationInfo}.
4497     */
4498    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4499        return updateFlagsForPackage(flags, userId, cookie);
4500    }
4501
4502    /**
4503     * Update given flags when being used to request {@link ComponentInfo}.
4504     */
4505    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4506        if (cookie instanceof Intent) {
4507            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4508                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4509            }
4510        }
4511
4512        boolean triaged = true;
4513        // Caller is asking for component details, so they'd better be
4514        // asking for specific encryption matching behavior, or be triaged
4515        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4516                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4517                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4518            triaged = false;
4519        }
4520        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4521            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4522                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4523        }
4524
4525        return updateFlags(flags, userId);
4526    }
4527
4528    /**
4529     * Update given intent when being used to request {@link ResolveInfo}.
4530     */
4531    private Intent updateIntentForResolve(Intent intent) {
4532        if (intent.getSelector() != null) {
4533            intent = intent.getSelector();
4534        }
4535        if (DEBUG_PREFERRED) {
4536            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4537        }
4538        return intent;
4539    }
4540
4541    /**
4542     * Update given flags when being used to request {@link ResolveInfo}.
4543     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4544     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4545     * flag set. However, this flag is only honoured in three circumstances:
4546     * <ul>
4547     * <li>when called from a system process</li>
4548     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4549     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4550     * action and a {@code android.intent.category.BROWSABLE} category</li>
4551     * </ul>
4552     */
4553    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4554        return updateFlagsForResolve(flags, userId, intent, callingUid,
4555                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4556    }
4557    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4558            boolean wantInstantApps) {
4559        return updateFlagsForResolve(flags, userId, intent, callingUid,
4560                wantInstantApps, false /*onlyExposedExplicitly*/);
4561    }
4562    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4563            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4564        // Safe mode means we shouldn't match any third-party components
4565        if (mSafeMode) {
4566            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4567        }
4568        if (getInstantAppPackageName(callingUid) != null) {
4569            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4570            if (onlyExposedExplicitly) {
4571                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4572            }
4573            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4574            flags |= PackageManager.MATCH_INSTANT;
4575        } else {
4576            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4577            final boolean allowMatchInstant =
4578                    (wantInstantApps
4579                            && Intent.ACTION_VIEW.equals(intent.getAction())
4580                            && hasWebURI(intent))
4581                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4582            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4583                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4584            if (!allowMatchInstant) {
4585                flags &= ~PackageManager.MATCH_INSTANT;
4586            }
4587        }
4588        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4589    }
4590
4591    @Override
4592    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4593        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4594    }
4595
4596    /**
4597     * Important: The provided filterCallingUid is used exclusively to filter out activities
4598     * that can be seen based on user state. It's typically the original caller uid prior
4599     * to clearing. Because it can only be provided by trusted code, it's value can be
4600     * trusted and will be used as-is; unlike userId which will be validated by this method.
4601     */
4602    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4603            int filterCallingUid, int userId) {
4604        if (!sUserManager.exists(userId)) return null;
4605        flags = updateFlagsForComponent(flags, userId, component);
4606        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4607                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4608        synchronized (mPackages) {
4609            PackageParser.Activity a = mActivities.mActivities.get(component);
4610
4611            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4612            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4613                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4614                if (ps == null) return null;
4615                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4616                    return null;
4617                }
4618                return PackageParser.generateActivityInfo(
4619                        a, flags, ps.readUserState(userId), userId);
4620            }
4621            if (mResolveComponentName.equals(component)) {
4622                return PackageParser.generateActivityInfo(
4623                        mResolveActivity, flags, new PackageUserState(), userId);
4624            }
4625        }
4626        return null;
4627    }
4628
4629    @Override
4630    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4631            String resolvedType) {
4632        synchronized (mPackages) {
4633            if (component.equals(mResolveComponentName)) {
4634                // The resolver supports EVERYTHING!
4635                return true;
4636            }
4637            final int callingUid = Binder.getCallingUid();
4638            final int callingUserId = UserHandle.getUserId(callingUid);
4639            PackageParser.Activity a = mActivities.mActivities.get(component);
4640            if (a == null) {
4641                return false;
4642            }
4643            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4644            if (ps == null) {
4645                return false;
4646            }
4647            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4648                return false;
4649            }
4650            for (int i=0; i<a.intents.size(); i++) {
4651                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4652                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4653                    return true;
4654                }
4655            }
4656            return false;
4657        }
4658    }
4659
4660    @Override
4661    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4662        if (!sUserManager.exists(userId)) return null;
4663        final int callingUid = Binder.getCallingUid();
4664        flags = updateFlagsForComponent(flags, userId, component);
4665        enforceCrossUserPermission(callingUid, userId,
4666                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4667        synchronized (mPackages) {
4668            PackageParser.Activity a = mReceivers.mActivities.get(component);
4669            if (DEBUG_PACKAGE_INFO) Log.v(
4670                TAG, "getReceiverInfo " + component + ": " + a);
4671            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4672                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4673                if (ps == null) return null;
4674                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4675                    return null;
4676                }
4677                return PackageParser.generateActivityInfo(
4678                        a, flags, ps.readUserState(userId), userId);
4679            }
4680        }
4681        return null;
4682    }
4683
4684    @Override
4685    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4686            int flags, int userId) {
4687        if (!sUserManager.exists(userId)) return null;
4688        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4689        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4690            return null;
4691        }
4692
4693        flags = updateFlagsForPackage(flags, userId, null);
4694
4695        final boolean canSeeStaticLibraries =
4696                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4697                        == PERMISSION_GRANTED
4698                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4699                        == PERMISSION_GRANTED
4700                || canRequestPackageInstallsInternal(packageName,
4701                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4702                        false  /* throwIfPermNotDeclared*/)
4703                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4704                        == PERMISSION_GRANTED;
4705
4706        synchronized (mPackages) {
4707            List<SharedLibraryInfo> result = null;
4708
4709            final int libCount = mSharedLibraries.size();
4710            for (int i = 0; i < libCount; i++) {
4711                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4712                if (versionedLib == null) {
4713                    continue;
4714                }
4715
4716                final int versionCount = versionedLib.size();
4717                for (int j = 0; j < versionCount; j++) {
4718                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4719                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4720                        break;
4721                    }
4722                    final long identity = Binder.clearCallingIdentity();
4723                    try {
4724                        PackageInfo packageInfo = getPackageInfoVersioned(
4725                                libInfo.getDeclaringPackage(), flags
4726                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4727                        if (packageInfo == null) {
4728                            continue;
4729                        }
4730                    } finally {
4731                        Binder.restoreCallingIdentity(identity);
4732                    }
4733
4734                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4735                            libInfo.getVersion(), libInfo.getType(),
4736                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4737                            flags, userId));
4738
4739                    if (result == null) {
4740                        result = new ArrayList<>();
4741                    }
4742                    result.add(resLibInfo);
4743                }
4744            }
4745
4746            return result != null ? new ParceledListSlice<>(result) : null;
4747        }
4748    }
4749
4750    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4751            SharedLibraryInfo libInfo, int flags, int userId) {
4752        List<VersionedPackage> versionedPackages = null;
4753        final int packageCount = mSettings.mPackages.size();
4754        for (int i = 0; i < packageCount; i++) {
4755            PackageSetting ps = mSettings.mPackages.valueAt(i);
4756
4757            if (ps == null) {
4758                continue;
4759            }
4760
4761            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4762                continue;
4763            }
4764
4765            final String libName = libInfo.getName();
4766            if (libInfo.isStatic()) {
4767                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4768                if (libIdx < 0) {
4769                    continue;
4770                }
4771                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4772                    continue;
4773                }
4774                if (versionedPackages == null) {
4775                    versionedPackages = new ArrayList<>();
4776                }
4777                // If the dependent is a static shared lib, use the public package name
4778                String dependentPackageName = ps.name;
4779                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4780                    dependentPackageName = ps.pkg.manifestPackageName;
4781                }
4782                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4783            } else if (ps.pkg != null) {
4784                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4785                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4786                    if (versionedPackages == null) {
4787                        versionedPackages = new ArrayList<>();
4788                    }
4789                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4790                }
4791            }
4792        }
4793
4794        return versionedPackages;
4795    }
4796
4797    @Override
4798    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4799        if (!sUserManager.exists(userId)) return null;
4800        final int callingUid = Binder.getCallingUid();
4801        flags = updateFlagsForComponent(flags, userId, component);
4802        enforceCrossUserPermission(callingUid, userId,
4803                false /* requireFullPermission */, false /* checkShell */, "get service info");
4804        synchronized (mPackages) {
4805            PackageParser.Service s = mServices.mServices.get(component);
4806            if (DEBUG_PACKAGE_INFO) Log.v(
4807                TAG, "getServiceInfo " + component + ": " + s);
4808            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4809                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4810                if (ps == null) return null;
4811                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4812                    return null;
4813                }
4814                return PackageParser.generateServiceInfo(
4815                        s, flags, ps.readUserState(userId), userId);
4816            }
4817        }
4818        return null;
4819    }
4820
4821    @Override
4822    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4823        if (!sUserManager.exists(userId)) return null;
4824        final int callingUid = Binder.getCallingUid();
4825        flags = updateFlagsForComponent(flags, userId, component);
4826        enforceCrossUserPermission(callingUid, userId,
4827                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4828        synchronized (mPackages) {
4829            PackageParser.Provider p = mProviders.mProviders.get(component);
4830            if (DEBUG_PACKAGE_INFO) Log.v(
4831                TAG, "getProviderInfo " + component + ": " + p);
4832            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4833                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4834                if (ps == null) return null;
4835                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4836                    return null;
4837                }
4838                return PackageParser.generateProviderInfo(
4839                        p, flags, ps.readUserState(userId), userId);
4840            }
4841        }
4842        return null;
4843    }
4844
4845    @Override
4846    public String[] getSystemSharedLibraryNames() {
4847        // allow instant applications
4848        synchronized (mPackages) {
4849            Set<String> libs = null;
4850            final int libCount = mSharedLibraries.size();
4851            for (int i = 0; i < libCount; i++) {
4852                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4853                if (versionedLib == null) {
4854                    continue;
4855                }
4856                final int versionCount = versionedLib.size();
4857                for (int j = 0; j < versionCount; j++) {
4858                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4859                    if (!libEntry.info.isStatic()) {
4860                        if (libs == null) {
4861                            libs = new ArraySet<>();
4862                        }
4863                        libs.add(libEntry.info.getName());
4864                        break;
4865                    }
4866                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4867                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4868                            UserHandle.getUserId(Binder.getCallingUid()),
4869                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4870                        if (libs == null) {
4871                            libs = new ArraySet<>();
4872                        }
4873                        libs.add(libEntry.info.getName());
4874                        break;
4875                    }
4876                }
4877            }
4878
4879            if (libs != null) {
4880                String[] libsArray = new String[libs.size()];
4881                libs.toArray(libsArray);
4882                return libsArray;
4883            }
4884
4885            return null;
4886        }
4887    }
4888
4889    @Override
4890    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4891        // allow instant applications
4892        synchronized (mPackages) {
4893            return mServicesSystemSharedLibraryPackageName;
4894        }
4895    }
4896
4897    @Override
4898    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4899        // allow instant applications
4900        synchronized (mPackages) {
4901            return mSharedSystemSharedLibraryPackageName;
4902        }
4903    }
4904
4905    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4906        for (int i = userList.length - 1; i >= 0; --i) {
4907            final int userId = userList[i];
4908            // don't add instant app to the list of updates
4909            if (pkgSetting.getInstantApp(userId)) {
4910                continue;
4911            }
4912            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4913            if (changedPackages == null) {
4914                changedPackages = new SparseArray<>();
4915                mChangedPackages.put(userId, changedPackages);
4916            }
4917            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4918            if (sequenceNumbers == null) {
4919                sequenceNumbers = new HashMap<>();
4920                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4921            }
4922            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4923            if (sequenceNumber != null) {
4924                changedPackages.remove(sequenceNumber);
4925            }
4926            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4927            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4928        }
4929        mChangedPackagesSequenceNumber++;
4930    }
4931
4932    @Override
4933    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4934        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4935            return null;
4936        }
4937        synchronized (mPackages) {
4938            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4939                return null;
4940            }
4941            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4942            if (changedPackages == null) {
4943                return null;
4944            }
4945            final List<String> packageNames =
4946                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4947            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4948                final String packageName = changedPackages.get(i);
4949                if (packageName != null) {
4950                    packageNames.add(packageName);
4951                }
4952            }
4953            return packageNames.isEmpty()
4954                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4955        }
4956    }
4957
4958    @Override
4959    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4960        // allow instant applications
4961        ArrayList<FeatureInfo> res;
4962        synchronized (mAvailableFeatures) {
4963            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4964            res.addAll(mAvailableFeatures.values());
4965        }
4966        final FeatureInfo fi = new FeatureInfo();
4967        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4968                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4969        res.add(fi);
4970
4971        return new ParceledListSlice<>(res);
4972    }
4973
4974    @Override
4975    public boolean hasSystemFeature(String name, int version) {
4976        // allow instant applications
4977        synchronized (mAvailableFeatures) {
4978            final FeatureInfo feat = mAvailableFeatures.get(name);
4979            if (feat == null) {
4980                return false;
4981            } else {
4982                return feat.version >= version;
4983            }
4984        }
4985    }
4986
4987    @Override
4988    public int checkPermission(String permName, String pkgName, int userId) {
4989        if (!sUserManager.exists(userId)) {
4990            return PackageManager.PERMISSION_DENIED;
4991        }
4992        final int callingUid = Binder.getCallingUid();
4993
4994        synchronized (mPackages) {
4995            final PackageParser.Package p = mPackages.get(pkgName);
4996            if (p != null && p.mExtras != null) {
4997                final PackageSetting ps = (PackageSetting) p.mExtras;
4998                if (filterAppAccessLPr(ps, callingUid, userId)) {
4999                    return PackageManager.PERMISSION_DENIED;
5000                }
5001                final boolean instantApp = ps.getInstantApp(userId);
5002                final PermissionsState permissionsState = ps.getPermissionsState();
5003                if (permissionsState.hasPermission(permName, userId)) {
5004                    if (instantApp) {
5005                        BasePermission bp = mSettings.mPermissions.get(permName);
5006                        if (bp != null && bp.isInstant()) {
5007                            return PackageManager.PERMISSION_GRANTED;
5008                        }
5009                    } else {
5010                        return PackageManager.PERMISSION_GRANTED;
5011                    }
5012                }
5013                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5014                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5015                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5016                    return PackageManager.PERMISSION_GRANTED;
5017                }
5018            }
5019        }
5020
5021        return PackageManager.PERMISSION_DENIED;
5022    }
5023
5024    @Override
5025    public int checkUidPermission(String permName, int uid) {
5026        final int callingUid = Binder.getCallingUid();
5027        final int callingUserId = UserHandle.getUserId(callingUid);
5028        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5029        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5030        final int userId = UserHandle.getUserId(uid);
5031        if (!sUserManager.exists(userId)) {
5032            return PackageManager.PERMISSION_DENIED;
5033        }
5034
5035        synchronized (mPackages) {
5036            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5037            if (obj != null) {
5038                if (obj instanceof SharedUserSetting) {
5039                    if (isCallerInstantApp) {
5040                        return PackageManager.PERMISSION_DENIED;
5041                    }
5042                } else if (obj instanceof PackageSetting) {
5043                    final PackageSetting ps = (PackageSetting) obj;
5044                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5045                        return PackageManager.PERMISSION_DENIED;
5046                    }
5047                }
5048                final SettingBase settingBase = (SettingBase) obj;
5049                final PermissionsState permissionsState = settingBase.getPermissionsState();
5050                if (permissionsState.hasPermission(permName, userId)) {
5051                    if (isUidInstantApp) {
5052                        BasePermission bp = mSettings.mPermissions.get(permName);
5053                        if (bp != null && bp.isInstant()) {
5054                            return PackageManager.PERMISSION_GRANTED;
5055                        }
5056                    } else {
5057                        return PackageManager.PERMISSION_GRANTED;
5058                    }
5059                }
5060                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5061                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5062                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5063                    return PackageManager.PERMISSION_GRANTED;
5064                }
5065            } else {
5066                ArraySet<String> perms = mSystemPermissions.get(uid);
5067                if (perms != null) {
5068                    if (perms.contains(permName)) {
5069                        return PackageManager.PERMISSION_GRANTED;
5070                    }
5071                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5072                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5073                        return PackageManager.PERMISSION_GRANTED;
5074                    }
5075                }
5076            }
5077        }
5078
5079        return PackageManager.PERMISSION_DENIED;
5080    }
5081
5082    @Override
5083    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5084        if (UserHandle.getCallingUserId() != userId) {
5085            mContext.enforceCallingPermission(
5086                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5087                    "isPermissionRevokedByPolicy for user " + userId);
5088        }
5089
5090        if (checkPermission(permission, packageName, userId)
5091                == PackageManager.PERMISSION_GRANTED) {
5092            return false;
5093        }
5094
5095        final int callingUid = Binder.getCallingUid();
5096        if (getInstantAppPackageName(callingUid) != null) {
5097            if (!isCallerSameApp(packageName, callingUid)) {
5098                return false;
5099            }
5100        } else {
5101            if (isInstantApp(packageName, userId)) {
5102                return false;
5103            }
5104        }
5105
5106        final long identity = Binder.clearCallingIdentity();
5107        try {
5108            final int flags = getPermissionFlags(permission, packageName, userId);
5109            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5110        } finally {
5111            Binder.restoreCallingIdentity(identity);
5112        }
5113    }
5114
5115    @Override
5116    public String getPermissionControllerPackageName() {
5117        synchronized (mPackages) {
5118            return mRequiredInstallerPackage;
5119        }
5120    }
5121
5122    /**
5123     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5124     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5125     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5126     * @param message the message to log on security exception
5127     */
5128    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5129            boolean checkShell, String message) {
5130        if (userId < 0) {
5131            throw new IllegalArgumentException("Invalid userId " + userId);
5132        }
5133        if (checkShell) {
5134            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5135        }
5136        if (userId == UserHandle.getUserId(callingUid)) return;
5137        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5138            if (requireFullPermission) {
5139                mContext.enforceCallingOrSelfPermission(
5140                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5141            } else {
5142                try {
5143                    mContext.enforceCallingOrSelfPermission(
5144                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5145                } catch (SecurityException se) {
5146                    mContext.enforceCallingOrSelfPermission(
5147                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5148                }
5149            }
5150        }
5151    }
5152
5153    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5154        if (callingUid == Process.SHELL_UID) {
5155            if (userHandle >= 0
5156                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5157                throw new SecurityException("Shell does not have permission to access user "
5158                        + userHandle);
5159            } else if (userHandle < 0) {
5160                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5161                        + Debug.getCallers(3));
5162            }
5163        }
5164    }
5165
5166    private BasePermission findPermissionTreeLP(String permName) {
5167        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5168            if (permName.startsWith(bp.name) &&
5169                    permName.length() > bp.name.length() &&
5170                    permName.charAt(bp.name.length()) == '.') {
5171                return bp;
5172            }
5173        }
5174        return null;
5175    }
5176
5177    private BasePermission checkPermissionTreeLP(String permName) {
5178        if (permName != null) {
5179            BasePermission bp = findPermissionTreeLP(permName);
5180            if (bp != null) {
5181                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5182                    return bp;
5183                }
5184                throw new SecurityException("Calling uid "
5185                        + Binder.getCallingUid()
5186                        + " is not allowed to add to permission tree "
5187                        + bp.name + " owned by uid " + bp.uid);
5188            }
5189        }
5190        throw new SecurityException("No permission tree found for " + permName);
5191    }
5192
5193    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5194        if (s1 == null) {
5195            return s2 == null;
5196        }
5197        if (s2 == null) {
5198            return false;
5199        }
5200        if (s1.getClass() != s2.getClass()) {
5201            return false;
5202        }
5203        return s1.equals(s2);
5204    }
5205
5206    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5207        if (pi1.icon != pi2.icon) return false;
5208        if (pi1.logo != pi2.logo) return false;
5209        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5210        if (!compareStrings(pi1.name, pi2.name)) return false;
5211        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5212        // We'll take care of setting this one.
5213        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5214        // These are not currently stored in settings.
5215        //if (!compareStrings(pi1.group, pi2.group)) return false;
5216        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5217        //if (pi1.labelRes != pi2.labelRes) return false;
5218        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5219        return true;
5220    }
5221
5222    int permissionInfoFootprint(PermissionInfo info) {
5223        int size = info.name.length();
5224        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5225        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5226        return size;
5227    }
5228
5229    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5230        int size = 0;
5231        for (BasePermission perm : mSettings.mPermissions.values()) {
5232            if (perm.uid == tree.uid) {
5233                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5234            }
5235        }
5236        return size;
5237    }
5238
5239    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5240        // We calculate the max size of permissions defined by this uid and throw
5241        // if that plus the size of 'info' would exceed our stated maximum.
5242        if (tree.uid != Process.SYSTEM_UID) {
5243            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5244            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5245                throw new SecurityException("Permission tree size cap exceeded");
5246            }
5247        }
5248    }
5249
5250    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5251        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5252            throw new SecurityException("Instant apps can't add permissions");
5253        }
5254        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5255            throw new SecurityException("Label must be specified in permission");
5256        }
5257        BasePermission tree = checkPermissionTreeLP(info.name);
5258        BasePermission bp = mSettings.mPermissions.get(info.name);
5259        boolean added = bp == null;
5260        boolean changed = true;
5261        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5262        if (added) {
5263            enforcePermissionCapLocked(info, tree);
5264            bp = new BasePermission(info.name, tree.sourcePackage,
5265                    BasePermission.TYPE_DYNAMIC);
5266        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5267            throw new SecurityException(
5268                    "Not allowed to modify non-dynamic permission "
5269                    + info.name);
5270        } else {
5271            if (bp.protectionLevel == fixedLevel
5272                    && bp.perm.owner.equals(tree.perm.owner)
5273                    && bp.uid == tree.uid
5274                    && comparePermissionInfos(bp.perm.info, info)) {
5275                changed = false;
5276            }
5277        }
5278        bp.protectionLevel = fixedLevel;
5279        info = new PermissionInfo(info);
5280        info.protectionLevel = fixedLevel;
5281        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5282        bp.perm.info.packageName = tree.perm.info.packageName;
5283        bp.uid = tree.uid;
5284        if (added) {
5285            mSettings.mPermissions.put(info.name, bp);
5286        }
5287        if (changed) {
5288            if (!async) {
5289                mSettings.writeLPr();
5290            } else {
5291                scheduleWriteSettingsLocked();
5292            }
5293        }
5294        return added;
5295    }
5296
5297    @Override
5298    public boolean addPermission(PermissionInfo info) {
5299        synchronized (mPackages) {
5300            return addPermissionLocked(info, false);
5301        }
5302    }
5303
5304    @Override
5305    public boolean addPermissionAsync(PermissionInfo info) {
5306        synchronized (mPackages) {
5307            return addPermissionLocked(info, true);
5308        }
5309    }
5310
5311    @Override
5312    public void removePermission(String name) {
5313        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5314            throw new SecurityException("Instant applications don't have access to this method");
5315        }
5316        synchronized (mPackages) {
5317            checkPermissionTreeLP(name);
5318            BasePermission bp = mSettings.mPermissions.get(name);
5319            if (bp != null) {
5320                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5321                    throw new SecurityException(
5322                            "Not allowed to modify non-dynamic permission "
5323                            + name);
5324                }
5325                mSettings.mPermissions.remove(name);
5326                mSettings.writeLPr();
5327            }
5328        }
5329    }
5330
5331    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5332            PackageParser.Package pkg, BasePermission bp) {
5333        int index = pkg.requestedPermissions.indexOf(bp.name);
5334        if (index == -1) {
5335            throw new SecurityException("Package " + pkg.packageName
5336                    + " has not requested permission " + bp.name);
5337        }
5338        if (!bp.isRuntime() && !bp.isDevelopment()) {
5339            throw new SecurityException("Permission " + bp.name
5340                    + " is not a changeable permission type");
5341        }
5342    }
5343
5344    @Override
5345    public void grantRuntimePermission(String packageName, String name, final int userId) {
5346        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5347    }
5348
5349    private void grantRuntimePermission(String packageName, String name, final int userId,
5350            boolean overridePolicy) {
5351        if (!sUserManager.exists(userId)) {
5352            Log.e(TAG, "No such user:" + userId);
5353            return;
5354        }
5355        final int callingUid = Binder.getCallingUid();
5356
5357        mContext.enforceCallingOrSelfPermission(
5358                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5359                "grantRuntimePermission");
5360
5361        enforceCrossUserPermission(callingUid, userId,
5362                true /* requireFullPermission */, true /* checkShell */,
5363                "grantRuntimePermission");
5364
5365        final int uid;
5366        final PackageSetting ps;
5367
5368        synchronized (mPackages) {
5369            final PackageParser.Package pkg = mPackages.get(packageName);
5370            if (pkg == null) {
5371                throw new IllegalArgumentException("Unknown package: " + packageName);
5372            }
5373            final BasePermission bp = mSettings.mPermissions.get(name);
5374            if (bp == null) {
5375                throw new IllegalArgumentException("Unknown permission: " + name);
5376            }
5377            ps = (PackageSetting) pkg.mExtras;
5378            if (ps == null
5379                    || filterAppAccessLPr(ps, callingUid, userId)) {
5380                throw new IllegalArgumentException("Unknown package: " + packageName);
5381            }
5382
5383            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5384
5385            // If a permission review is required for legacy apps we represent
5386            // their permissions as always granted runtime ones since we need
5387            // to keep the review required permission flag per user while an
5388            // install permission's state is shared across all users.
5389            if (mPermissionReviewRequired
5390                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5391                    && bp.isRuntime()) {
5392                return;
5393            }
5394
5395            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5396
5397            final PermissionsState permissionsState = ps.getPermissionsState();
5398
5399            final int flags = permissionsState.getPermissionFlags(name, userId);
5400            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5401                throw new SecurityException("Cannot grant system fixed permission "
5402                        + name + " for package " + packageName);
5403            }
5404            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5405                throw new SecurityException("Cannot grant policy fixed permission "
5406                        + name + " for package " + packageName);
5407            }
5408
5409            if (bp.isDevelopment()) {
5410                // Development permissions must be handled specially, since they are not
5411                // normal runtime permissions.  For now they apply to all users.
5412                if (permissionsState.grantInstallPermission(bp) !=
5413                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5414                    scheduleWriteSettingsLocked();
5415                }
5416                return;
5417            }
5418
5419            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5420                throw new SecurityException("Cannot grant non-ephemeral permission"
5421                        + name + " for package " + packageName);
5422            }
5423
5424            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5425                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5426                return;
5427            }
5428
5429            final int result = permissionsState.grantRuntimePermission(bp, userId);
5430            switch (result) {
5431                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5432                    return;
5433                }
5434
5435                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5436                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5437                    mHandler.post(new Runnable() {
5438                        @Override
5439                        public void run() {
5440                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5441                        }
5442                    });
5443                }
5444                break;
5445            }
5446
5447            if (bp.isRuntime()) {
5448                logPermissionGranted(mContext, name, packageName);
5449            }
5450
5451            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5452
5453            // Not critical if that is lost - app has to request again.
5454            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5455        }
5456
5457        // Only need to do this if user is initialized. Otherwise it's a new user
5458        // and there are no processes running as the user yet and there's no need
5459        // to make an expensive call to remount processes for the changed permissions.
5460        if (READ_EXTERNAL_STORAGE.equals(name)
5461                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5462            final long token = Binder.clearCallingIdentity();
5463            try {
5464                if (sUserManager.isInitialized(userId)) {
5465                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5466                            StorageManagerInternal.class);
5467                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5468                }
5469            } finally {
5470                Binder.restoreCallingIdentity(token);
5471            }
5472        }
5473    }
5474
5475    @Override
5476    public void revokeRuntimePermission(String packageName, String name, int userId) {
5477        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5478    }
5479
5480    private void revokeRuntimePermission(String packageName, String name, int userId,
5481            boolean overridePolicy) {
5482        if (!sUserManager.exists(userId)) {
5483            Log.e(TAG, "No such user:" + userId);
5484            return;
5485        }
5486
5487        mContext.enforceCallingOrSelfPermission(
5488                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5489                "revokeRuntimePermission");
5490
5491        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5492                true /* requireFullPermission */, true /* checkShell */,
5493                "revokeRuntimePermission");
5494
5495        final int appId;
5496
5497        synchronized (mPackages) {
5498            final PackageParser.Package pkg = mPackages.get(packageName);
5499            if (pkg == null) {
5500                throw new IllegalArgumentException("Unknown package: " + packageName);
5501            }
5502            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5503            if (ps == null
5504                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5505                throw new IllegalArgumentException("Unknown package: " + packageName);
5506            }
5507            final BasePermission bp = mSettings.mPermissions.get(name);
5508            if (bp == null) {
5509                throw new IllegalArgumentException("Unknown permission: " + name);
5510            }
5511
5512            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5513
5514            // If a permission review is required for legacy apps we represent
5515            // their permissions as always granted runtime ones since we need
5516            // to keep the review required permission flag per user while an
5517            // install permission's state is shared across all users.
5518            if (mPermissionReviewRequired
5519                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5520                    && bp.isRuntime()) {
5521                return;
5522            }
5523
5524            final PermissionsState permissionsState = ps.getPermissionsState();
5525
5526            final int flags = permissionsState.getPermissionFlags(name, userId);
5527            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5528                throw new SecurityException("Cannot revoke system fixed permission "
5529                        + name + " for package " + packageName);
5530            }
5531            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5532                throw new SecurityException("Cannot revoke policy fixed permission "
5533                        + name + " for package " + packageName);
5534            }
5535
5536            if (bp.isDevelopment()) {
5537                // Development permissions must be handled specially, since they are not
5538                // normal runtime permissions.  For now they apply to all users.
5539                if (permissionsState.revokeInstallPermission(bp) !=
5540                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5541                    scheduleWriteSettingsLocked();
5542                }
5543                return;
5544            }
5545
5546            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5547                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5548                return;
5549            }
5550
5551            if (bp.isRuntime()) {
5552                logPermissionRevoked(mContext, name, packageName);
5553            }
5554
5555            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5556
5557            // Critical, after this call app should never have the permission.
5558            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5559
5560            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5561        }
5562
5563        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5564    }
5565
5566    /**
5567     * Get the first event id for the permission.
5568     *
5569     * <p>There are four events for each permission: <ul>
5570     *     <li>Request permission: first id + 0</li>
5571     *     <li>Grant permission: first id + 1</li>
5572     *     <li>Request for permission denied: first id + 2</li>
5573     *     <li>Revoke permission: first id + 3</li>
5574     * </ul></p>
5575     *
5576     * @param name name of the permission
5577     *
5578     * @return The first event id for the permission
5579     */
5580    private static int getBaseEventId(@NonNull String name) {
5581        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5582
5583        if (eventIdIndex == -1) {
5584            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5585                    || "user".equals(Build.TYPE)) {
5586                Log.i(TAG, "Unknown permission " + name);
5587
5588                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5589            } else {
5590                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5591                //
5592                // Also update
5593                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5594                // - metrics_constants.proto
5595                throw new IllegalStateException("Unknown permission " + name);
5596            }
5597        }
5598
5599        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5600    }
5601
5602    /**
5603     * Log that a permission was revoked.
5604     *
5605     * @param context Context of the caller
5606     * @param name name of the permission
5607     * @param packageName package permission if for
5608     */
5609    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5610            @NonNull String packageName) {
5611        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5612    }
5613
5614    /**
5615     * Log that a permission request was granted.
5616     *
5617     * @param context Context of the caller
5618     * @param name name of the permission
5619     * @param packageName package permission if for
5620     */
5621    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5622            @NonNull String packageName) {
5623        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5624    }
5625
5626    @Override
5627    public void resetRuntimePermissions() {
5628        mContext.enforceCallingOrSelfPermission(
5629                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5630                "revokeRuntimePermission");
5631
5632        int callingUid = Binder.getCallingUid();
5633        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5634            mContext.enforceCallingOrSelfPermission(
5635                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5636                    "resetRuntimePermissions");
5637        }
5638
5639        synchronized (mPackages) {
5640            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5641            for (int userId : UserManagerService.getInstance().getUserIds()) {
5642                final int packageCount = mPackages.size();
5643                for (int i = 0; i < packageCount; i++) {
5644                    PackageParser.Package pkg = mPackages.valueAt(i);
5645                    if (!(pkg.mExtras instanceof PackageSetting)) {
5646                        continue;
5647                    }
5648                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5649                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5650                }
5651            }
5652        }
5653    }
5654
5655    @Override
5656    public int getPermissionFlags(String name, String packageName, int userId) {
5657        if (!sUserManager.exists(userId)) {
5658            return 0;
5659        }
5660
5661        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5662
5663        final int callingUid = Binder.getCallingUid();
5664        enforceCrossUserPermission(callingUid, userId,
5665                true /* requireFullPermission */, false /* checkShell */,
5666                "getPermissionFlags");
5667
5668        synchronized (mPackages) {
5669            final PackageParser.Package pkg = mPackages.get(packageName);
5670            if (pkg == null) {
5671                return 0;
5672            }
5673            final BasePermission bp = mSettings.mPermissions.get(name);
5674            if (bp == null) {
5675                return 0;
5676            }
5677            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5678            if (ps == null
5679                    || filterAppAccessLPr(ps, callingUid, userId)) {
5680                return 0;
5681            }
5682            PermissionsState permissionsState = ps.getPermissionsState();
5683            return permissionsState.getPermissionFlags(name, userId);
5684        }
5685    }
5686
5687    @Override
5688    public void updatePermissionFlags(String name, String packageName, int flagMask,
5689            int flagValues, int userId) {
5690        if (!sUserManager.exists(userId)) {
5691            return;
5692        }
5693
5694        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5695
5696        final int callingUid = Binder.getCallingUid();
5697        enforceCrossUserPermission(callingUid, userId,
5698                true /* requireFullPermission */, true /* checkShell */,
5699                "updatePermissionFlags");
5700
5701        // Only the system can change these flags and nothing else.
5702        if (getCallingUid() != Process.SYSTEM_UID) {
5703            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5704            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5705            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5706            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5707            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5708        }
5709
5710        synchronized (mPackages) {
5711            final PackageParser.Package pkg = mPackages.get(packageName);
5712            if (pkg == null) {
5713                throw new IllegalArgumentException("Unknown package: " + packageName);
5714            }
5715            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5716            if (ps == null
5717                    || filterAppAccessLPr(ps, callingUid, userId)) {
5718                throw new IllegalArgumentException("Unknown package: " + packageName);
5719            }
5720
5721            final BasePermission bp = mSettings.mPermissions.get(name);
5722            if (bp == null) {
5723                throw new IllegalArgumentException("Unknown permission: " + name);
5724            }
5725
5726            PermissionsState permissionsState = ps.getPermissionsState();
5727
5728            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5729
5730            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5731                // Install and runtime permissions are stored in different places,
5732                // so figure out what permission changed and persist the change.
5733                if (permissionsState.getInstallPermissionState(name) != null) {
5734                    scheduleWriteSettingsLocked();
5735                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5736                        || hadState) {
5737                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5738                }
5739            }
5740        }
5741    }
5742
5743    /**
5744     * Update the permission flags for all packages and runtime permissions of a user in order
5745     * to allow device or profile owner to remove POLICY_FIXED.
5746     */
5747    @Override
5748    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5749        if (!sUserManager.exists(userId)) {
5750            return;
5751        }
5752
5753        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5754
5755        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5756                true /* requireFullPermission */, true /* checkShell */,
5757                "updatePermissionFlagsForAllApps");
5758
5759        // Only the system can change system fixed flags.
5760        if (getCallingUid() != Process.SYSTEM_UID) {
5761            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5762            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5763        }
5764
5765        synchronized (mPackages) {
5766            boolean changed = false;
5767            final int packageCount = mPackages.size();
5768            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5769                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5770                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5771                if (ps == null) {
5772                    continue;
5773                }
5774                PermissionsState permissionsState = ps.getPermissionsState();
5775                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5776                        userId, flagMask, flagValues);
5777            }
5778            if (changed) {
5779                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5780            }
5781        }
5782    }
5783
5784    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5785        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5786                != PackageManager.PERMISSION_GRANTED
5787            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5788                != PackageManager.PERMISSION_GRANTED) {
5789            throw new SecurityException(message + " requires "
5790                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5791                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5792        }
5793    }
5794
5795    @Override
5796    public boolean shouldShowRequestPermissionRationale(String permissionName,
5797            String packageName, int userId) {
5798        if (UserHandle.getCallingUserId() != userId) {
5799            mContext.enforceCallingPermission(
5800                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5801                    "canShowRequestPermissionRationale for user " + userId);
5802        }
5803
5804        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5805        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5806            return false;
5807        }
5808
5809        if (checkPermission(permissionName, packageName, userId)
5810                == PackageManager.PERMISSION_GRANTED) {
5811            return false;
5812        }
5813
5814        final int flags;
5815
5816        final long identity = Binder.clearCallingIdentity();
5817        try {
5818            flags = getPermissionFlags(permissionName,
5819                    packageName, userId);
5820        } finally {
5821            Binder.restoreCallingIdentity(identity);
5822        }
5823
5824        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5825                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5826                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5827
5828        if ((flags & fixedFlags) != 0) {
5829            return false;
5830        }
5831
5832        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5833    }
5834
5835    @Override
5836    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5837        mContext.enforceCallingOrSelfPermission(
5838                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5839                "addOnPermissionsChangeListener");
5840
5841        synchronized (mPackages) {
5842            mOnPermissionChangeListeners.addListenerLocked(listener);
5843        }
5844    }
5845
5846    @Override
5847    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5848        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5849            throw new SecurityException("Instant applications don't have access to this method");
5850        }
5851        synchronized (mPackages) {
5852            mOnPermissionChangeListeners.removeListenerLocked(listener);
5853        }
5854    }
5855
5856    @Override
5857    public boolean isProtectedBroadcast(String actionName) {
5858        // allow instant applications
5859        synchronized (mPackages) {
5860            if (mProtectedBroadcasts.contains(actionName)) {
5861                return true;
5862            } else if (actionName != null) {
5863                // TODO: remove these terrible hacks
5864                if (actionName.startsWith("android.net.netmon.lingerExpired")
5865                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5866                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5867                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5868                    return true;
5869                }
5870            }
5871        }
5872        return false;
5873    }
5874
5875    @Override
5876    public int checkSignatures(String pkg1, String pkg2) {
5877        synchronized (mPackages) {
5878            final PackageParser.Package p1 = mPackages.get(pkg1);
5879            final PackageParser.Package p2 = mPackages.get(pkg2);
5880            if (p1 == null || p1.mExtras == null
5881                    || p2 == null || p2.mExtras == null) {
5882                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5883            }
5884            final int callingUid = Binder.getCallingUid();
5885            final int callingUserId = UserHandle.getUserId(callingUid);
5886            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5887            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5888            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5889                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5890                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891            }
5892            return compareSignatures(p1.mSignatures, p2.mSignatures);
5893        }
5894    }
5895
5896    @Override
5897    public int checkUidSignatures(int uid1, int uid2) {
5898        final int callingUid = Binder.getCallingUid();
5899        final int callingUserId = UserHandle.getUserId(callingUid);
5900        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5901        // Map to base uids.
5902        uid1 = UserHandle.getAppId(uid1);
5903        uid2 = UserHandle.getAppId(uid2);
5904        // reader
5905        synchronized (mPackages) {
5906            Signature[] s1;
5907            Signature[] s2;
5908            Object obj = mSettings.getUserIdLPr(uid1);
5909            if (obj != null) {
5910                if (obj instanceof SharedUserSetting) {
5911                    if (isCallerInstantApp) {
5912                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5913                    }
5914                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5915                } else if (obj instanceof PackageSetting) {
5916                    final PackageSetting ps = (PackageSetting) obj;
5917                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5918                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5919                    }
5920                    s1 = ps.signatures.mSignatures;
5921                } else {
5922                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5923                }
5924            } else {
5925                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5926            }
5927            obj = mSettings.getUserIdLPr(uid2);
5928            if (obj != null) {
5929                if (obj instanceof SharedUserSetting) {
5930                    if (isCallerInstantApp) {
5931                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5932                    }
5933                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5934                } else if (obj instanceof PackageSetting) {
5935                    final PackageSetting ps = (PackageSetting) obj;
5936                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5937                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5938                    }
5939                    s2 = ps.signatures.mSignatures;
5940                } else {
5941                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5942                }
5943            } else {
5944                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5945            }
5946            return compareSignatures(s1, s2);
5947        }
5948    }
5949
5950    /**
5951     * This method should typically only be used when granting or revoking
5952     * permissions, since the app may immediately restart after this call.
5953     * <p>
5954     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5955     * guard your work against the app being relaunched.
5956     */
5957    private void killUid(int appId, int userId, String reason) {
5958        final long identity = Binder.clearCallingIdentity();
5959        try {
5960            IActivityManager am = ActivityManager.getService();
5961            if (am != null) {
5962                try {
5963                    am.killUid(appId, userId, reason);
5964                } catch (RemoteException e) {
5965                    /* ignore - same process */
5966                }
5967            }
5968        } finally {
5969            Binder.restoreCallingIdentity(identity);
5970        }
5971    }
5972
5973    /**
5974     * Compares two sets of signatures. Returns:
5975     * <br />
5976     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5977     * <br />
5978     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5979     * <br />
5980     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5981     * <br />
5982     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5983     * <br />
5984     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5985     */
5986    static int compareSignatures(Signature[] s1, Signature[] s2) {
5987        if (s1 == null) {
5988            return s2 == null
5989                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5990                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5991        }
5992
5993        if (s2 == null) {
5994            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5995        }
5996
5997        if (s1.length != s2.length) {
5998            return PackageManager.SIGNATURE_NO_MATCH;
5999        }
6000
6001        // Since both signature sets are of size 1, we can compare without HashSets.
6002        if (s1.length == 1) {
6003            return s1[0].equals(s2[0]) ?
6004                    PackageManager.SIGNATURE_MATCH :
6005                    PackageManager.SIGNATURE_NO_MATCH;
6006        }
6007
6008        ArraySet<Signature> set1 = new ArraySet<Signature>();
6009        for (Signature sig : s1) {
6010            set1.add(sig);
6011        }
6012        ArraySet<Signature> set2 = new ArraySet<Signature>();
6013        for (Signature sig : s2) {
6014            set2.add(sig);
6015        }
6016        // Make sure s2 contains all signatures in s1.
6017        if (set1.equals(set2)) {
6018            return PackageManager.SIGNATURE_MATCH;
6019        }
6020        return PackageManager.SIGNATURE_NO_MATCH;
6021    }
6022
6023    /**
6024     * If the database version for this type of package (internal storage or
6025     * external storage) is less than the version where package signatures
6026     * were updated, return true.
6027     */
6028    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6029        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6030        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6031    }
6032
6033    /**
6034     * Used for backward compatibility to make sure any packages with
6035     * certificate chains get upgraded to the new style. {@code existingSigs}
6036     * will be in the old format (since they were stored on disk from before the
6037     * system upgrade) and {@code scannedSigs} will be in the newer format.
6038     */
6039    private int compareSignaturesCompat(PackageSignatures existingSigs,
6040            PackageParser.Package scannedPkg) {
6041        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6042            return PackageManager.SIGNATURE_NO_MATCH;
6043        }
6044
6045        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6046        for (Signature sig : existingSigs.mSignatures) {
6047            existingSet.add(sig);
6048        }
6049        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6050        for (Signature sig : scannedPkg.mSignatures) {
6051            try {
6052                Signature[] chainSignatures = sig.getChainSignatures();
6053                for (Signature chainSig : chainSignatures) {
6054                    scannedCompatSet.add(chainSig);
6055                }
6056            } catch (CertificateEncodingException e) {
6057                scannedCompatSet.add(sig);
6058            }
6059        }
6060        /*
6061         * Make sure the expanded scanned set contains all signatures in the
6062         * existing one.
6063         */
6064        if (scannedCompatSet.equals(existingSet)) {
6065            // Migrate the old signatures to the new scheme.
6066            existingSigs.assignSignatures(scannedPkg.mSignatures);
6067            // The new KeySets will be re-added later in the scanning process.
6068            synchronized (mPackages) {
6069                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6070            }
6071            return PackageManager.SIGNATURE_MATCH;
6072        }
6073        return PackageManager.SIGNATURE_NO_MATCH;
6074    }
6075
6076    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6077        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6078        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6079    }
6080
6081    private int compareSignaturesRecover(PackageSignatures existingSigs,
6082            PackageParser.Package scannedPkg) {
6083        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6084            return PackageManager.SIGNATURE_NO_MATCH;
6085        }
6086
6087        String msg = null;
6088        try {
6089            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6090                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6091                        + scannedPkg.packageName);
6092                return PackageManager.SIGNATURE_MATCH;
6093            }
6094        } catch (CertificateException e) {
6095            msg = e.getMessage();
6096        }
6097
6098        logCriticalInfo(Log.INFO,
6099                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6100        return PackageManager.SIGNATURE_NO_MATCH;
6101    }
6102
6103    @Override
6104    public List<String> getAllPackages() {
6105        final int callingUid = Binder.getCallingUid();
6106        final int callingUserId = UserHandle.getUserId(callingUid);
6107        synchronized (mPackages) {
6108            if (canViewInstantApps(callingUid, callingUserId)) {
6109                return new ArrayList<String>(mPackages.keySet());
6110            }
6111            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6112            final List<String> result = new ArrayList<>();
6113            if (instantAppPkgName != null) {
6114                // caller is an instant application; filter unexposed applications
6115                for (PackageParser.Package pkg : mPackages.values()) {
6116                    if (!pkg.visibleToInstantApps) {
6117                        continue;
6118                    }
6119                    result.add(pkg.packageName);
6120                }
6121            } else {
6122                // caller is a normal application; filter instant applications
6123                for (PackageParser.Package pkg : mPackages.values()) {
6124                    final PackageSetting ps =
6125                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6126                    if (ps != null
6127                            && ps.getInstantApp(callingUserId)
6128                            && !mInstantAppRegistry.isInstantAccessGranted(
6129                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6130                        continue;
6131                    }
6132                    result.add(pkg.packageName);
6133                }
6134            }
6135            return result;
6136        }
6137    }
6138
6139    @Override
6140    public String[] getPackagesForUid(int uid) {
6141        final int callingUid = Binder.getCallingUid();
6142        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6143        final int userId = UserHandle.getUserId(uid);
6144        uid = UserHandle.getAppId(uid);
6145        // reader
6146        synchronized (mPackages) {
6147            Object obj = mSettings.getUserIdLPr(uid);
6148            if (obj instanceof SharedUserSetting) {
6149                if (isCallerInstantApp) {
6150                    return null;
6151                }
6152                final SharedUserSetting sus = (SharedUserSetting) obj;
6153                final int N = sus.packages.size();
6154                String[] res = new String[N];
6155                final Iterator<PackageSetting> it = sus.packages.iterator();
6156                int i = 0;
6157                while (it.hasNext()) {
6158                    PackageSetting ps = it.next();
6159                    if (ps.getInstalled(userId)) {
6160                        res[i++] = ps.name;
6161                    } else {
6162                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6163                    }
6164                }
6165                return res;
6166            } else if (obj instanceof PackageSetting) {
6167                final PackageSetting ps = (PackageSetting) obj;
6168                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6169                    return new String[]{ps.name};
6170                }
6171            }
6172        }
6173        return null;
6174    }
6175
6176    @Override
6177    public String getNameForUid(int uid) {
6178        final int callingUid = Binder.getCallingUid();
6179        if (getInstantAppPackageName(callingUid) != null) {
6180            return null;
6181        }
6182        synchronized (mPackages) {
6183            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6184            if (obj instanceof SharedUserSetting) {
6185                final SharedUserSetting sus = (SharedUserSetting) obj;
6186                return sus.name + ":" + sus.userId;
6187            } else if (obj instanceof PackageSetting) {
6188                final PackageSetting ps = (PackageSetting) obj;
6189                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6190                    return null;
6191                }
6192                return ps.name;
6193            }
6194        }
6195        return null;
6196    }
6197
6198    @Override
6199    public int getUidForSharedUser(String sharedUserName) {
6200        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6201            return -1;
6202        }
6203        if (sharedUserName == null) {
6204            return -1;
6205        }
6206        // reader
6207        synchronized (mPackages) {
6208            SharedUserSetting suid;
6209            try {
6210                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6211                if (suid != null) {
6212                    return suid.userId;
6213                }
6214            } catch (PackageManagerException ignore) {
6215                // can't happen, but, still need to catch it
6216            }
6217            return -1;
6218        }
6219    }
6220
6221    @Override
6222    public int getFlagsForUid(int uid) {
6223        final int callingUid = Binder.getCallingUid();
6224        if (getInstantAppPackageName(callingUid) != null) {
6225            return 0;
6226        }
6227        synchronized (mPackages) {
6228            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6229            if (obj instanceof SharedUserSetting) {
6230                final SharedUserSetting sus = (SharedUserSetting) obj;
6231                return sus.pkgFlags;
6232            } else if (obj instanceof PackageSetting) {
6233                final PackageSetting ps = (PackageSetting) obj;
6234                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6235                    return 0;
6236                }
6237                return ps.pkgFlags;
6238            }
6239        }
6240        return 0;
6241    }
6242
6243    @Override
6244    public int getPrivateFlagsForUid(int uid) {
6245        final int callingUid = Binder.getCallingUid();
6246        if (getInstantAppPackageName(callingUid) != null) {
6247            return 0;
6248        }
6249        synchronized (mPackages) {
6250            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6251            if (obj instanceof SharedUserSetting) {
6252                final SharedUserSetting sus = (SharedUserSetting) obj;
6253                return sus.pkgPrivateFlags;
6254            } else if (obj instanceof PackageSetting) {
6255                final PackageSetting ps = (PackageSetting) obj;
6256                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6257                    return 0;
6258                }
6259                return ps.pkgPrivateFlags;
6260            }
6261        }
6262        return 0;
6263    }
6264
6265    @Override
6266    public boolean isUidPrivileged(int uid) {
6267        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6268            return false;
6269        }
6270        uid = UserHandle.getAppId(uid);
6271        // reader
6272        synchronized (mPackages) {
6273            Object obj = mSettings.getUserIdLPr(uid);
6274            if (obj instanceof SharedUserSetting) {
6275                final SharedUserSetting sus = (SharedUserSetting) obj;
6276                final Iterator<PackageSetting> it = sus.packages.iterator();
6277                while (it.hasNext()) {
6278                    if (it.next().isPrivileged()) {
6279                        return true;
6280                    }
6281                }
6282            } else if (obj instanceof PackageSetting) {
6283                final PackageSetting ps = (PackageSetting) obj;
6284                return ps.isPrivileged();
6285            }
6286        }
6287        return false;
6288    }
6289
6290    @Override
6291    public String[] getAppOpPermissionPackages(String permissionName) {
6292        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6293            return null;
6294        }
6295        synchronized (mPackages) {
6296            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6297            if (pkgs == null) {
6298                return null;
6299            }
6300            return pkgs.toArray(new String[pkgs.size()]);
6301        }
6302    }
6303
6304    @Override
6305    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6306            int flags, int userId) {
6307        return resolveIntentInternal(
6308                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6309    }
6310
6311    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6312            int flags, int userId, boolean resolveForStart) {
6313        try {
6314            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6315
6316            if (!sUserManager.exists(userId)) return null;
6317            final int callingUid = Binder.getCallingUid();
6318            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6319            enforceCrossUserPermission(callingUid, userId,
6320                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6321
6322            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6323            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6324                    flags, callingUid, userId, resolveForStart);
6325            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6326
6327            final ResolveInfo bestChoice =
6328                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6329            return bestChoice;
6330        } finally {
6331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6332        }
6333    }
6334
6335    @Override
6336    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6337        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6338            throw new SecurityException(
6339                    "findPersistentPreferredActivity can only be run by the system");
6340        }
6341        if (!sUserManager.exists(userId)) {
6342            return null;
6343        }
6344        final int callingUid = Binder.getCallingUid();
6345        intent = updateIntentForResolve(intent);
6346        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6347        final int flags = updateFlagsForResolve(
6348                0, userId, intent, callingUid, false /*includeInstantApps*/);
6349        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6350                userId);
6351        synchronized (mPackages) {
6352            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6353                    userId);
6354        }
6355    }
6356
6357    @Override
6358    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6359            IntentFilter filter, int match, ComponentName activity) {
6360        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6361            return;
6362        }
6363        final int userId = UserHandle.getCallingUserId();
6364        if (DEBUG_PREFERRED) {
6365            Log.v(TAG, "setLastChosenActivity intent=" + intent
6366                + " resolvedType=" + resolvedType
6367                + " flags=" + flags
6368                + " filter=" + filter
6369                + " match=" + match
6370                + " activity=" + activity);
6371            filter.dump(new PrintStreamPrinter(System.out), "    ");
6372        }
6373        intent.setComponent(null);
6374        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6375                userId);
6376        // Find any earlier preferred or last chosen entries and nuke them
6377        findPreferredActivity(intent, resolvedType,
6378                flags, query, 0, false, true, false, userId);
6379        // Add the new activity as the last chosen for this filter
6380        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6381                "Setting last chosen");
6382    }
6383
6384    @Override
6385    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6386        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6387            return null;
6388        }
6389        final int userId = UserHandle.getCallingUserId();
6390        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6391        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6392                userId);
6393        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6394                false, false, false, userId);
6395    }
6396
6397    /**
6398     * Returns whether or not instant apps have been disabled remotely.
6399     */
6400    private boolean isEphemeralDisabled() {
6401        return mEphemeralAppsDisabled;
6402    }
6403
6404    private boolean isInstantAppAllowed(
6405            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6406            boolean skipPackageCheck) {
6407        if (mInstantAppResolverConnection == null) {
6408            return false;
6409        }
6410        if (mInstantAppInstallerActivity == null) {
6411            return false;
6412        }
6413        if (intent.getComponent() != null) {
6414            return false;
6415        }
6416        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6417            return false;
6418        }
6419        if (!skipPackageCheck && intent.getPackage() != null) {
6420            return false;
6421        }
6422        final boolean isWebUri = hasWebURI(intent);
6423        if (!isWebUri || intent.getData().getHost() == null) {
6424            return false;
6425        }
6426        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6427        // Or if there's already an ephemeral app installed that handles the action
6428        synchronized (mPackages) {
6429            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6430            for (int n = 0; n < count; n++) {
6431                final ResolveInfo info = resolvedActivities.get(n);
6432                final String packageName = info.activityInfo.packageName;
6433                final PackageSetting ps = mSettings.mPackages.get(packageName);
6434                if (ps != null) {
6435                    // only check domain verification status if the app is not a browser
6436                    if (!info.handleAllWebDataURI) {
6437                        // Try to get the status from User settings first
6438                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6439                        final int status = (int) (packedStatus >> 32);
6440                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6441                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6442                            if (DEBUG_EPHEMERAL) {
6443                                Slog.v(TAG, "DENY instant app;"
6444                                    + " pkg: " + packageName + ", status: " + status);
6445                            }
6446                            return false;
6447                        }
6448                    }
6449                    if (ps.getInstantApp(userId)) {
6450                        if (DEBUG_EPHEMERAL) {
6451                            Slog.v(TAG, "DENY instant app installed;"
6452                                    + " pkg: " + packageName);
6453                        }
6454                        return false;
6455                    }
6456                }
6457            }
6458        }
6459        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6460        return true;
6461    }
6462
6463    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6464            Intent origIntent, String resolvedType, String callingPackage,
6465            Bundle verificationBundle, int userId) {
6466        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6467                new InstantAppRequest(responseObj, origIntent, resolvedType,
6468                        callingPackage, userId, verificationBundle));
6469        mHandler.sendMessage(msg);
6470    }
6471
6472    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6473            int flags, List<ResolveInfo> query, int userId) {
6474        if (query != null) {
6475            final int N = query.size();
6476            if (N == 1) {
6477                return query.get(0);
6478            } else if (N > 1) {
6479                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6480                // If there is more than one activity with the same priority,
6481                // then let the user decide between them.
6482                ResolveInfo r0 = query.get(0);
6483                ResolveInfo r1 = query.get(1);
6484                if (DEBUG_INTENT_MATCHING || debug) {
6485                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6486                            + r1.activityInfo.name + "=" + r1.priority);
6487                }
6488                // If the first activity has a higher priority, or a different
6489                // default, then it is always desirable to pick it.
6490                if (r0.priority != r1.priority
6491                        || r0.preferredOrder != r1.preferredOrder
6492                        || r0.isDefault != r1.isDefault) {
6493                    return query.get(0);
6494                }
6495                // If we have saved a preference for a preferred activity for
6496                // this Intent, use that.
6497                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6498                        flags, query, r0.priority, true, false, debug, userId);
6499                if (ri != null) {
6500                    return ri;
6501                }
6502                // If we have an ephemeral app, use it
6503                for (int i = 0; i < N; i++) {
6504                    ri = query.get(i);
6505                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6506                        final String packageName = ri.activityInfo.packageName;
6507                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6508                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6509                        final int status = (int)(packedStatus >> 32);
6510                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6511                            return ri;
6512                        }
6513                    }
6514                }
6515                ri = new ResolveInfo(mResolveInfo);
6516                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6517                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6518                // If all of the options come from the same package, show the application's
6519                // label and icon instead of the generic resolver's.
6520                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6521                // and then throw away the ResolveInfo itself, meaning that the caller loses
6522                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6523                // a fallback for this case; we only set the target package's resources on
6524                // the ResolveInfo, not the ActivityInfo.
6525                final String intentPackage = intent.getPackage();
6526                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6527                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6528                    ri.resolvePackageName = intentPackage;
6529                    if (userNeedsBadging(userId)) {
6530                        ri.noResourceId = true;
6531                    } else {
6532                        ri.icon = appi.icon;
6533                    }
6534                    ri.iconResourceId = appi.icon;
6535                    ri.labelRes = appi.labelRes;
6536                }
6537                ri.activityInfo.applicationInfo = new ApplicationInfo(
6538                        ri.activityInfo.applicationInfo);
6539                if (userId != 0) {
6540                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6541                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6542                }
6543                // Make sure that the resolver is displayable in car mode
6544                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6545                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6546                return ri;
6547            }
6548        }
6549        return null;
6550    }
6551
6552    /**
6553     * Return true if the given list is not empty and all of its contents have
6554     * an activityInfo with the given package name.
6555     */
6556    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6557        if (ArrayUtils.isEmpty(list)) {
6558            return false;
6559        }
6560        for (int i = 0, N = list.size(); i < N; i++) {
6561            final ResolveInfo ri = list.get(i);
6562            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6563            if (ai == null || !packageName.equals(ai.packageName)) {
6564                return false;
6565            }
6566        }
6567        return true;
6568    }
6569
6570    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6571            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6572        final int N = query.size();
6573        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6574                .get(userId);
6575        // Get the list of persistent preferred activities that handle the intent
6576        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6577        List<PersistentPreferredActivity> pprefs = ppir != null
6578                ? ppir.queryIntent(intent, resolvedType,
6579                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6580                        userId)
6581                : null;
6582        if (pprefs != null && pprefs.size() > 0) {
6583            final int M = pprefs.size();
6584            for (int i=0; i<M; i++) {
6585                final PersistentPreferredActivity ppa = pprefs.get(i);
6586                if (DEBUG_PREFERRED || debug) {
6587                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6588                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6589                            + "\n  component=" + ppa.mComponent);
6590                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6591                }
6592                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6593                        flags | MATCH_DISABLED_COMPONENTS, userId);
6594                if (DEBUG_PREFERRED || debug) {
6595                    Slog.v(TAG, "Found persistent preferred activity:");
6596                    if (ai != null) {
6597                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6598                    } else {
6599                        Slog.v(TAG, "  null");
6600                    }
6601                }
6602                if (ai == null) {
6603                    // This previously registered persistent preferred activity
6604                    // component is no longer known. Ignore it and do NOT remove it.
6605                    continue;
6606                }
6607                for (int j=0; j<N; j++) {
6608                    final ResolveInfo ri = query.get(j);
6609                    if (!ri.activityInfo.applicationInfo.packageName
6610                            .equals(ai.applicationInfo.packageName)) {
6611                        continue;
6612                    }
6613                    if (!ri.activityInfo.name.equals(ai.name)) {
6614                        continue;
6615                    }
6616                    //  Found a persistent preference that can handle the intent.
6617                    if (DEBUG_PREFERRED || debug) {
6618                        Slog.v(TAG, "Returning persistent preferred activity: " +
6619                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6620                    }
6621                    return ri;
6622                }
6623            }
6624        }
6625        return null;
6626    }
6627
6628    // TODO: handle preferred activities missing while user has amnesia
6629    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6630            List<ResolveInfo> query, int priority, boolean always,
6631            boolean removeMatches, boolean debug, int userId) {
6632        if (!sUserManager.exists(userId)) return null;
6633        final int callingUid = Binder.getCallingUid();
6634        flags = updateFlagsForResolve(
6635                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6636        intent = updateIntentForResolve(intent);
6637        // writer
6638        synchronized (mPackages) {
6639            // Try to find a matching persistent preferred activity.
6640            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6641                    debug, userId);
6642
6643            // If a persistent preferred activity matched, use it.
6644            if (pri != null) {
6645                return pri;
6646            }
6647
6648            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6649            // Get the list of preferred activities that handle the intent
6650            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6651            List<PreferredActivity> prefs = pir != null
6652                    ? pir.queryIntent(intent, resolvedType,
6653                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6654                            userId)
6655                    : null;
6656            if (prefs != null && prefs.size() > 0) {
6657                boolean changed = false;
6658                try {
6659                    // First figure out how good the original match set is.
6660                    // We will only allow preferred activities that came
6661                    // from the same match quality.
6662                    int match = 0;
6663
6664                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6665
6666                    final int N = query.size();
6667                    for (int j=0; j<N; j++) {
6668                        final ResolveInfo ri = query.get(j);
6669                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6670                                + ": 0x" + Integer.toHexString(match));
6671                        if (ri.match > match) {
6672                            match = ri.match;
6673                        }
6674                    }
6675
6676                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6677                            + Integer.toHexString(match));
6678
6679                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6680                    final int M = prefs.size();
6681                    for (int i=0; i<M; i++) {
6682                        final PreferredActivity pa = prefs.get(i);
6683                        if (DEBUG_PREFERRED || debug) {
6684                            Slog.v(TAG, "Checking PreferredActivity ds="
6685                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6686                                    + "\n  component=" + pa.mPref.mComponent);
6687                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6688                        }
6689                        if (pa.mPref.mMatch != match) {
6690                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6691                                    + Integer.toHexString(pa.mPref.mMatch));
6692                            continue;
6693                        }
6694                        // If it's not an "always" type preferred activity and that's what we're
6695                        // looking for, skip it.
6696                        if (always && !pa.mPref.mAlways) {
6697                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6698                            continue;
6699                        }
6700                        final ActivityInfo ai = getActivityInfo(
6701                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6702                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6703                                userId);
6704                        if (DEBUG_PREFERRED || debug) {
6705                            Slog.v(TAG, "Found preferred activity:");
6706                            if (ai != null) {
6707                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6708                            } else {
6709                                Slog.v(TAG, "  null");
6710                            }
6711                        }
6712                        if (ai == null) {
6713                            // This previously registered preferred activity
6714                            // component is no longer known.  Most likely an update
6715                            // to the app was installed and in the new version this
6716                            // component no longer exists.  Clean it up by removing
6717                            // it from the preferred activities list, and skip it.
6718                            Slog.w(TAG, "Removing dangling preferred activity: "
6719                                    + pa.mPref.mComponent);
6720                            pir.removeFilter(pa);
6721                            changed = true;
6722                            continue;
6723                        }
6724                        for (int j=0; j<N; j++) {
6725                            final ResolveInfo ri = query.get(j);
6726                            if (!ri.activityInfo.applicationInfo.packageName
6727                                    .equals(ai.applicationInfo.packageName)) {
6728                                continue;
6729                            }
6730                            if (!ri.activityInfo.name.equals(ai.name)) {
6731                                continue;
6732                            }
6733
6734                            if (removeMatches) {
6735                                pir.removeFilter(pa);
6736                                changed = true;
6737                                if (DEBUG_PREFERRED) {
6738                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6739                                }
6740                                break;
6741                            }
6742
6743                            // Okay we found a previously set preferred or last chosen app.
6744                            // If the result set is different from when this
6745                            // was created, we need to clear it and re-ask the
6746                            // user their preference, if we're looking for an "always" type entry.
6747                            if (always && !pa.mPref.sameSet(query)) {
6748                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6749                                        + intent + " type " + resolvedType);
6750                                if (DEBUG_PREFERRED) {
6751                                    Slog.v(TAG, "Removing preferred activity since set changed "
6752                                            + pa.mPref.mComponent);
6753                                }
6754                                pir.removeFilter(pa);
6755                                // Re-add the filter as a "last chosen" entry (!always)
6756                                PreferredActivity lastChosen = new PreferredActivity(
6757                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6758                                pir.addFilter(lastChosen);
6759                                changed = true;
6760                                return null;
6761                            }
6762
6763                            // Yay! Either the set matched or we're looking for the last chosen
6764                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6765                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6766                            return ri;
6767                        }
6768                    }
6769                } finally {
6770                    if (changed) {
6771                        if (DEBUG_PREFERRED) {
6772                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6773                        }
6774                        scheduleWritePackageRestrictionsLocked(userId);
6775                    }
6776                }
6777            }
6778        }
6779        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6780        return null;
6781    }
6782
6783    /*
6784     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6785     */
6786    @Override
6787    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6788            int targetUserId) {
6789        mContext.enforceCallingOrSelfPermission(
6790                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6791        List<CrossProfileIntentFilter> matches =
6792                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6793        if (matches != null) {
6794            int size = matches.size();
6795            for (int i = 0; i < size; i++) {
6796                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6797            }
6798        }
6799        if (hasWebURI(intent)) {
6800            // cross-profile app linking works only towards the parent.
6801            final int callingUid = Binder.getCallingUid();
6802            final UserInfo parent = getProfileParent(sourceUserId);
6803            synchronized(mPackages) {
6804                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6805                        false /*includeInstantApps*/);
6806                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6807                        intent, resolvedType, flags, sourceUserId, parent.id);
6808                return xpDomainInfo != null;
6809            }
6810        }
6811        return false;
6812    }
6813
6814    private UserInfo getProfileParent(int userId) {
6815        final long identity = Binder.clearCallingIdentity();
6816        try {
6817            return sUserManager.getProfileParent(userId);
6818        } finally {
6819            Binder.restoreCallingIdentity(identity);
6820        }
6821    }
6822
6823    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6824            String resolvedType, int userId) {
6825        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6826        if (resolver != null) {
6827            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6828        }
6829        return null;
6830    }
6831
6832    @Override
6833    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6834            String resolvedType, int flags, int userId) {
6835        try {
6836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6837
6838            return new ParceledListSlice<>(
6839                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6840        } finally {
6841            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6842        }
6843    }
6844
6845    /**
6846     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6847     * instant, returns {@code null}.
6848     */
6849    private String getInstantAppPackageName(int callingUid) {
6850        synchronized (mPackages) {
6851            // If the caller is an isolated app use the owner's uid for the lookup.
6852            if (Process.isIsolated(callingUid)) {
6853                callingUid = mIsolatedOwners.get(callingUid);
6854            }
6855            final int appId = UserHandle.getAppId(callingUid);
6856            final Object obj = mSettings.getUserIdLPr(appId);
6857            if (obj instanceof PackageSetting) {
6858                final PackageSetting ps = (PackageSetting) obj;
6859                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6860                return isInstantApp ? ps.pkg.packageName : null;
6861            }
6862        }
6863        return null;
6864    }
6865
6866    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6867            String resolvedType, int flags, int userId) {
6868        return queryIntentActivitiesInternal(
6869                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6870    }
6871
6872    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6873            String resolvedType, int flags, int filterCallingUid, int userId,
6874            boolean resolveForStart) {
6875        if (!sUserManager.exists(userId)) return Collections.emptyList();
6876        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6877        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6878                false /* requireFullPermission */, false /* checkShell */,
6879                "query intent activities");
6880        final String pkgName = intent.getPackage();
6881        ComponentName comp = intent.getComponent();
6882        if (comp == null) {
6883            if (intent.getSelector() != null) {
6884                intent = intent.getSelector();
6885                comp = intent.getComponent();
6886            }
6887        }
6888
6889        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6890                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6891        if (comp != null) {
6892            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6893            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6894            if (ai != null) {
6895                // When specifying an explicit component, we prevent the activity from being
6896                // used when either 1) the calling package is normal and the activity is within
6897                // an ephemeral application or 2) the calling package is ephemeral and the
6898                // activity is not visible to ephemeral applications.
6899                final boolean matchInstantApp =
6900                        (flags & PackageManager.MATCH_INSTANT) != 0;
6901                final boolean matchVisibleToInstantAppOnly =
6902                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6903                final boolean matchExplicitlyVisibleOnly =
6904                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6905                final boolean isCallerInstantApp =
6906                        instantAppPkgName != null;
6907                final boolean isTargetSameInstantApp =
6908                        comp.getPackageName().equals(instantAppPkgName);
6909                final boolean isTargetInstantApp =
6910                        (ai.applicationInfo.privateFlags
6911                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6912                final boolean isTargetVisibleToInstantApp =
6913                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6914                final boolean isTargetExplicitlyVisibleToInstantApp =
6915                        isTargetVisibleToInstantApp
6916                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6917                final boolean isTargetHiddenFromInstantApp =
6918                        !isTargetVisibleToInstantApp
6919                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6920                final boolean blockResolution =
6921                        !isTargetSameInstantApp
6922                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6923                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6924                                        && isTargetHiddenFromInstantApp));
6925                if (!blockResolution) {
6926                    final ResolveInfo ri = new ResolveInfo();
6927                    ri.activityInfo = ai;
6928                    list.add(ri);
6929                }
6930            }
6931            return applyPostResolutionFilter(list, instantAppPkgName);
6932        }
6933
6934        // reader
6935        boolean sortResult = false;
6936        boolean addEphemeral = false;
6937        List<ResolveInfo> result;
6938        final boolean ephemeralDisabled = isEphemeralDisabled();
6939        synchronized (mPackages) {
6940            if (pkgName == null) {
6941                List<CrossProfileIntentFilter> matchingFilters =
6942                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6943                // Check for results that need to skip the current profile.
6944                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6945                        resolvedType, flags, userId);
6946                if (xpResolveInfo != null) {
6947                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6948                    xpResult.add(xpResolveInfo);
6949                    return applyPostResolutionFilter(
6950                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6951                }
6952
6953                // Check for results in the current profile.
6954                result = filterIfNotSystemUser(mActivities.queryIntent(
6955                        intent, resolvedType, flags, userId), userId);
6956                addEphemeral = !ephemeralDisabled
6957                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6958                // Check for cross profile results.
6959                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6960                xpResolveInfo = queryCrossProfileIntents(
6961                        matchingFilters, intent, resolvedType, flags, userId,
6962                        hasNonNegativePriorityResult);
6963                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6964                    boolean isVisibleToUser = filterIfNotSystemUser(
6965                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6966                    if (isVisibleToUser) {
6967                        result.add(xpResolveInfo);
6968                        sortResult = true;
6969                    }
6970                }
6971                if (hasWebURI(intent)) {
6972                    CrossProfileDomainInfo xpDomainInfo = null;
6973                    final UserInfo parent = getProfileParent(userId);
6974                    if (parent != null) {
6975                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6976                                flags, userId, parent.id);
6977                    }
6978                    if (xpDomainInfo != null) {
6979                        if (xpResolveInfo != null) {
6980                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6981                            // in the result.
6982                            result.remove(xpResolveInfo);
6983                        }
6984                        if (result.size() == 0 && !addEphemeral) {
6985                            // No result in current profile, but found candidate in parent user.
6986                            // And we are not going to add emphemeral app, so we can return the
6987                            // result straight away.
6988                            result.add(xpDomainInfo.resolveInfo);
6989                            return applyPostResolutionFilter(result, instantAppPkgName);
6990                        }
6991                    } else if (result.size() <= 1 && !addEphemeral) {
6992                        // No result in parent user and <= 1 result in current profile, and we
6993                        // are not going to add emphemeral app, so we can return the result without
6994                        // further processing.
6995                        return applyPostResolutionFilter(result, instantAppPkgName);
6996                    }
6997                    // We have more than one candidate (combining results from current and parent
6998                    // profile), so we need filtering and sorting.
6999                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7000                            intent, flags, result, xpDomainInfo, userId);
7001                    sortResult = true;
7002                }
7003            } else {
7004                final PackageParser.Package pkg = mPackages.get(pkgName);
7005                result = null;
7006                if (pkg != null) {
7007                    result = filterIfNotSystemUser(
7008                            mActivities.queryIntentForPackage(
7009                                    intent, resolvedType, flags, pkg.activities, userId),
7010                            userId);
7011                }
7012                if (result == null || result.size() == 0) {
7013                    // the caller wants to resolve for a particular package; however, there
7014                    // were no installed results, so, try to find an ephemeral result
7015                    addEphemeral = !ephemeralDisabled
7016                            && isInstantAppAllowed(
7017                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7018                    if (result == null) {
7019                        result = new ArrayList<>();
7020                    }
7021                }
7022            }
7023        }
7024        if (addEphemeral) {
7025            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7026        }
7027        if (sortResult) {
7028            Collections.sort(result, mResolvePrioritySorter);
7029        }
7030        return applyPostResolutionFilter(result, instantAppPkgName);
7031    }
7032
7033    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7034            String resolvedType, int flags, int userId) {
7035        // first, check to see if we've got an instant app already installed
7036        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7037        ResolveInfo localInstantApp = null;
7038        boolean blockResolution = false;
7039        if (!alreadyResolvedLocally) {
7040            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7041                    flags
7042                        | PackageManager.GET_RESOLVED_FILTER
7043                        | PackageManager.MATCH_INSTANT
7044                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7045                    userId);
7046            for (int i = instantApps.size() - 1; i >= 0; --i) {
7047                final ResolveInfo info = instantApps.get(i);
7048                final String packageName = info.activityInfo.packageName;
7049                final PackageSetting ps = mSettings.mPackages.get(packageName);
7050                if (ps.getInstantApp(userId)) {
7051                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7052                    final int status = (int)(packedStatus >> 32);
7053                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7054                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7055                        // there's a local instant application installed, but, the user has
7056                        // chosen to never use it; skip resolution and don't acknowledge
7057                        // an instant application is even available
7058                        if (DEBUG_EPHEMERAL) {
7059                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7060                        }
7061                        blockResolution = true;
7062                        break;
7063                    } else {
7064                        // we have a locally installed instant application; skip resolution
7065                        // but acknowledge there's an instant application available
7066                        if (DEBUG_EPHEMERAL) {
7067                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7068                        }
7069                        localInstantApp = info;
7070                        break;
7071                    }
7072                }
7073            }
7074        }
7075        // no app installed, let's see if one's available
7076        AuxiliaryResolveInfo auxiliaryResponse = null;
7077        if (!blockResolution) {
7078            if (localInstantApp == null) {
7079                // we don't have an instant app locally, resolve externally
7080                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7081                final InstantAppRequest requestObject = new InstantAppRequest(
7082                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7083                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7084                auxiliaryResponse =
7085                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7086                                mContext, mInstantAppResolverConnection, requestObject);
7087                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7088            } else {
7089                // we have an instant application locally, but, we can't admit that since
7090                // callers shouldn't be able to determine prior browsing. create a dummy
7091                // auxiliary response so the downstream code behaves as if there's an
7092                // instant application available externally. when it comes time to start
7093                // the instant application, we'll do the right thing.
7094                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7095                auxiliaryResponse = new AuxiliaryResolveInfo(
7096                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7097            }
7098        }
7099        if (auxiliaryResponse != null) {
7100            if (DEBUG_EPHEMERAL) {
7101                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7102            }
7103            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7104            final PackageSetting ps =
7105                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7106            if (ps != null) {
7107                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7108                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7109                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7110                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7111                // make sure this resolver is the default
7112                ephemeralInstaller.isDefault = true;
7113                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7114                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7115                // add a non-generic filter
7116                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7117                ephemeralInstaller.filter.addDataPath(
7118                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7119                ephemeralInstaller.isInstantAppAvailable = true;
7120                result.add(ephemeralInstaller);
7121            }
7122        }
7123        return result;
7124    }
7125
7126    private static class CrossProfileDomainInfo {
7127        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7128        ResolveInfo resolveInfo;
7129        /* Best domain verification status of the activities found in the other profile */
7130        int bestDomainVerificationStatus;
7131    }
7132
7133    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7134            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7135        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7136                sourceUserId)) {
7137            return null;
7138        }
7139        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7140                resolvedType, flags, parentUserId);
7141
7142        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7143            return null;
7144        }
7145        CrossProfileDomainInfo result = null;
7146        int size = resultTargetUser.size();
7147        for (int i = 0; i < size; i++) {
7148            ResolveInfo riTargetUser = resultTargetUser.get(i);
7149            // Intent filter verification is only for filters that specify a host. So don't return
7150            // those that handle all web uris.
7151            if (riTargetUser.handleAllWebDataURI) {
7152                continue;
7153            }
7154            String packageName = riTargetUser.activityInfo.packageName;
7155            PackageSetting ps = mSettings.mPackages.get(packageName);
7156            if (ps == null) {
7157                continue;
7158            }
7159            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7160            int status = (int)(verificationState >> 32);
7161            if (result == null) {
7162                result = new CrossProfileDomainInfo();
7163                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7164                        sourceUserId, parentUserId);
7165                result.bestDomainVerificationStatus = status;
7166            } else {
7167                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7168                        result.bestDomainVerificationStatus);
7169            }
7170        }
7171        // Don't consider matches with status NEVER across profiles.
7172        if (result != null && result.bestDomainVerificationStatus
7173                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7174            return null;
7175        }
7176        return result;
7177    }
7178
7179    /**
7180     * Verification statuses are ordered from the worse to the best, except for
7181     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7182     */
7183    private int bestDomainVerificationStatus(int status1, int status2) {
7184        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7185            return status2;
7186        }
7187        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7188            return status1;
7189        }
7190        return (int) MathUtils.max(status1, status2);
7191    }
7192
7193    private boolean isUserEnabled(int userId) {
7194        long callingId = Binder.clearCallingIdentity();
7195        try {
7196            UserInfo userInfo = sUserManager.getUserInfo(userId);
7197            return userInfo != null && userInfo.isEnabled();
7198        } finally {
7199            Binder.restoreCallingIdentity(callingId);
7200        }
7201    }
7202
7203    /**
7204     * Filter out activities with systemUserOnly flag set, when current user is not System.
7205     *
7206     * @return filtered list
7207     */
7208    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7209        if (userId == UserHandle.USER_SYSTEM) {
7210            return resolveInfos;
7211        }
7212        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7213            ResolveInfo info = resolveInfos.get(i);
7214            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7215                resolveInfos.remove(i);
7216            }
7217        }
7218        return resolveInfos;
7219    }
7220
7221    /**
7222     * Filters out ephemeral activities.
7223     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7224     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7225     *
7226     * @param resolveInfos The pre-filtered list of resolved activities
7227     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7228     *          is performed.
7229     * @return A filtered list of resolved activities.
7230     */
7231    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7232            String ephemeralPkgName) {
7233        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7234            final ResolveInfo info = resolveInfos.get(i);
7235            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7236            // TODO: When adding on-demand split support for non-instant apps, remove this check
7237            // and always apply post filtering
7238            // allow activities that are defined in the provided package
7239            if (isEphemeralApp) {
7240                if (info.activityInfo.splitName != null
7241                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7242                                info.activityInfo.splitName)) {
7243                    // requested activity is defined in a split that hasn't been installed yet.
7244                    // add the installer to the resolve list
7245                    if (DEBUG_EPHEMERAL) {
7246                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7247                    }
7248                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7249                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7250                            info.activityInfo.packageName, info.activityInfo.splitName,
7251                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7252                    // make sure this resolver is the default
7253                    installerInfo.isDefault = true;
7254                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7255                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7256                    // add a non-generic filter
7257                    installerInfo.filter = new IntentFilter();
7258                    // load resources from the correct package
7259                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7260                    resolveInfos.set(i, installerInfo);
7261                    continue;
7262                }
7263            }
7264            // caller is a full app, don't need to apply any other filtering
7265            if (ephemeralPkgName == null) {
7266                continue;
7267            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7268                // caller is same app; don't need to apply any other filtering
7269                continue;
7270            }
7271            // allow activities that have been explicitly exposed to ephemeral apps
7272            if (!isEphemeralApp
7273                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7274                continue;
7275            }
7276            resolveInfos.remove(i);
7277        }
7278        return resolveInfos;
7279    }
7280
7281    /**
7282     * @param resolveInfos list of resolve infos in descending priority order
7283     * @return if the list contains a resolve info with non-negative priority
7284     */
7285    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7286        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7287    }
7288
7289    private static boolean hasWebURI(Intent intent) {
7290        if (intent.getData() == null) {
7291            return false;
7292        }
7293        final String scheme = intent.getScheme();
7294        if (TextUtils.isEmpty(scheme)) {
7295            return false;
7296        }
7297        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7298    }
7299
7300    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7301            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7302            int userId) {
7303        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7304
7305        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7306            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7307                    candidates.size());
7308        }
7309
7310        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7311        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7316
7317        synchronized (mPackages) {
7318            final int count = candidates.size();
7319            // First, try to use linked apps. Partition the candidates into four lists:
7320            // one for the final results, one for the "do not use ever", one for "undefined status"
7321            // and finally one for "browser app type".
7322            for (int n=0; n<count; n++) {
7323                ResolveInfo info = candidates.get(n);
7324                String packageName = info.activityInfo.packageName;
7325                PackageSetting ps = mSettings.mPackages.get(packageName);
7326                if (ps != null) {
7327                    // Add to the special match all list (Browser use case)
7328                    if (info.handleAllWebDataURI) {
7329                        matchAllList.add(info);
7330                        continue;
7331                    }
7332                    // Try to get the status from User settings first
7333                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7334                    int status = (int)(packedStatus >> 32);
7335                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7336                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7337                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7338                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7339                                    + " : linkgen=" + linkGeneration);
7340                        }
7341                        // Use link-enabled generation as preferredOrder, i.e.
7342                        // prefer newly-enabled over earlier-enabled.
7343                        info.preferredOrder = linkGeneration;
7344                        alwaysList.add(info);
7345                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7346                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7347                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7348                        }
7349                        neverList.add(info);
7350                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7351                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7352                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7353                        }
7354                        alwaysAskList.add(info);
7355                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7356                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7357                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7358                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7359                        }
7360                        undefinedList.add(info);
7361                    }
7362                }
7363            }
7364
7365            // We'll want to include browser possibilities in a few cases
7366            boolean includeBrowser = false;
7367
7368            // First try to add the "always" resolution(s) for the current user, if any
7369            if (alwaysList.size() > 0) {
7370                result.addAll(alwaysList);
7371            } else {
7372                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7373                result.addAll(undefinedList);
7374                // Maybe add one for the other profile.
7375                if (xpDomainInfo != null && (
7376                        xpDomainInfo.bestDomainVerificationStatus
7377                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7378                    result.add(xpDomainInfo.resolveInfo);
7379                }
7380                includeBrowser = true;
7381            }
7382
7383            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7384            // If there were 'always' entries their preferred order has been set, so we also
7385            // back that off to make the alternatives equivalent
7386            if (alwaysAskList.size() > 0) {
7387                for (ResolveInfo i : result) {
7388                    i.preferredOrder = 0;
7389                }
7390                result.addAll(alwaysAskList);
7391                includeBrowser = true;
7392            }
7393
7394            if (includeBrowser) {
7395                // Also add browsers (all of them or only the default one)
7396                if (DEBUG_DOMAIN_VERIFICATION) {
7397                    Slog.v(TAG, "   ...including browsers in candidate set");
7398                }
7399                if ((matchFlags & MATCH_ALL) != 0) {
7400                    result.addAll(matchAllList);
7401                } else {
7402                    // Browser/generic handling case.  If there's a default browser, go straight
7403                    // to that (but only if there is no other higher-priority match).
7404                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7405                    int maxMatchPrio = 0;
7406                    ResolveInfo defaultBrowserMatch = null;
7407                    final int numCandidates = matchAllList.size();
7408                    for (int n = 0; n < numCandidates; n++) {
7409                        ResolveInfo info = matchAllList.get(n);
7410                        // track the highest overall match priority...
7411                        if (info.priority > maxMatchPrio) {
7412                            maxMatchPrio = info.priority;
7413                        }
7414                        // ...and the highest-priority default browser match
7415                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7416                            if (defaultBrowserMatch == null
7417                                    || (defaultBrowserMatch.priority < info.priority)) {
7418                                if (debug) {
7419                                    Slog.v(TAG, "Considering default browser match " + info);
7420                                }
7421                                defaultBrowserMatch = info;
7422                            }
7423                        }
7424                    }
7425                    if (defaultBrowserMatch != null
7426                            && defaultBrowserMatch.priority >= maxMatchPrio
7427                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7428                    {
7429                        if (debug) {
7430                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7431                        }
7432                        result.add(defaultBrowserMatch);
7433                    } else {
7434                        result.addAll(matchAllList);
7435                    }
7436                }
7437
7438                // If there is nothing selected, add all candidates and remove the ones that the user
7439                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7440                if (result.size() == 0) {
7441                    result.addAll(candidates);
7442                    result.removeAll(neverList);
7443                }
7444            }
7445        }
7446        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7447            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7448                    result.size());
7449            for (ResolveInfo info : result) {
7450                Slog.v(TAG, "  + " + info.activityInfo);
7451            }
7452        }
7453        return result;
7454    }
7455
7456    // Returns a packed value as a long:
7457    //
7458    // high 'int'-sized word: link status: undefined/ask/never/always.
7459    // low 'int'-sized word: relative priority among 'always' results.
7460    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7461        long result = ps.getDomainVerificationStatusForUser(userId);
7462        // if none available, get the master status
7463        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7464            if (ps.getIntentFilterVerificationInfo() != null) {
7465                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7466            }
7467        }
7468        return result;
7469    }
7470
7471    private ResolveInfo querySkipCurrentProfileIntents(
7472            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7473            int flags, int sourceUserId) {
7474        if (matchingFilters != null) {
7475            int size = matchingFilters.size();
7476            for (int i = 0; i < size; i ++) {
7477                CrossProfileIntentFilter filter = matchingFilters.get(i);
7478                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7479                    // Checking if there are activities in the target user that can handle the
7480                    // intent.
7481                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7482                            resolvedType, flags, sourceUserId);
7483                    if (resolveInfo != null) {
7484                        return resolveInfo;
7485                    }
7486                }
7487            }
7488        }
7489        return null;
7490    }
7491
7492    // Return matching ResolveInfo in target user if any.
7493    private ResolveInfo queryCrossProfileIntents(
7494            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7495            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7496        if (matchingFilters != null) {
7497            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7498            // match the same intent. For performance reasons, it is better not to
7499            // run queryIntent twice for the same userId
7500            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7501            int size = matchingFilters.size();
7502            for (int i = 0; i < size; i++) {
7503                CrossProfileIntentFilter filter = matchingFilters.get(i);
7504                int targetUserId = filter.getTargetUserId();
7505                boolean skipCurrentProfile =
7506                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7507                boolean skipCurrentProfileIfNoMatchFound =
7508                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7509                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7510                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7511                    // Checking if there are activities in the target user that can handle the
7512                    // intent.
7513                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7514                            resolvedType, flags, sourceUserId);
7515                    if (resolveInfo != null) return resolveInfo;
7516                    alreadyTriedUserIds.put(targetUserId, true);
7517                }
7518            }
7519        }
7520        return null;
7521    }
7522
7523    /**
7524     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7525     * will forward the intent to the filter's target user.
7526     * Otherwise, returns null.
7527     */
7528    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7529            String resolvedType, int flags, int sourceUserId) {
7530        int targetUserId = filter.getTargetUserId();
7531        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7532                resolvedType, flags, targetUserId);
7533        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7534            // If all the matches in the target profile are suspended, return null.
7535            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7536                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7537                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7538                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7539                            targetUserId);
7540                }
7541            }
7542        }
7543        return null;
7544    }
7545
7546    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7547            int sourceUserId, int targetUserId) {
7548        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7549        long ident = Binder.clearCallingIdentity();
7550        boolean targetIsProfile;
7551        try {
7552            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7553        } finally {
7554            Binder.restoreCallingIdentity(ident);
7555        }
7556        String className;
7557        if (targetIsProfile) {
7558            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7559        } else {
7560            className = FORWARD_INTENT_TO_PARENT;
7561        }
7562        ComponentName forwardingActivityComponentName = new ComponentName(
7563                mAndroidApplication.packageName, className);
7564        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7565                sourceUserId);
7566        if (!targetIsProfile) {
7567            forwardingActivityInfo.showUserIcon = targetUserId;
7568            forwardingResolveInfo.noResourceId = true;
7569        }
7570        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7571        forwardingResolveInfo.priority = 0;
7572        forwardingResolveInfo.preferredOrder = 0;
7573        forwardingResolveInfo.match = 0;
7574        forwardingResolveInfo.isDefault = true;
7575        forwardingResolveInfo.filter = filter;
7576        forwardingResolveInfo.targetUserId = targetUserId;
7577        return forwardingResolveInfo;
7578    }
7579
7580    @Override
7581    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7582            Intent[] specifics, String[] specificTypes, Intent intent,
7583            String resolvedType, int flags, int userId) {
7584        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7585                specificTypes, intent, resolvedType, flags, userId));
7586    }
7587
7588    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7589            Intent[] specifics, String[] specificTypes, Intent intent,
7590            String resolvedType, int flags, int userId) {
7591        if (!sUserManager.exists(userId)) return Collections.emptyList();
7592        final int callingUid = Binder.getCallingUid();
7593        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7594                false /*includeInstantApps*/);
7595        enforceCrossUserPermission(callingUid, userId,
7596                false /*requireFullPermission*/, false /*checkShell*/,
7597                "query intent activity options");
7598        final String resultsAction = intent.getAction();
7599
7600        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7601                | PackageManager.GET_RESOLVED_FILTER, userId);
7602
7603        if (DEBUG_INTENT_MATCHING) {
7604            Log.v(TAG, "Query " + intent + ": " + results);
7605        }
7606
7607        int specificsPos = 0;
7608        int N;
7609
7610        // todo: note that the algorithm used here is O(N^2).  This
7611        // isn't a problem in our current environment, but if we start running
7612        // into situations where we have more than 5 or 10 matches then this
7613        // should probably be changed to something smarter...
7614
7615        // First we go through and resolve each of the specific items
7616        // that were supplied, taking care of removing any corresponding
7617        // duplicate items in the generic resolve list.
7618        if (specifics != null) {
7619            for (int i=0; i<specifics.length; i++) {
7620                final Intent sintent = specifics[i];
7621                if (sintent == null) {
7622                    continue;
7623                }
7624
7625                if (DEBUG_INTENT_MATCHING) {
7626                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7627                }
7628
7629                String action = sintent.getAction();
7630                if (resultsAction != null && resultsAction.equals(action)) {
7631                    // If this action was explicitly requested, then don't
7632                    // remove things that have it.
7633                    action = null;
7634                }
7635
7636                ResolveInfo ri = null;
7637                ActivityInfo ai = null;
7638
7639                ComponentName comp = sintent.getComponent();
7640                if (comp == null) {
7641                    ri = resolveIntent(
7642                        sintent,
7643                        specificTypes != null ? specificTypes[i] : null,
7644                            flags, userId);
7645                    if (ri == null) {
7646                        continue;
7647                    }
7648                    if (ri == mResolveInfo) {
7649                        // ACK!  Must do something better with this.
7650                    }
7651                    ai = ri.activityInfo;
7652                    comp = new ComponentName(ai.applicationInfo.packageName,
7653                            ai.name);
7654                } else {
7655                    ai = getActivityInfo(comp, flags, userId);
7656                    if (ai == null) {
7657                        continue;
7658                    }
7659                }
7660
7661                // Look for any generic query activities that are duplicates
7662                // of this specific one, and remove them from the results.
7663                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7664                N = results.size();
7665                int j;
7666                for (j=specificsPos; j<N; j++) {
7667                    ResolveInfo sri = results.get(j);
7668                    if ((sri.activityInfo.name.equals(comp.getClassName())
7669                            && sri.activityInfo.applicationInfo.packageName.equals(
7670                                    comp.getPackageName()))
7671                        || (action != null && sri.filter.matchAction(action))) {
7672                        results.remove(j);
7673                        if (DEBUG_INTENT_MATCHING) Log.v(
7674                            TAG, "Removing duplicate item from " + j
7675                            + " due to specific " + specificsPos);
7676                        if (ri == null) {
7677                            ri = sri;
7678                        }
7679                        j--;
7680                        N--;
7681                    }
7682                }
7683
7684                // Add this specific item to its proper place.
7685                if (ri == null) {
7686                    ri = new ResolveInfo();
7687                    ri.activityInfo = ai;
7688                }
7689                results.add(specificsPos, ri);
7690                ri.specificIndex = i;
7691                specificsPos++;
7692            }
7693        }
7694
7695        // Now we go through the remaining generic results and remove any
7696        // duplicate actions that are found here.
7697        N = results.size();
7698        for (int i=specificsPos; i<N-1; i++) {
7699            final ResolveInfo rii = results.get(i);
7700            if (rii.filter == null) {
7701                continue;
7702            }
7703
7704            // Iterate over all of the actions of this result's intent
7705            // filter...  typically this should be just one.
7706            final Iterator<String> it = rii.filter.actionsIterator();
7707            if (it == null) {
7708                continue;
7709            }
7710            while (it.hasNext()) {
7711                final String action = it.next();
7712                if (resultsAction != null && resultsAction.equals(action)) {
7713                    // If this action was explicitly requested, then don't
7714                    // remove things that have it.
7715                    continue;
7716                }
7717                for (int j=i+1; j<N; j++) {
7718                    final ResolveInfo rij = results.get(j);
7719                    if (rij.filter != null && rij.filter.hasAction(action)) {
7720                        results.remove(j);
7721                        if (DEBUG_INTENT_MATCHING) Log.v(
7722                            TAG, "Removing duplicate item from " + j
7723                            + " due to action " + action + " at " + i);
7724                        j--;
7725                        N--;
7726                    }
7727                }
7728            }
7729
7730            // If the caller didn't request filter information, drop it now
7731            // so we don't have to marshall/unmarshall it.
7732            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7733                rii.filter = null;
7734            }
7735        }
7736
7737        // Filter out the caller activity if so requested.
7738        if (caller != null) {
7739            N = results.size();
7740            for (int i=0; i<N; i++) {
7741                ActivityInfo ainfo = results.get(i).activityInfo;
7742                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7743                        && caller.getClassName().equals(ainfo.name)) {
7744                    results.remove(i);
7745                    break;
7746                }
7747            }
7748        }
7749
7750        // If the caller didn't request filter information,
7751        // drop them now so we don't have to
7752        // marshall/unmarshall it.
7753        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7754            N = results.size();
7755            for (int i=0; i<N; i++) {
7756                results.get(i).filter = null;
7757            }
7758        }
7759
7760        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7761        return results;
7762    }
7763
7764    @Override
7765    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7766            String resolvedType, int flags, int userId) {
7767        return new ParceledListSlice<>(
7768                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7769    }
7770
7771    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7772            String resolvedType, int flags, int userId) {
7773        if (!sUserManager.exists(userId)) return Collections.emptyList();
7774        final int callingUid = Binder.getCallingUid();
7775        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7776        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7777                false /*includeInstantApps*/);
7778        ComponentName comp = intent.getComponent();
7779        if (comp == null) {
7780            if (intent.getSelector() != null) {
7781                intent = intent.getSelector();
7782                comp = intent.getComponent();
7783            }
7784        }
7785        if (comp != null) {
7786            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7787            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7788            if (ai != null) {
7789                // When specifying an explicit component, we prevent the activity from being
7790                // used when either 1) the calling package is normal and the activity is within
7791                // an instant application or 2) the calling package is ephemeral and the
7792                // activity is not visible to instant applications.
7793                final boolean matchInstantApp =
7794                        (flags & PackageManager.MATCH_INSTANT) != 0;
7795                final boolean matchVisibleToInstantAppOnly =
7796                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7797                final boolean matchExplicitlyVisibleOnly =
7798                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7799                final boolean isCallerInstantApp =
7800                        instantAppPkgName != null;
7801                final boolean isTargetSameInstantApp =
7802                        comp.getPackageName().equals(instantAppPkgName);
7803                final boolean isTargetInstantApp =
7804                        (ai.applicationInfo.privateFlags
7805                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7806                final boolean isTargetVisibleToInstantApp =
7807                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7808                final boolean isTargetExplicitlyVisibleToInstantApp =
7809                        isTargetVisibleToInstantApp
7810                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7811                final boolean isTargetHiddenFromInstantApp =
7812                        !isTargetVisibleToInstantApp
7813                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7814                final boolean blockResolution =
7815                        !isTargetSameInstantApp
7816                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7817                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7818                                        && isTargetHiddenFromInstantApp));
7819                if (!blockResolution) {
7820                    ResolveInfo ri = new ResolveInfo();
7821                    ri.activityInfo = ai;
7822                    list.add(ri);
7823                }
7824            }
7825            return applyPostResolutionFilter(list, instantAppPkgName);
7826        }
7827
7828        // reader
7829        synchronized (mPackages) {
7830            String pkgName = intent.getPackage();
7831            if (pkgName == null) {
7832                final List<ResolveInfo> result =
7833                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7834                return applyPostResolutionFilter(result, instantAppPkgName);
7835            }
7836            final PackageParser.Package pkg = mPackages.get(pkgName);
7837            if (pkg != null) {
7838                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7839                        intent, resolvedType, flags, pkg.receivers, userId);
7840                return applyPostResolutionFilter(result, instantAppPkgName);
7841            }
7842            return Collections.emptyList();
7843        }
7844    }
7845
7846    @Override
7847    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7848        final int callingUid = Binder.getCallingUid();
7849        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7850    }
7851
7852    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7853            int userId, int callingUid) {
7854        if (!sUserManager.exists(userId)) return null;
7855        flags = updateFlagsForResolve(
7856                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7857        List<ResolveInfo> query = queryIntentServicesInternal(
7858                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7859        if (query != null) {
7860            if (query.size() >= 1) {
7861                // If there is more than one service with the same priority,
7862                // just arbitrarily pick the first one.
7863                return query.get(0);
7864            }
7865        }
7866        return null;
7867    }
7868
7869    @Override
7870    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7871            String resolvedType, int flags, int userId) {
7872        final int callingUid = Binder.getCallingUid();
7873        return new ParceledListSlice<>(queryIntentServicesInternal(
7874                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7875    }
7876
7877    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7878            String resolvedType, int flags, int userId, int callingUid,
7879            boolean includeInstantApps) {
7880        if (!sUserManager.exists(userId)) return Collections.emptyList();
7881        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7882        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7883        ComponentName comp = intent.getComponent();
7884        if (comp == null) {
7885            if (intent.getSelector() != null) {
7886                intent = intent.getSelector();
7887                comp = intent.getComponent();
7888            }
7889        }
7890        if (comp != null) {
7891            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7892            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7893            if (si != null) {
7894                // When specifying an explicit component, we prevent the service from being
7895                // used when either 1) the service is in an instant application and the
7896                // caller is not the same instant application or 2) the calling package is
7897                // ephemeral and the activity is not visible to ephemeral applications.
7898                final boolean matchInstantApp =
7899                        (flags & PackageManager.MATCH_INSTANT) != 0;
7900                final boolean matchVisibleToInstantAppOnly =
7901                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7902                final boolean isCallerInstantApp =
7903                        instantAppPkgName != null;
7904                final boolean isTargetSameInstantApp =
7905                        comp.getPackageName().equals(instantAppPkgName);
7906                final boolean isTargetInstantApp =
7907                        (si.applicationInfo.privateFlags
7908                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7909                final boolean isTargetHiddenFromInstantApp =
7910                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7911                final boolean blockResolution =
7912                        !isTargetSameInstantApp
7913                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7914                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7915                                        && isTargetHiddenFromInstantApp));
7916                if (!blockResolution) {
7917                    final ResolveInfo ri = new ResolveInfo();
7918                    ri.serviceInfo = si;
7919                    list.add(ri);
7920                }
7921            }
7922            return list;
7923        }
7924
7925        // reader
7926        synchronized (mPackages) {
7927            String pkgName = intent.getPackage();
7928            if (pkgName == null) {
7929                return applyPostServiceResolutionFilter(
7930                        mServices.queryIntent(intent, resolvedType, flags, userId),
7931                        instantAppPkgName);
7932            }
7933            final PackageParser.Package pkg = mPackages.get(pkgName);
7934            if (pkg != null) {
7935                return applyPostServiceResolutionFilter(
7936                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7937                                userId),
7938                        instantAppPkgName);
7939            }
7940            return Collections.emptyList();
7941        }
7942    }
7943
7944    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7945            String instantAppPkgName) {
7946        // TODO: When adding on-demand split support for non-instant apps, remove this check
7947        // and always apply post filtering
7948        if (instantAppPkgName == null) {
7949            return resolveInfos;
7950        }
7951        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7952            final ResolveInfo info = resolveInfos.get(i);
7953            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7954            // allow services that are defined in the provided package
7955            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7956                if (info.serviceInfo.splitName != null
7957                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7958                                info.serviceInfo.splitName)) {
7959                    // requested service is defined in a split that hasn't been installed yet.
7960                    // add the installer to the resolve list
7961                    if (DEBUG_EPHEMERAL) {
7962                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7963                    }
7964                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7965                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7966                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7967                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7968                    // make sure this resolver is the default
7969                    installerInfo.isDefault = true;
7970                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7971                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7972                    // add a non-generic filter
7973                    installerInfo.filter = new IntentFilter();
7974                    // load resources from the correct package
7975                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7976                    resolveInfos.set(i, installerInfo);
7977                }
7978                continue;
7979            }
7980            // allow services that have been explicitly exposed to ephemeral apps
7981            if (!isEphemeralApp
7982                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7983                continue;
7984            }
7985            resolveInfos.remove(i);
7986        }
7987        return resolveInfos;
7988    }
7989
7990    @Override
7991    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7992            String resolvedType, int flags, int userId) {
7993        return new ParceledListSlice<>(
7994                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7995    }
7996
7997    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7998            Intent intent, String resolvedType, int flags, int userId) {
7999        if (!sUserManager.exists(userId)) return Collections.emptyList();
8000        final int callingUid = Binder.getCallingUid();
8001        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8002        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8003                false /*includeInstantApps*/);
8004        ComponentName comp = intent.getComponent();
8005        if (comp == null) {
8006            if (intent.getSelector() != null) {
8007                intent = intent.getSelector();
8008                comp = intent.getComponent();
8009            }
8010        }
8011        if (comp != null) {
8012            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8013            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8014            if (pi != null) {
8015                // When specifying an explicit component, we prevent the provider from being
8016                // used when either 1) the provider is in an instant application and the
8017                // caller is not the same instant application or 2) the calling package is an
8018                // instant application and the provider is not visible to instant applications.
8019                final boolean matchInstantApp =
8020                        (flags & PackageManager.MATCH_INSTANT) != 0;
8021                final boolean matchVisibleToInstantAppOnly =
8022                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8023                final boolean isCallerInstantApp =
8024                        instantAppPkgName != null;
8025                final boolean isTargetSameInstantApp =
8026                        comp.getPackageName().equals(instantAppPkgName);
8027                final boolean isTargetInstantApp =
8028                        (pi.applicationInfo.privateFlags
8029                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8030                final boolean isTargetHiddenFromInstantApp =
8031                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8032                final boolean blockResolution =
8033                        !isTargetSameInstantApp
8034                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8035                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8036                                        && isTargetHiddenFromInstantApp));
8037                if (!blockResolution) {
8038                    final ResolveInfo ri = new ResolveInfo();
8039                    ri.providerInfo = pi;
8040                    list.add(ri);
8041                }
8042            }
8043            return list;
8044        }
8045
8046        // reader
8047        synchronized (mPackages) {
8048            String pkgName = intent.getPackage();
8049            if (pkgName == null) {
8050                return applyPostContentProviderResolutionFilter(
8051                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8052                        instantAppPkgName);
8053            }
8054            final PackageParser.Package pkg = mPackages.get(pkgName);
8055            if (pkg != null) {
8056                return applyPostContentProviderResolutionFilter(
8057                        mProviders.queryIntentForPackage(
8058                        intent, resolvedType, flags, pkg.providers, userId),
8059                        instantAppPkgName);
8060            }
8061            return Collections.emptyList();
8062        }
8063    }
8064
8065    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8066            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8067        // TODO: When adding on-demand split support for non-instant applications, remove
8068        // this check and always apply post filtering
8069        if (instantAppPkgName == null) {
8070            return resolveInfos;
8071        }
8072        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8073            final ResolveInfo info = resolveInfos.get(i);
8074            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8075            // allow providers that are defined in the provided package
8076            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8077                if (info.providerInfo.splitName != null
8078                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8079                                info.providerInfo.splitName)) {
8080                    // requested provider is defined in a split that hasn't been installed yet.
8081                    // add the installer to the resolve list
8082                    if (DEBUG_EPHEMERAL) {
8083                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8084                    }
8085                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8086                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8087                            info.providerInfo.packageName, info.providerInfo.splitName,
8088                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8089                    // make sure this resolver is the default
8090                    installerInfo.isDefault = true;
8091                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8092                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8093                    // add a non-generic filter
8094                    installerInfo.filter = new IntentFilter();
8095                    // load resources from the correct package
8096                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8097                    resolveInfos.set(i, installerInfo);
8098                }
8099                continue;
8100            }
8101            // allow providers that have been explicitly exposed to instant applications
8102            if (!isEphemeralApp
8103                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8104                continue;
8105            }
8106            resolveInfos.remove(i);
8107        }
8108        return resolveInfos;
8109    }
8110
8111    @Override
8112    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8113        final int callingUid = Binder.getCallingUid();
8114        if (getInstantAppPackageName(callingUid) != null) {
8115            return ParceledListSlice.emptyList();
8116        }
8117        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8118        flags = updateFlagsForPackage(flags, userId, null);
8119        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8120        enforceCrossUserPermission(callingUid, userId,
8121                true /* requireFullPermission */, false /* checkShell */,
8122                "get installed packages");
8123
8124        // writer
8125        synchronized (mPackages) {
8126            ArrayList<PackageInfo> list;
8127            if (listUninstalled) {
8128                list = new ArrayList<>(mSettings.mPackages.size());
8129                for (PackageSetting ps : mSettings.mPackages.values()) {
8130                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8131                        continue;
8132                    }
8133                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8134                        return null;
8135                    }
8136                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8137                    if (pi != null) {
8138                        list.add(pi);
8139                    }
8140                }
8141            } else {
8142                list = new ArrayList<>(mPackages.size());
8143                for (PackageParser.Package p : mPackages.values()) {
8144                    final PackageSetting ps = (PackageSetting) p.mExtras;
8145                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8146                        continue;
8147                    }
8148                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8149                        return null;
8150                    }
8151                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8152                            p.mExtras, flags, userId);
8153                    if (pi != null) {
8154                        list.add(pi);
8155                    }
8156                }
8157            }
8158
8159            return new ParceledListSlice<>(list);
8160        }
8161    }
8162
8163    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8164            String[] permissions, boolean[] tmp, int flags, int userId) {
8165        int numMatch = 0;
8166        final PermissionsState permissionsState = ps.getPermissionsState();
8167        for (int i=0; i<permissions.length; i++) {
8168            final String permission = permissions[i];
8169            if (permissionsState.hasPermission(permission, userId)) {
8170                tmp[i] = true;
8171                numMatch++;
8172            } else {
8173                tmp[i] = false;
8174            }
8175        }
8176        if (numMatch == 0) {
8177            return;
8178        }
8179        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8180
8181        // The above might return null in cases of uninstalled apps or install-state
8182        // skew across users/profiles.
8183        if (pi != null) {
8184            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8185                if (numMatch == permissions.length) {
8186                    pi.requestedPermissions = permissions;
8187                } else {
8188                    pi.requestedPermissions = new String[numMatch];
8189                    numMatch = 0;
8190                    for (int i=0; i<permissions.length; i++) {
8191                        if (tmp[i]) {
8192                            pi.requestedPermissions[numMatch] = permissions[i];
8193                            numMatch++;
8194                        }
8195                    }
8196                }
8197            }
8198            list.add(pi);
8199        }
8200    }
8201
8202    @Override
8203    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8204            String[] permissions, int flags, int userId) {
8205        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8206        flags = updateFlagsForPackage(flags, userId, permissions);
8207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8208                true /* requireFullPermission */, false /* checkShell */,
8209                "get packages holding permissions");
8210        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8211
8212        // writer
8213        synchronized (mPackages) {
8214            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8215            boolean[] tmpBools = new boolean[permissions.length];
8216            if (listUninstalled) {
8217                for (PackageSetting ps : mSettings.mPackages.values()) {
8218                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8219                            userId);
8220                }
8221            } else {
8222                for (PackageParser.Package pkg : mPackages.values()) {
8223                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8224                    if (ps != null) {
8225                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8226                                userId);
8227                    }
8228                }
8229            }
8230
8231            return new ParceledListSlice<PackageInfo>(list);
8232        }
8233    }
8234
8235    @Override
8236    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8237        final int callingUid = Binder.getCallingUid();
8238        if (getInstantAppPackageName(callingUid) != null) {
8239            return ParceledListSlice.emptyList();
8240        }
8241        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8242        flags = updateFlagsForApplication(flags, userId, null);
8243        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8244
8245        // writer
8246        synchronized (mPackages) {
8247            ArrayList<ApplicationInfo> list;
8248            if (listUninstalled) {
8249                list = new ArrayList<>(mSettings.mPackages.size());
8250                for (PackageSetting ps : mSettings.mPackages.values()) {
8251                    ApplicationInfo ai;
8252                    int effectiveFlags = flags;
8253                    if (ps.isSystem()) {
8254                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8255                    }
8256                    if (ps.pkg != null) {
8257                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8258                            continue;
8259                        }
8260                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8261                            return null;
8262                        }
8263                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8264                                ps.readUserState(userId), userId);
8265                        if (ai != null) {
8266                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8267                        }
8268                    } else {
8269                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8270                        // and already converts to externally visible package name
8271                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8272                                callingUid, effectiveFlags, userId);
8273                    }
8274                    if (ai != null) {
8275                        list.add(ai);
8276                    }
8277                }
8278            } else {
8279                list = new ArrayList<>(mPackages.size());
8280                for (PackageParser.Package p : mPackages.values()) {
8281                    if (p.mExtras != null) {
8282                        PackageSetting ps = (PackageSetting) p.mExtras;
8283                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8284                            continue;
8285                        }
8286                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8287                            return null;
8288                        }
8289                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8290                                ps.readUserState(userId), userId);
8291                        if (ai != null) {
8292                            ai.packageName = resolveExternalPackageNameLPr(p);
8293                            list.add(ai);
8294                        }
8295                    }
8296                }
8297            }
8298
8299            return new ParceledListSlice<>(list);
8300        }
8301    }
8302
8303    @Override
8304    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8305        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306            return null;
8307        }
8308        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8309                "getEphemeralApplications");
8310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8311                true /* requireFullPermission */, false /* checkShell */,
8312                "getEphemeralApplications");
8313        synchronized (mPackages) {
8314            List<InstantAppInfo> instantApps = mInstantAppRegistry
8315                    .getInstantAppsLPr(userId);
8316            if (instantApps != null) {
8317                return new ParceledListSlice<>(instantApps);
8318            }
8319        }
8320        return null;
8321    }
8322
8323    @Override
8324    public boolean isInstantApp(String packageName, int userId) {
8325        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8326                true /* requireFullPermission */, false /* checkShell */,
8327                "isInstantApp");
8328        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8329            return false;
8330        }
8331        int callingUid = Binder.getCallingUid();
8332        if (Process.isIsolated(callingUid)) {
8333            callingUid = mIsolatedOwners.get(callingUid);
8334        }
8335
8336        synchronized (mPackages) {
8337            final PackageSetting ps = mSettings.mPackages.get(packageName);
8338            PackageParser.Package pkg = mPackages.get(packageName);
8339            final boolean returnAllowed =
8340                    ps != null
8341                    && (isCallerSameApp(packageName, callingUid)
8342                            || canViewInstantApps(callingUid, userId)
8343                            || mInstantAppRegistry.isInstantAccessGranted(
8344                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8345            if (returnAllowed) {
8346                return ps.getInstantApp(userId);
8347            }
8348        }
8349        return false;
8350    }
8351
8352    @Override
8353    public byte[] getInstantAppCookie(String packageName, int userId) {
8354        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8355            return null;
8356        }
8357
8358        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8359                true /* requireFullPermission */, false /* checkShell */,
8360                "getInstantAppCookie");
8361        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8362            return null;
8363        }
8364        synchronized (mPackages) {
8365            return mInstantAppRegistry.getInstantAppCookieLPw(
8366                    packageName, userId);
8367        }
8368    }
8369
8370    @Override
8371    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8372        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8373            return true;
8374        }
8375
8376        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8377                true /* requireFullPermission */, true /* checkShell */,
8378                "setInstantAppCookie");
8379        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8380            return false;
8381        }
8382        synchronized (mPackages) {
8383            return mInstantAppRegistry.setInstantAppCookieLPw(
8384                    packageName, cookie, userId);
8385        }
8386    }
8387
8388    @Override
8389    public Bitmap getInstantAppIcon(String packageName, int userId) {
8390        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8391            return null;
8392        }
8393
8394        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8395                "getInstantAppIcon");
8396
8397        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8398                true /* requireFullPermission */, false /* checkShell */,
8399                "getInstantAppIcon");
8400
8401        synchronized (mPackages) {
8402            return mInstantAppRegistry.getInstantAppIconLPw(
8403                    packageName, userId);
8404        }
8405    }
8406
8407    private boolean isCallerSameApp(String packageName, int uid) {
8408        PackageParser.Package pkg = mPackages.get(packageName);
8409        return pkg != null
8410                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8411    }
8412
8413    @Override
8414    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8415        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8416            return ParceledListSlice.emptyList();
8417        }
8418        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8419    }
8420
8421    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8422        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8423
8424        // reader
8425        synchronized (mPackages) {
8426            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8427            final int userId = UserHandle.getCallingUserId();
8428            while (i.hasNext()) {
8429                final PackageParser.Package p = i.next();
8430                if (p.applicationInfo == null) continue;
8431
8432                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8433                        && !p.applicationInfo.isDirectBootAware();
8434                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8435                        && p.applicationInfo.isDirectBootAware();
8436
8437                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8438                        && (!mSafeMode || isSystemApp(p))
8439                        && (matchesUnaware || matchesAware)) {
8440                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8441                    if (ps != null) {
8442                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8443                                ps.readUserState(userId), userId);
8444                        if (ai != null) {
8445                            finalList.add(ai);
8446                        }
8447                    }
8448                }
8449            }
8450        }
8451
8452        return finalList;
8453    }
8454
8455    @Override
8456    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8457        if (!sUserManager.exists(userId)) return null;
8458        flags = updateFlagsForComponent(flags, userId, name);
8459        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8460        // reader
8461        synchronized (mPackages) {
8462            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8463            PackageSetting ps = provider != null
8464                    ? mSettings.mPackages.get(provider.owner.packageName)
8465                    : null;
8466            if (ps != null) {
8467                final boolean isInstantApp = ps.getInstantApp(userId);
8468                // normal application; filter out instant application provider
8469                if (instantAppPkgName == null && isInstantApp) {
8470                    return null;
8471                }
8472                // instant application; filter out other instant applications
8473                if (instantAppPkgName != null
8474                        && isInstantApp
8475                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8476                    return null;
8477                }
8478                // instant application; filter out non-exposed provider
8479                if (instantAppPkgName != null
8480                        && !isInstantApp
8481                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8482                    return null;
8483                }
8484                // provider not enabled
8485                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8486                    return null;
8487                }
8488                return PackageParser.generateProviderInfo(
8489                        provider, flags, ps.readUserState(userId), userId);
8490            }
8491            return null;
8492        }
8493    }
8494
8495    /**
8496     * @deprecated
8497     */
8498    @Deprecated
8499    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8500        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8501            return;
8502        }
8503        // reader
8504        synchronized (mPackages) {
8505            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8506                    .entrySet().iterator();
8507            final int userId = UserHandle.getCallingUserId();
8508            while (i.hasNext()) {
8509                Map.Entry<String, PackageParser.Provider> entry = i.next();
8510                PackageParser.Provider p = entry.getValue();
8511                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8512
8513                if (ps != null && p.syncable
8514                        && (!mSafeMode || (p.info.applicationInfo.flags
8515                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8516                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8517                            ps.readUserState(userId), userId);
8518                    if (info != null) {
8519                        outNames.add(entry.getKey());
8520                        outInfo.add(info);
8521                    }
8522                }
8523            }
8524        }
8525    }
8526
8527    @Override
8528    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8529            int uid, int flags, String metaDataKey) {
8530        final int callingUid = Binder.getCallingUid();
8531        final int userId = processName != null ? UserHandle.getUserId(uid)
8532                : UserHandle.getCallingUserId();
8533        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8534        flags = updateFlagsForComponent(flags, userId, processName);
8535        ArrayList<ProviderInfo> finalList = null;
8536        // reader
8537        synchronized (mPackages) {
8538            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8539            while (i.hasNext()) {
8540                final PackageParser.Provider p = i.next();
8541                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8542                if (ps != null && p.info.authority != null
8543                        && (processName == null
8544                                || (p.info.processName.equals(processName)
8545                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8546                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8547
8548                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8549                    // parameter.
8550                    if (metaDataKey != null
8551                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8552                        continue;
8553                    }
8554                    final ComponentName component =
8555                            new ComponentName(p.info.packageName, p.info.name);
8556                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8557                        continue;
8558                    }
8559                    if (finalList == null) {
8560                        finalList = new ArrayList<ProviderInfo>(3);
8561                    }
8562                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8563                            ps.readUserState(userId), userId);
8564                    if (info != null) {
8565                        finalList.add(info);
8566                    }
8567                }
8568            }
8569        }
8570
8571        if (finalList != null) {
8572            Collections.sort(finalList, mProviderInitOrderSorter);
8573            return new ParceledListSlice<ProviderInfo>(finalList);
8574        }
8575
8576        return ParceledListSlice.emptyList();
8577    }
8578
8579    @Override
8580    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8581        // reader
8582        synchronized (mPackages) {
8583            final int callingUid = Binder.getCallingUid();
8584            final int callingUserId = UserHandle.getUserId(callingUid);
8585            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8586            if (ps == null) return null;
8587            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8588                return null;
8589            }
8590            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8591            return PackageParser.generateInstrumentationInfo(i, flags);
8592        }
8593    }
8594
8595    @Override
8596    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8597            String targetPackage, int flags) {
8598        final int callingUid = Binder.getCallingUid();
8599        final int callingUserId = UserHandle.getUserId(callingUid);
8600        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8601        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8602            return ParceledListSlice.emptyList();
8603        }
8604        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8605    }
8606
8607    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8608            int flags) {
8609        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8610
8611        // reader
8612        synchronized (mPackages) {
8613            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8614            while (i.hasNext()) {
8615                final PackageParser.Instrumentation p = i.next();
8616                if (targetPackage == null
8617                        || targetPackage.equals(p.info.targetPackage)) {
8618                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8619                            flags);
8620                    if (ii != null) {
8621                        finalList.add(ii);
8622                    }
8623                }
8624            }
8625        }
8626
8627        return finalList;
8628    }
8629
8630    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8631        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8632        try {
8633            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8634        } finally {
8635            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8636        }
8637    }
8638
8639    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8640        final File[] files = dir.listFiles();
8641        if (ArrayUtils.isEmpty(files)) {
8642            Log.d(TAG, "No files in app dir " + dir);
8643            return;
8644        }
8645
8646        if (DEBUG_PACKAGE_SCANNING) {
8647            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8648                    + " flags=0x" + Integer.toHexString(parseFlags));
8649        }
8650        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8651                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8652                mParallelPackageParserCallback);
8653
8654        // Submit files for parsing in parallel
8655        int fileCount = 0;
8656        for (File file : files) {
8657            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8658                    && !PackageInstallerService.isStageName(file.getName());
8659            if (!isPackage) {
8660                // Ignore entries which are not packages
8661                continue;
8662            }
8663            parallelPackageParser.submit(file, parseFlags);
8664            fileCount++;
8665        }
8666
8667        // Process results one by one
8668        for (; fileCount > 0; fileCount--) {
8669            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8670            Throwable throwable = parseResult.throwable;
8671            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8672
8673            if (throwable == null) {
8674                // Static shared libraries have synthetic package names
8675                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8676                    renameStaticSharedLibraryPackage(parseResult.pkg);
8677                }
8678                try {
8679                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8680                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8681                                currentTime, null);
8682                    }
8683                } catch (PackageManagerException e) {
8684                    errorCode = e.error;
8685                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8686                }
8687            } else if (throwable instanceof PackageParser.PackageParserException) {
8688                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8689                        throwable;
8690                errorCode = e.error;
8691                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8692            } else {
8693                throw new IllegalStateException("Unexpected exception occurred while parsing "
8694                        + parseResult.scanFile, throwable);
8695            }
8696
8697            // Delete invalid userdata apps
8698            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8699                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8700                logCriticalInfo(Log.WARN,
8701                        "Deleting invalid package at " + parseResult.scanFile);
8702                removeCodePathLI(parseResult.scanFile);
8703            }
8704        }
8705        parallelPackageParser.close();
8706    }
8707
8708    private static File getSettingsProblemFile() {
8709        File dataDir = Environment.getDataDirectory();
8710        File systemDir = new File(dataDir, "system");
8711        File fname = new File(systemDir, "uiderrors.txt");
8712        return fname;
8713    }
8714
8715    static void reportSettingsProblem(int priority, String msg) {
8716        logCriticalInfo(priority, msg);
8717    }
8718
8719    public static void logCriticalInfo(int priority, String msg) {
8720        Slog.println(priority, TAG, msg);
8721        EventLogTags.writePmCriticalInfo(msg);
8722        try {
8723            File fname = getSettingsProblemFile();
8724            FileOutputStream out = new FileOutputStream(fname, true);
8725            PrintWriter pw = new FastPrintWriter(out);
8726            SimpleDateFormat formatter = new SimpleDateFormat();
8727            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8728            pw.println(dateString + ": " + msg);
8729            pw.close();
8730            FileUtils.setPermissions(
8731                    fname.toString(),
8732                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8733                    -1, -1);
8734        } catch (java.io.IOException e) {
8735        }
8736    }
8737
8738    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8739        if (srcFile.isDirectory()) {
8740            final File baseFile = new File(pkg.baseCodePath);
8741            long maxModifiedTime = baseFile.lastModified();
8742            if (pkg.splitCodePaths != null) {
8743                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8744                    final File splitFile = new File(pkg.splitCodePaths[i]);
8745                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8746                }
8747            }
8748            return maxModifiedTime;
8749        }
8750        return srcFile.lastModified();
8751    }
8752
8753    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8754            final int policyFlags) throws PackageManagerException {
8755        // When upgrading from pre-N MR1, verify the package time stamp using the package
8756        // directory and not the APK file.
8757        final long lastModifiedTime = mIsPreNMR1Upgrade
8758                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8759        if (ps != null
8760                && ps.codePath.equals(srcFile)
8761                && ps.timeStamp == lastModifiedTime
8762                && !isCompatSignatureUpdateNeeded(pkg)
8763                && !isRecoverSignatureUpdateNeeded(pkg)) {
8764            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8765            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8766            ArraySet<PublicKey> signingKs;
8767            synchronized (mPackages) {
8768                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8769            }
8770            if (ps.signatures.mSignatures != null
8771                    && ps.signatures.mSignatures.length != 0
8772                    && signingKs != null) {
8773                // Optimization: reuse the existing cached certificates
8774                // if the package appears to be unchanged.
8775                pkg.mSignatures = ps.signatures.mSignatures;
8776                pkg.mSigningKeys = signingKs;
8777                return;
8778            }
8779
8780            Slog.w(TAG, "PackageSetting for " + ps.name
8781                    + " is missing signatures.  Collecting certs again to recover them.");
8782        } else {
8783            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8784        }
8785
8786        try {
8787            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8788            PackageParser.collectCertificates(pkg, policyFlags);
8789        } catch (PackageParserException e) {
8790            throw PackageManagerException.from(e);
8791        } finally {
8792            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8793        }
8794    }
8795
8796    /**
8797     *  Traces a package scan.
8798     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8799     */
8800    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8801            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8803        try {
8804            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8805        } finally {
8806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8807        }
8808    }
8809
8810    /**
8811     *  Scans a package and returns the newly parsed package.
8812     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8813     */
8814    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8815            long currentTime, UserHandle user) throws PackageManagerException {
8816        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8817        PackageParser pp = new PackageParser();
8818        pp.setSeparateProcesses(mSeparateProcesses);
8819        pp.setOnlyCoreApps(mOnlyCore);
8820        pp.setDisplayMetrics(mMetrics);
8821        pp.setCallback(mPackageParserCallback);
8822
8823        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8824            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8825        }
8826
8827        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8828        final PackageParser.Package pkg;
8829        try {
8830            pkg = pp.parsePackage(scanFile, parseFlags);
8831        } catch (PackageParserException e) {
8832            throw PackageManagerException.from(e);
8833        } finally {
8834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8835        }
8836
8837        // Static shared libraries have synthetic package names
8838        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8839            renameStaticSharedLibraryPackage(pkg);
8840        }
8841
8842        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8843    }
8844
8845    /**
8846     *  Scans a package and returns the newly parsed package.
8847     *  @throws PackageManagerException on a parse error.
8848     */
8849    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8850            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8851            throws PackageManagerException {
8852        // If the package has children and this is the first dive in the function
8853        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8854        // packages (parent and children) would be successfully scanned before the
8855        // actual scan since scanning mutates internal state and we want to atomically
8856        // install the package and its children.
8857        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8858            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8859                scanFlags |= SCAN_CHECK_ONLY;
8860            }
8861        } else {
8862            scanFlags &= ~SCAN_CHECK_ONLY;
8863        }
8864
8865        // Scan the parent
8866        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8867                scanFlags, currentTime, user);
8868
8869        // Scan the children
8870        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8871        for (int i = 0; i < childCount; i++) {
8872            PackageParser.Package childPackage = pkg.childPackages.get(i);
8873            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8874                    currentTime, user);
8875        }
8876
8877
8878        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8879            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8880        }
8881
8882        return scannedPkg;
8883    }
8884
8885    /**
8886     *  Scans a package and returns the newly parsed package.
8887     *  @throws PackageManagerException on a parse error.
8888     */
8889    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8890            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8891            throws PackageManagerException {
8892        PackageSetting ps = null;
8893        PackageSetting updatedPkg;
8894        // reader
8895        synchronized (mPackages) {
8896            // Look to see if we already know about this package.
8897            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8898            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8899                // This package has been renamed to its original name.  Let's
8900                // use that.
8901                ps = mSettings.getPackageLPr(oldName);
8902            }
8903            // If there was no original package, see one for the real package name.
8904            if (ps == null) {
8905                ps = mSettings.getPackageLPr(pkg.packageName);
8906            }
8907            // Check to see if this package could be hiding/updating a system
8908            // package.  Must look for it either under the original or real
8909            // package name depending on our state.
8910            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8911            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8912
8913            // If this is a package we don't know about on the system partition, we
8914            // may need to remove disabled child packages on the system partition
8915            // or may need to not add child packages if the parent apk is updated
8916            // on the data partition and no longer defines this child package.
8917            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8918                // If this is a parent package for an updated system app and this system
8919                // app got an OTA update which no longer defines some of the child packages
8920                // we have to prune them from the disabled system packages.
8921                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8922                if (disabledPs != null) {
8923                    final int scannedChildCount = (pkg.childPackages != null)
8924                            ? pkg.childPackages.size() : 0;
8925                    final int disabledChildCount = disabledPs.childPackageNames != null
8926                            ? disabledPs.childPackageNames.size() : 0;
8927                    for (int i = 0; i < disabledChildCount; i++) {
8928                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8929                        boolean disabledPackageAvailable = false;
8930                        for (int j = 0; j < scannedChildCount; j++) {
8931                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8932                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8933                                disabledPackageAvailable = true;
8934                                break;
8935                            }
8936                         }
8937                         if (!disabledPackageAvailable) {
8938                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8939                         }
8940                    }
8941                }
8942            }
8943        }
8944
8945        final boolean isUpdatedPkg = updatedPkg != null;
8946        final boolean isUpdatedSystemPkg = isUpdatedPkg
8947                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8948        boolean isUpdatedPkgBetter = false;
8949        // First check if this is a system package that may involve an update
8950        if (isUpdatedSystemPkg) {
8951            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8952            // it needs to drop FLAG_PRIVILEGED.
8953            if (locationIsPrivileged(scanFile)) {
8954                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8955            } else {
8956                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8957            }
8958
8959            if (ps != null && !ps.codePath.equals(scanFile)) {
8960                // The path has changed from what was last scanned...  check the
8961                // version of the new path against what we have stored to determine
8962                // what to do.
8963                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8964                if (pkg.mVersionCode <= ps.versionCode) {
8965                    // The system package has been updated and the code path does not match
8966                    // Ignore entry. Skip it.
8967                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8968                            + " ignored: updated version " + ps.versionCode
8969                            + " better than this " + pkg.mVersionCode);
8970                    if (!updatedPkg.codePath.equals(scanFile)) {
8971                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8972                                + ps.name + " changing from " + updatedPkg.codePathString
8973                                + " to " + scanFile);
8974                        updatedPkg.codePath = scanFile;
8975                        updatedPkg.codePathString = scanFile.toString();
8976                        updatedPkg.resourcePath = scanFile;
8977                        updatedPkg.resourcePathString = scanFile.toString();
8978                    }
8979                    updatedPkg.pkg = pkg;
8980                    updatedPkg.versionCode = pkg.mVersionCode;
8981
8982                    // Update the disabled system child packages to point to the package too.
8983                    final int childCount = updatedPkg.childPackageNames != null
8984                            ? updatedPkg.childPackageNames.size() : 0;
8985                    for (int i = 0; i < childCount; i++) {
8986                        String childPackageName = updatedPkg.childPackageNames.get(i);
8987                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8988                                childPackageName);
8989                        if (updatedChildPkg != null) {
8990                            updatedChildPkg.pkg = pkg;
8991                            updatedChildPkg.versionCode = pkg.mVersionCode;
8992                        }
8993                    }
8994                } else {
8995                    // The current app on the system partition is better than
8996                    // what we have updated to on the data partition; switch
8997                    // back to the system partition version.
8998                    // At this point, its safely assumed that package installation for
8999                    // apps in system partition will go through. If not there won't be a working
9000                    // version of the app
9001                    // writer
9002                    synchronized (mPackages) {
9003                        // Just remove the loaded entries from package lists.
9004                        mPackages.remove(ps.name);
9005                    }
9006
9007                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9008                            + " reverting from " + ps.codePathString
9009                            + ": new version " + pkg.mVersionCode
9010                            + " better than installed " + ps.versionCode);
9011
9012                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9013                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9014                    synchronized (mInstallLock) {
9015                        args.cleanUpResourcesLI();
9016                    }
9017                    synchronized (mPackages) {
9018                        mSettings.enableSystemPackageLPw(ps.name);
9019                    }
9020                    isUpdatedPkgBetter = true;
9021                }
9022            }
9023        }
9024
9025        String resourcePath = null;
9026        String baseResourcePath = null;
9027        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9028            if (ps != null && ps.resourcePathString != null) {
9029                resourcePath = ps.resourcePathString;
9030                baseResourcePath = ps.resourcePathString;
9031            } else {
9032                // Should not happen at all. Just log an error.
9033                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9034            }
9035        } else {
9036            resourcePath = pkg.codePath;
9037            baseResourcePath = pkg.baseCodePath;
9038        }
9039
9040        // Set application objects path explicitly.
9041        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9042        pkg.setApplicationInfoCodePath(pkg.codePath);
9043        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9044        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9045        pkg.setApplicationInfoResourcePath(resourcePath);
9046        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9047        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9048
9049        // throw an exception if we have an update to a system application, but, it's not more
9050        // recent than the package we've already scanned
9051        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9052            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9053                    + scanFile + " ignored: updated version " + ps.versionCode
9054                    + " better than this " + pkg.mVersionCode);
9055        }
9056
9057        if (isUpdatedPkg) {
9058            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9059            // initially
9060            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9061
9062            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9063            // flag set initially
9064            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9065                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9066            }
9067        }
9068
9069        // Verify certificates against what was last scanned
9070        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9071
9072        /*
9073         * A new system app appeared, but we already had a non-system one of the
9074         * same name installed earlier.
9075         */
9076        boolean shouldHideSystemApp = false;
9077        if (!isUpdatedPkg && ps != null
9078                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9079            /*
9080             * Check to make sure the signatures match first. If they don't,
9081             * wipe the installed application and its data.
9082             */
9083            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9084                    != PackageManager.SIGNATURE_MATCH) {
9085                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9086                        + " signatures don't match existing userdata copy; removing");
9087                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9088                        "scanPackageInternalLI")) {
9089                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9090                }
9091                ps = null;
9092            } else {
9093                /*
9094                 * If the newly-added system app is an older version than the
9095                 * already installed version, hide it. It will be scanned later
9096                 * and re-added like an update.
9097                 */
9098                if (pkg.mVersionCode <= ps.versionCode) {
9099                    shouldHideSystemApp = true;
9100                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9101                            + " but new version " + pkg.mVersionCode + " better than installed "
9102                            + ps.versionCode + "; hiding system");
9103                } else {
9104                    /*
9105                     * The newly found system app is a newer version that the
9106                     * one previously installed. Simply remove the
9107                     * already-installed application and replace it with our own
9108                     * while keeping the application data.
9109                     */
9110                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9111                            + " reverting from " + ps.codePathString + ": new version "
9112                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9113                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9114                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9115                    synchronized (mInstallLock) {
9116                        args.cleanUpResourcesLI();
9117                    }
9118                }
9119            }
9120        }
9121
9122        // The apk is forward locked (not public) if its code and resources
9123        // are kept in different files. (except for app in either system or
9124        // vendor path).
9125        // TODO grab this value from PackageSettings
9126        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9127            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9128                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9129            }
9130        }
9131
9132        final int userId = ((user == null) ? 0 : user.getIdentifier());
9133        if (ps != null && ps.getInstantApp(userId)) {
9134            scanFlags |= SCAN_AS_INSTANT_APP;
9135        }
9136
9137        // Note that we invoke the following method only if we are about to unpack an application
9138        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9139                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9140
9141        /*
9142         * If the system app should be overridden by a previously installed
9143         * data, hide the system app now and let the /data/app scan pick it up
9144         * again.
9145         */
9146        if (shouldHideSystemApp) {
9147            synchronized (mPackages) {
9148                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9149            }
9150        }
9151
9152        return scannedPkg;
9153    }
9154
9155    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9156        // Derive the new package synthetic package name
9157        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9158                + pkg.staticSharedLibVersion);
9159    }
9160
9161    private static String fixProcessName(String defProcessName,
9162            String processName) {
9163        if (processName == null) {
9164            return defProcessName;
9165        }
9166        return processName;
9167    }
9168
9169    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9170            throws PackageManagerException {
9171        if (pkgSetting.signatures.mSignatures != null) {
9172            // Already existing package. Make sure signatures match
9173            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9174                    == PackageManager.SIGNATURE_MATCH;
9175            if (!match) {
9176                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9177                        == PackageManager.SIGNATURE_MATCH;
9178            }
9179            if (!match) {
9180                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9181                        == PackageManager.SIGNATURE_MATCH;
9182            }
9183            if (!match) {
9184                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9185                        + pkg.packageName + " signatures do not match the "
9186                        + "previously installed version; ignoring!");
9187            }
9188        }
9189
9190        // Check for shared user signatures
9191        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9192            // Already existing package. Make sure signatures match
9193            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9194                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9195            if (!match) {
9196                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9197                        == PackageManager.SIGNATURE_MATCH;
9198            }
9199            if (!match) {
9200                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9201                        == PackageManager.SIGNATURE_MATCH;
9202            }
9203            if (!match) {
9204                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9205                        "Package " + pkg.packageName
9206                        + " has no signatures that match those in shared user "
9207                        + pkgSetting.sharedUser.name + "; ignoring!");
9208            }
9209        }
9210    }
9211
9212    /**
9213     * Enforces that only the system UID or root's UID can call a method exposed
9214     * via Binder.
9215     *
9216     * @param message used as message if SecurityException is thrown
9217     * @throws SecurityException if the caller is not system or root
9218     */
9219    private static final void enforceSystemOrRoot(String message) {
9220        final int uid = Binder.getCallingUid();
9221        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9222            throw new SecurityException(message);
9223        }
9224    }
9225
9226    @Override
9227    public void performFstrimIfNeeded() {
9228        enforceSystemOrRoot("Only the system can request fstrim");
9229
9230        // Before everything else, see whether we need to fstrim.
9231        try {
9232            IStorageManager sm = PackageHelper.getStorageManager();
9233            if (sm != null) {
9234                boolean doTrim = false;
9235                final long interval = android.provider.Settings.Global.getLong(
9236                        mContext.getContentResolver(),
9237                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9238                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9239                if (interval > 0) {
9240                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9241                    if (timeSinceLast > interval) {
9242                        doTrim = true;
9243                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9244                                + "; running immediately");
9245                    }
9246                }
9247                if (doTrim) {
9248                    final boolean dexOptDialogShown;
9249                    synchronized (mPackages) {
9250                        dexOptDialogShown = mDexOptDialogShown;
9251                    }
9252                    if (!isFirstBoot() && dexOptDialogShown) {
9253                        try {
9254                            ActivityManager.getService().showBootMessage(
9255                                    mContext.getResources().getString(
9256                                            R.string.android_upgrading_fstrim), true);
9257                        } catch (RemoteException e) {
9258                        }
9259                    }
9260                    sm.runMaintenance();
9261                }
9262            } else {
9263                Slog.e(TAG, "storageManager service unavailable!");
9264            }
9265        } catch (RemoteException e) {
9266            // Can't happen; StorageManagerService is local
9267        }
9268    }
9269
9270    @Override
9271    public void updatePackagesIfNeeded() {
9272        enforceSystemOrRoot("Only the system can request package update");
9273
9274        // We need to re-extract after an OTA.
9275        boolean causeUpgrade = isUpgrade();
9276
9277        // First boot or factory reset.
9278        // Note: we also handle devices that are upgrading to N right now as if it is their
9279        //       first boot, as they do not have profile data.
9280        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9281
9282        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9283        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9284
9285        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9286            return;
9287        }
9288
9289        List<PackageParser.Package> pkgs;
9290        synchronized (mPackages) {
9291            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9292        }
9293
9294        final long startTime = System.nanoTime();
9295        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9296                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9297                    false /* bootComplete */);
9298
9299        final int elapsedTimeSeconds =
9300                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9301
9302        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9305        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9306        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9307    }
9308
9309    /*
9310     * Return the prebuilt profile path given a package base code path.
9311     */
9312    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9313        return pkg.baseCodePath + ".prof";
9314    }
9315
9316    /**
9317     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9318     * containing statistics about the invocation. The array consists of three elements,
9319     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9320     * and {@code numberOfPackagesFailed}.
9321     */
9322    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9323            String compilerFilter, boolean bootComplete) {
9324
9325        int numberOfPackagesVisited = 0;
9326        int numberOfPackagesOptimized = 0;
9327        int numberOfPackagesSkipped = 0;
9328        int numberOfPackagesFailed = 0;
9329        final int numberOfPackagesToDexopt = pkgs.size();
9330
9331        for (PackageParser.Package pkg : pkgs) {
9332            numberOfPackagesVisited++;
9333
9334            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9335                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9336                // that are already compiled.
9337                File profileFile = new File(getPrebuildProfilePath(pkg));
9338                // Copy profile if it exists.
9339                if (profileFile.exists()) {
9340                    try {
9341                        // We could also do this lazily before calling dexopt in
9342                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9343                        // is that we don't have a good way to say "do this only once".
9344                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9345                                pkg.applicationInfo.uid, pkg.packageName)) {
9346                            Log.e(TAG, "Installer failed to copy system profile!");
9347                        }
9348                    } catch (Exception e) {
9349                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9350                                e);
9351                    }
9352                }
9353            }
9354
9355            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9356                if (DEBUG_DEXOPT) {
9357                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9358                }
9359                numberOfPackagesSkipped++;
9360                continue;
9361            }
9362
9363            if (DEBUG_DEXOPT) {
9364                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9365                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9366            }
9367
9368            if (showDialog) {
9369                try {
9370                    ActivityManager.getService().showBootMessage(
9371                            mContext.getResources().getString(R.string.android_upgrading_apk,
9372                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9373                } catch (RemoteException e) {
9374                }
9375                synchronized (mPackages) {
9376                    mDexOptDialogShown = true;
9377                }
9378            }
9379
9380            // If the OTA updates a system app which was previously preopted to a non-preopted state
9381            // the app might end up being verified at runtime. That's because by default the apps
9382            // are verify-profile but for preopted apps there's no profile.
9383            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9384            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9385            // filter (by default 'quicken').
9386            // Note that at this stage unused apps are already filtered.
9387            if (isSystemApp(pkg) &&
9388                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9389                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9390                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9391            }
9392
9393            // checkProfiles is false to avoid merging profiles during boot which
9394            // might interfere with background compilation (b/28612421).
9395            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9396            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9397            // trade-off worth doing to save boot time work.
9398            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9399            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9400                    pkg.packageName,
9401                    compilerFilter,
9402                    dexoptFlags));
9403
9404            boolean secondaryDexOptStatus = true;
9405            if (pkg.isSystemApp()) {
9406                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9407                // too much boot after an OTA.
9408                int secondaryDexoptFlags = dexoptFlags |
9409                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9410                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9411                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9412                        pkg.packageName,
9413                        compilerFilter,
9414                        secondaryDexoptFlags));
9415            }
9416
9417            if (secondaryDexOptStatus) {
9418                switch (primaryDexOptStaus) {
9419                    case PackageDexOptimizer.DEX_OPT_PERFORMED:
9420                        numberOfPackagesOptimized++;
9421                        break;
9422                    case PackageDexOptimizer.DEX_OPT_SKIPPED:
9423                        numberOfPackagesSkipped++;
9424                        break;
9425                    case PackageDexOptimizer.DEX_OPT_FAILED:
9426                        numberOfPackagesFailed++;
9427                        break;
9428                    default:
9429                        Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9430                        break;
9431                }
9432            } else {
9433                numberOfPackagesFailed++;
9434            }
9435        }
9436
9437        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9438                numberOfPackagesFailed };
9439    }
9440
9441    @Override
9442    public void notifyPackageUse(String packageName, int reason) {
9443        synchronized (mPackages) {
9444            final int callingUid = Binder.getCallingUid();
9445            final int callingUserId = UserHandle.getUserId(callingUid);
9446            if (getInstantAppPackageName(callingUid) != null) {
9447                if (!isCallerSameApp(packageName, callingUid)) {
9448                    return;
9449                }
9450            } else {
9451                if (isInstantApp(packageName, callingUserId)) {
9452                    return;
9453                }
9454            }
9455            final PackageParser.Package p = mPackages.get(packageName);
9456            if (p == null) {
9457                return;
9458            }
9459            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9460        }
9461    }
9462
9463    @Override
9464    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9465            List<String> classPaths, String loaderIsa) {
9466        int userId = UserHandle.getCallingUserId();
9467        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9468        if (ai == null) {
9469            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9470                + loadingPackageName + ", user=" + userId);
9471            return;
9472        }
9473        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9474    }
9475
9476    @Override
9477    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9478            IDexModuleRegisterCallback callback) {
9479        int userId = UserHandle.getCallingUserId();
9480        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9481        DexManager.RegisterDexModuleResult result;
9482        if (ai == null) {
9483            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9484                     " calling user. package=" + packageName + ", user=" + userId);
9485            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9486        } else {
9487            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9488        }
9489
9490        if (callback != null) {
9491            mHandler.post(() -> {
9492                try {
9493                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9494                } catch (RemoteException e) {
9495                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9496                }
9497            });
9498        }
9499    }
9500
9501    /**
9502     * Ask the package manager to perform a dex-opt with the given compiler filter.
9503     *
9504     * Note: exposed only for the shell command to allow moving packages explicitly to a
9505     *       definite state.
9506     */
9507    @Override
9508    public boolean performDexOptMode(String packageName,
9509            boolean checkProfiles, String targetCompilerFilter, boolean force,
9510            boolean bootComplete, String splitName) {
9511        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9512                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9513                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9514        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9515                splitName, flags));
9516    }
9517
9518    /**
9519     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9520     * secondary dex files belonging to the given package.
9521     *
9522     * Note: exposed only for the shell command to allow moving packages explicitly to a
9523     *       definite state.
9524     */
9525    @Override
9526    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9527            boolean force) {
9528        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9529                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9530                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9531                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9532        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9533    }
9534
9535    /*package*/ boolean performDexOpt(DexoptOptions options) {
9536        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9537            return false;
9538        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9539            return false;
9540        }
9541
9542        if (options.isDexoptOnlySecondaryDex()) {
9543            return mDexManager.dexoptSecondaryDex(options);
9544        } else {
9545            int dexoptStatus = performDexOptWithStatus(options);
9546            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9547        }
9548    }
9549
9550    /**
9551     * Perform dexopt on the given package and return one of following result:
9552     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9553     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9554     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9555     */
9556    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9557        return performDexOptTraced(options);
9558    }
9559
9560    private int performDexOptTraced(DexoptOptions options) {
9561        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9562        try {
9563            return performDexOptInternal(options);
9564        } finally {
9565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9566        }
9567    }
9568
9569    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9570    // if the package can now be considered up to date for the given filter.
9571    private int performDexOptInternal(DexoptOptions options) {
9572        PackageParser.Package p;
9573        synchronized (mPackages) {
9574            p = mPackages.get(options.getPackageName());
9575            if (p == null) {
9576                // Package could not be found. Report failure.
9577                return PackageDexOptimizer.DEX_OPT_FAILED;
9578            }
9579            mPackageUsage.maybeWriteAsync(mPackages);
9580            mCompilerStats.maybeWriteAsync();
9581        }
9582        long callingId = Binder.clearCallingIdentity();
9583        try {
9584            synchronized (mInstallLock) {
9585                return performDexOptInternalWithDependenciesLI(p, options);
9586            }
9587        } finally {
9588            Binder.restoreCallingIdentity(callingId);
9589        }
9590    }
9591
9592    public ArraySet<String> getOptimizablePackages() {
9593        ArraySet<String> pkgs = new ArraySet<String>();
9594        synchronized (mPackages) {
9595            for (PackageParser.Package p : mPackages.values()) {
9596                if (PackageDexOptimizer.canOptimizePackage(p)) {
9597                    pkgs.add(p.packageName);
9598                }
9599            }
9600        }
9601        return pkgs;
9602    }
9603
9604    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9605            DexoptOptions options) {
9606        // Select the dex optimizer based on the force parameter.
9607        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9608        //       allocate an object here.
9609        PackageDexOptimizer pdo = options.isForce()
9610                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9611                : mPackageDexOptimizer;
9612
9613        // Dexopt all dependencies first. Note: we ignore the return value and march on
9614        // on errors.
9615        // Note that we are going to call performDexOpt on those libraries as many times as
9616        // they are referenced in packages. When we do a batch of performDexOpt (for example
9617        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9618        // and the first package that uses the library will dexopt it. The
9619        // others will see that the compiled code for the library is up to date.
9620        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9621        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9622        if (!deps.isEmpty()) {
9623            for (PackageParser.Package depPackage : deps) {
9624                // TODO: Analyze and investigate if we (should) profile libraries.
9625                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9626                        getOrCreateCompilerPackageStats(depPackage),
9627                        true /* isUsedByOtherApps */,
9628                        options);
9629            }
9630        }
9631        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9632                getOrCreateCompilerPackageStats(p),
9633                mDexManager.isUsedByOtherApps(p.packageName), options);
9634    }
9635
9636    /**
9637     * Reconcile the information we have about the secondary dex files belonging to
9638     * {@code packagName} and the actual dex files. For all dex files that were
9639     * deleted, update the internal records and delete the generated oat files.
9640     */
9641    @Override
9642    public void reconcileSecondaryDexFiles(String packageName) {
9643        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9644            return;
9645        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9646            return;
9647        }
9648        mDexManager.reconcileSecondaryDexFiles(packageName);
9649    }
9650
9651    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9652    // a reference there.
9653    /*package*/ DexManager getDexManager() {
9654        return mDexManager;
9655    }
9656
9657    /**
9658     * Execute the background dexopt job immediately.
9659     */
9660    @Override
9661    public boolean runBackgroundDexoptJob() {
9662        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9663            return false;
9664        }
9665        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9666    }
9667
9668    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9669        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9670                || p.usesStaticLibraries != null) {
9671            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9672            Set<String> collectedNames = new HashSet<>();
9673            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9674
9675            retValue.remove(p);
9676
9677            return retValue;
9678        } else {
9679            return Collections.emptyList();
9680        }
9681    }
9682
9683    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9684            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9685        if (!collectedNames.contains(p.packageName)) {
9686            collectedNames.add(p.packageName);
9687            collected.add(p);
9688
9689            if (p.usesLibraries != null) {
9690                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9691                        null, collected, collectedNames);
9692            }
9693            if (p.usesOptionalLibraries != null) {
9694                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9695                        null, collected, collectedNames);
9696            }
9697            if (p.usesStaticLibraries != null) {
9698                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9699                        p.usesStaticLibrariesVersions, collected, collectedNames);
9700            }
9701        }
9702    }
9703
9704    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9705            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9706        final int libNameCount = libs.size();
9707        for (int i = 0; i < libNameCount; i++) {
9708            String libName = libs.get(i);
9709            int version = (versions != null && versions.length == libNameCount)
9710                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9711            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9712            if (libPkg != null) {
9713                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9714            }
9715        }
9716    }
9717
9718    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9719        synchronized (mPackages) {
9720            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9721            if (libEntry != null) {
9722                return mPackages.get(libEntry.apk);
9723            }
9724            return null;
9725        }
9726    }
9727
9728    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9729        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9730        if (versionedLib == null) {
9731            return null;
9732        }
9733        return versionedLib.get(version);
9734    }
9735
9736    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9737        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9738                pkg.staticSharedLibName);
9739        if (versionedLib == null) {
9740            return null;
9741        }
9742        int previousLibVersion = -1;
9743        final int versionCount = versionedLib.size();
9744        for (int i = 0; i < versionCount; i++) {
9745            final int libVersion = versionedLib.keyAt(i);
9746            if (libVersion < pkg.staticSharedLibVersion) {
9747                previousLibVersion = Math.max(previousLibVersion, libVersion);
9748            }
9749        }
9750        if (previousLibVersion >= 0) {
9751            return versionedLib.get(previousLibVersion);
9752        }
9753        return null;
9754    }
9755
9756    public void shutdown() {
9757        mPackageUsage.writeNow(mPackages);
9758        mCompilerStats.writeNow();
9759        mDexManager.savePackageDexUsageNow();
9760    }
9761
9762    @Override
9763    public void dumpProfiles(String packageName) {
9764        PackageParser.Package pkg;
9765        synchronized (mPackages) {
9766            pkg = mPackages.get(packageName);
9767            if (pkg == null) {
9768                throw new IllegalArgumentException("Unknown package: " + packageName);
9769            }
9770        }
9771        /* Only the shell, root, or the app user should be able to dump profiles. */
9772        int callingUid = Binder.getCallingUid();
9773        if (callingUid != Process.SHELL_UID &&
9774            callingUid != Process.ROOT_UID &&
9775            callingUid != pkg.applicationInfo.uid) {
9776            throw new SecurityException("dumpProfiles");
9777        }
9778
9779        synchronized (mInstallLock) {
9780            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9781            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9782            try {
9783                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9784                String codePaths = TextUtils.join(";", allCodePaths);
9785                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9786            } catch (InstallerException e) {
9787                Slog.w(TAG, "Failed to dump profiles", e);
9788            }
9789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9790        }
9791    }
9792
9793    @Override
9794    public void forceDexOpt(String packageName) {
9795        enforceSystemOrRoot("forceDexOpt");
9796
9797        PackageParser.Package pkg;
9798        synchronized (mPackages) {
9799            pkg = mPackages.get(packageName);
9800            if (pkg == null) {
9801                throw new IllegalArgumentException("Unknown package: " + packageName);
9802            }
9803        }
9804
9805        synchronized (mInstallLock) {
9806            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9807
9808            // Whoever is calling forceDexOpt wants a compiled package.
9809            // Don't use profiles since that may cause compilation to be skipped.
9810            final int res = performDexOptInternalWithDependenciesLI(
9811                    pkg,
9812                    new DexoptOptions(packageName,
9813                            getDefaultCompilerFilter(),
9814                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9815
9816            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9817            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9818                throw new IllegalStateException("Failed to dexopt: " + res);
9819            }
9820        }
9821    }
9822
9823    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9824        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9825            Slog.w(TAG, "Unable to update from " + oldPkg.name
9826                    + " to " + newPkg.packageName
9827                    + ": old package not in system partition");
9828            return false;
9829        } else if (mPackages.get(oldPkg.name) != null) {
9830            Slog.w(TAG, "Unable to update from " + oldPkg.name
9831                    + " to " + newPkg.packageName
9832                    + ": old package still exists");
9833            return false;
9834        }
9835        return true;
9836    }
9837
9838    void removeCodePathLI(File codePath) {
9839        if (codePath.isDirectory()) {
9840            try {
9841                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9842            } catch (InstallerException e) {
9843                Slog.w(TAG, "Failed to remove code path", e);
9844            }
9845        } else {
9846            codePath.delete();
9847        }
9848    }
9849
9850    private int[] resolveUserIds(int userId) {
9851        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9852    }
9853
9854    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9855        if (pkg == null) {
9856            Slog.wtf(TAG, "Package was null!", new Throwable());
9857            return;
9858        }
9859        clearAppDataLeafLIF(pkg, userId, flags);
9860        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9861        for (int i = 0; i < childCount; i++) {
9862            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9863        }
9864    }
9865
9866    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9867        final PackageSetting ps;
9868        synchronized (mPackages) {
9869            ps = mSettings.mPackages.get(pkg.packageName);
9870        }
9871        for (int realUserId : resolveUserIds(userId)) {
9872            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9873            try {
9874                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9875                        ceDataInode);
9876            } catch (InstallerException e) {
9877                Slog.w(TAG, String.valueOf(e));
9878            }
9879        }
9880    }
9881
9882    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9883        if (pkg == null) {
9884            Slog.wtf(TAG, "Package was null!", new Throwable());
9885            return;
9886        }
9887        destroyAppDataLeafLIF(pkg, userId, flags);
9888        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9889        for (int i = 0; i < childCount; i++) {
9890            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9891        }
9892    }
9893
9894    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9895        final PackageSetting ps;
9896        synchronized (mPackages) {
9897            ps = mSettings.mPackages.get(pkg.packageName);
9898        }
9899        for (int realUserId : resolveUserIds(userId)) {
9900            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9901            try {
9902                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9903                        ceDataInode);
9904            } catch (InstallerException e) {
9905                Slog.w(TAG, String.valueOf(e));
9906            }
9907            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9908        }
9909    }
9910
9911    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9912        if (pkg == null) {
9913            Slog.wtf(TAG, "Package was null!", new Throwable());
9914            return;
9915        }
9916        destroyAppProfilesLeafLIF(pkg);
9917        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9918        for (int i = 0; i < childCount; i++) {
9919            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9920        }
9921    }
9922
9923    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9924        try {
9925            mInstaller.destroyAppProfiles(pkg.packageName);
9926        } catch (InstallerException e) {
9927            Slog.w(TAG, String.valueOf(e));
9928        }
9929    }
9930
9931    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9932        if (pkg == null) {
9933            Slog.wtf(TAG, "Package was null!", new Throwable());
9934            return;
9935        }
9936        clearAppProfilesLeafLIF(pkg);
9937        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9938        for (int i = 0; i < childCount; i++) {
9939            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9940        }
9941    }
9942
9943    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9944        try {
9945            mInstaller.clearAppProfiles(pkg.packageName);
9946        } catch (InstallerException e) {
9947            Slog.w(TAG, String.valueOf(e));
9948        }
9949    }
9950
9951    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9952            long lastUpdateTime) {
9953        // Set parent install/update time
9954        PackageSetting ps = (PackageSetting) pkg.mExtras;
9955        if (ps != null) {
9956            ps.firstInstallTime = firstInstallTime;
9957            ps.lastUpdateTime = lastUpdateTime;
9958        }
9959        // Set children install/update time
9960        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9961        for (int i = 0; i < childCount; i++) {
9962            PackageParser.Package childPkg = pkg.childPackages.get(i);
9963            ps = (PackageSetting) childPkg.mExtras;
9964            if (ps != null) {
9965                ps.firstInstallTime = firstInstallTime;
9966                ps.lastUpdateTime = lastUpdateTime;
9967            }
9968        }
9969    }
9970
9971    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9972            SharedLibraryEntry file,
9973            PackageParser.Package changingLib) {
9974        if (file.path != null) {
9975            usesLibraryFiles.add(file.path);
9976            return;
9977        }
9978        PackageParser.Package p = mPackages.get(file.apk);
9979        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9980            // If we are doing this while in the middle of updating a library apk,
9981            // then we need to make sure to use that new apk for determining the
9982            // dependencies here.  (We haven't yet finished committing the new apk
9983            // to the package manager state.)
9984            if (p == null || p.packageName.equals(changingLib.packageName)) {
9985                p = changingLib;
9986            }
9987        }
9988        if (p != null) {
9989            usesLibraryFiles.addAll(p.getAllCodePaths());
9990            if (p.usesLibraryFiles != null) {
9991                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9992            }
9993        }
9994    }
9995
9996    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9997            PackageParser.Package changingLib) throws PackageManagerException {
9998        if (pkg == null) {
9999            return;
10000        }
10001        // The collection used here must maintain the order of addition (so
10002        // that libraries are searched in the correct order) and must have no
10003        // duplicates.
10004        Set<String> usesLibraryFiles = null;
10005        if (pkg.usesLibraries != null) {
10006            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10007                    null, null, pkg.packageName, changingLib, true, null);
10008        }
10009        if (pkg.usesStaticLibraries != null) {
10010            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10011                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10012                    pkg.packageName, changingLib, true, usesLibraryFiles);
10013        }
10014        if (pkg.usesOptionalLibraries != null) {
10015            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10016                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10017        }
10018        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10019            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10020        } else {
10021            pkg.usesLibraryFiles = null;
10022        }
10023    }
10024
10025    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10026            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10027            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10028            boolean required, @Nullable Set<String> outUsedLibraries)
10029            throws PackageManagerException {
10030        final int libCount = requestedLibraries.size();
10031        for (int i = 0; i < libCount; i++) {
10032            final String libName = requestedLibraries.get(i);
10033            final int libVersion = requiredVersions != null ? requiredVersions[i]
10034                    : SharedLibraryInfo.VERSION_UNDEFINED;
10035            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10036            if (libEntry == null) {
10037                if (required) {
10038                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10039                            "Package " + packageName + " requires unavailable shared library "
10040                                    + libName + "; failing!");
10041                } else if (DEBUG_SHARED_LIBRARIES) {
10042                    Slog.i(TAG, "Package " + packageName
10043                            + " desires unavailable shared library "
10044                            + libName + "; ignoring!");
10045                }
10046            } else {
10047                if (requiredVersions != null && requiredCertDigests != null) {
10048                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10049                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10050                            "Package " + packageName + " requires unavailable static shared"
10051                                    + " library " + libName + " version "
10052                                    + libEntry.info.getVersion() + "; failing!");
10053                    }
10054
10055                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10056                    if (libPkg == null) {
10057                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10058                                "Package " + packageName + " requires unavailable static shared"
10059                                        + " library; failing!");
10060                    }
10061
10062                    String expectedCertDigest = requiredCertDigests[i];
10063                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10064                                libPkg.mSignatures[0]);
10065                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10066                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10067                                "Package " + packageName + " requires differently signed" +
10068                                        " static shared library; failing!");
10069                    }
10070                }
10071
10072                if (outUsedLibraries == null) {
10073                    // Use LinkedHashSet to preserve the order of files added to
10074                    // usesLibraryFiles while eliminating duplicates.
10075                    outUsedLibraries = new LinkedHashSet<>();
10076                }
10077                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10078            }
10079        }
10080        return outUsedLibraries;
10081    }
10082
10083    private static boolean hasString(List<String> list, List<String> which) {
10084        if (list == null) {
10085            return false;
10086        }
10087        for (int i=list.size()-1; i>=0; i--) {
10088            for (int j=which.size()-1; j>=0; j--) {
10089                if (which.get(j).equals(list.get(i))) {
10090                    return true;
10091                }
10092            }
10093        }
10094        return false;
10095    }
10096
10097    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10098            PackageParser.Package changingPkg) {
10099        ArrayList<PackageParser.Package> res = null;
10100        for (PackageParser.Package pkg : mPackages.values()) {
10101            if (changingPkg != null
10102                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10103                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10104                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10105                            changingPkg.staticSharedLibName)) {
10106                return null;
10107            }
10108            if (res == null) {
10109                res = new ArrayList<>();
10110            }
10111            res.add(pkg);
10112            try {
10113                updateSharedLibrariesLPr(pkg, changingPkg);
10114            } catch (PackageManagerException e) {
10115                // If a system app update or an app and a required lib missing we
10116                // delete the package and for updated system apps keep the data as
10117                // it is better for the user to reinstall than to be in an limbo
10118                // state. Also libs disappearing under an app should never happen
10119                // - just in case.
10120                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10121                    final int flags = pkg.isUpdatedSystemApp()
10122                            ? PackageManager.DELETE_KEEP_DATA : 0;
10123                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10124                            flags , null, true, null);
10125                }
10126                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10127            }
10128        }
10129        return res;
10130    }
10131
10132    /**
10133     * Derive the value of the {@code cpuAbiOverride} based on the provided
10134     * value and an optional stored value from the package settings.
10135     */
10136    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10137        String cpuAbiOverride = null;
10138
10139        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10140            cpuAbiOverride = null;
10141        } else if (abiOverride != null) {
10142            cpuAbiOverride = abiOverride;
10143        } else if (settings != null) {
10144            cpuAbiOverride = settings.cpuAbiOverrideString;
10145        }
10146
10147        return cpuAbiOverride;
10148    }
10149
10150    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10151            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10152                    throws PackageManagerException {
10153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10154        // If the package has children and this is the first dive in the function
10155        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10156        // whether all packages (parent and children) would be successfully scanned
10157        // before the actual scan since scanning mutates internal state and we want
10158        // to atomically install the package and its children.
10159        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10160            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10161                scanFlags |= SCAN_CHECK_ONLY;
10162            }
10163        } else {
10164            scanFlags &= ~SCAN_CHECK_ONLY;
10165        }
10166
10167        final PackageParser.Package scannedPkg;
10168        try {
10169            // Scan the parent
10170            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10171            // Scan the children
10172            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10173            for (int i = 0; i < childCount; i++) {
10174                PackageParser.Package childPkg = pkg.childPackages.get(i);
10175                scanPackageLI(childPkg, policyFlags,
10176                        scanFlags, currentTime, user);
10177            }
10178        } finally {
10179            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10180        }
10181
10182        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10183            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10184        }
10185
10186        return scannedPkg;
10187    }
10188
10189    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10190            int scanFlags, long currentTime, @Nullable UserHandle user)
10191                    throws PackageManagerException {
10192        boolean success = false;
10193        try {
10194            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10195                    currentTime, user);
10196            success = true;
10197            return res;
10198        } finally {
10199            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10200                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10201                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10202                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10203                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10204            }
10205        }
10206    }
10207
10208    /**
10209     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10210     */
10211    private static boolean apkHasCode(String fileName) {
10212        StrictJarFile jarFile = null;
10213        try {
10214            jarFile = new StrictJarFile(fileName,
10215                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10216            return jarFile.findEntry("classes.dex") != null;
10217        } catch (IOException ignore) {
10218        } finally {
10219            try {
10220                if (jarFile != null) {
10221                    jarFile.close();
10222                }
10223            } catch (IOException ignore) {}
10224        }
10225        return false;
10226    }
10227
10228    /**
10229     * Enforces code policy for the package. This ensures that if an APK has
10230     * declared hasCode="true" in its manifest that the APK actually contains
10231     * code.
10232     *
10233     * @throws PackageManagerException If bytecode could not be found when it should exist
10234     */
10235    private static void assertCodePolicy(PackageParser.Package pkg)
10236            throws PackageManagerException {
10237        final boolean shouldHaveCode =
10238                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10239        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10240            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10241                    "Package " + pkg.baseCodePath + " code is missing");
10242        }
10243
10244        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10245            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10246                final boolean splitShouldHaveCode =
10247                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10248                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10249                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10250                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10251                }
10252            }
10253        }
10254    }
10255
10256    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10257            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10258                    throws PackageManagerException {
10259        if (DEBUG_PACKAGE_SCANNING) {
10260            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10261                Log.d(TAG, "Scanning package " + pkg.packageName);
10262        }
10263
10264        applyPolicy(pkg, policyFlags);
10265
10266        assertPackageIsValid(pkg, policyFlags, scanFlags);
10267
10268        if (Build.IS_DEBUGGABLE &&
10269                pkg.isPrivilegedApp() &&
10270                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10271            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10272        }
10273
10274        // Initialize package source and resource directories
10275        final File scanFile = new File(pkg.codePath);
10276        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10277        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10278
10279        SharedUserSetting suid = null;
10280        PackageSetting pkgSetting = null;
10281
10282        // Getting the package setting may have a side-effect, so if we
10283        // are only checking if scan would succeed, stash a copy of the
10284        // old setting to restore at the end.
10285        PackageSetting nonMutatedPs = null;
10286
10287        // We keep references to the derived CPU Abis from settings in oder to reuse
10288        // them in the case where we're not upgrading or booting for the first time.
10289        String primaryCpuAbiFromSettings = null;
10290        String secondaryCpuAbiFromSettings = null;
10291
10292        // writer
10293        synchronized (mPackages) {
10294            if (pkg.mSharedUserId != null) {
10295                // SIDE EFFECTS; may potentially allocate a new shared user
10296                suid = mSettings.getSharedUserLPw(
10297                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10298                if (DEBUG_PACKAGE_SCANNING) {
10299                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10300                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10301                                + "): packages=" + suid.packages);
10302                }
10303            }
10304
10305            // Check if we are renaming from an original package name.
10306            PackageSetting origPackage = null;
10307            String realName = null;
10308            if (pkg.mOriginalPackages != null) {
10309                // This package may need to be renamed to a previously
10310                // installed name.  Let's check on that...
10311                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10312                if (pkg.mOriginalPackages.contains(renamed)) {
10313                    // This package had originally been installed as the
10314                    // original name, and we have already taken care of
10315                    // transitioning to the new one.  Just update the new
10316                    // one to continue using the old name.
10317                    realName = pkg.mRealPackage;
10318                    if (!pkg.packageName.equals(renamed)) {
10319                        // Callers into this function may have already taken
10320                        // care of renaming the package; only do it here if
10321                        // it is not already done.
10322                        pkg.setPackageName(renamed);
10323                    }
10324                } else {
10325                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10326                        if ((origPackage = mSettings.getPackageLPr(
10327                                pkg.mOriginalPackages.get(i))) != null) {
10328                            // We do have the package already installed under its
10329                            // original name...  should we use it?
10330                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10331                                // New package is not compatible with original.
10332                                origPackage = null;
10333                                continue;
10334                            } else if (origPackage.sharedUser != null) {
10335                                // Make sure uid is compatible between packages.
10336                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10337                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10338                                            + " to " + pkg.packageName + ": old uid "
10339                                            + origPackage.sharedUser.name
10340                                            + " differs from " + pkg.mSharedUserId);
10341                                    origPackage = null;
10342                                    continue;
10343                                }
10344                                // TODO: Add case when shared user id is added [b/28144775]
10345                            } else {
10346                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10347                                        + pkg.packageName + " to old name " + origPackage.name);
10348                            }
10349                            break;
10350                        }
10351                    }
10352                }
10353            }
10354
10355            if (mTransferedPackages.contains(pkg.packageName)) {
10356                Slog.w(TAG, "Package " + pkg.packageName
10357                        + " was transferred to another, but its .apk remains");
10358            }
10359
10360            // See comments in nonMutatedPs declaration
10361            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10362                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10363                if (foundPs != null) {
10364                    nonMutatedPs = new PackageSetting(foundPs);
10365                }
10366            }
10367
10368            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10369                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10370                if (foundPs != null) {
10371                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10372                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10373                }
10374            }
10375
10376            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10377            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10378                PackageManagerService.reportSettingsProblem(Log.WARN,
10379                        "Package " + pkg.packageName + " shared user changed from "
10380                                + (pkgSetting.sharedUser != null
10381                                        ? pkgSetting.sharedUser.name : "<nothing>")
10382                                + " to "
10383                                + (suid != null ? suid.name : "<nothing>")
10384                                + "; replacing with new");
10385                pkgSetting = null;
10386            }
10387            final PackageSetting oldPkgSetting =
10388                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10389            final PackageSetting disabledPkgSetting =
10390                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10391
10392            String[] usesStaticLibraries = null;
10393            if (pkg.usesStaticLibraries != null) {
10394                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10395                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10396            }
10397
10398            if (pkgSetting == null) {
10399                final String parentPackageName = (pkg.parentPackage != null)
10400                        ? pkg.parentPackage.packageName : null;
10401                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10402                // REMOVE SharedUserSetting from method; update in a separate call
10403                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10404                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10405                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10406                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10407                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10408                        true /*allowInstall*/, instantApp, parentPackageName,
10409                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10410                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10411                // SIDE EFFECTS; updates system state; move elsewhere
10412                if (origPackage != null) {
10413                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10414                }
10415                mSettings.addUserToSettingLPw(pkgSetting);
10416            } else {
10417                // REMOVE SharedUserSetting from method; update in a separate call.
10418                //
10419                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10420                // secondaryCpuAbi are not known at this point so we always update them
10421                // to null here, only to reset them at a later point.
10422                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10423                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10424                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10425                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10426                        UserManagerService.getInstance(), usesStaticLibraries,
10427                        pkg.usesStaticLibrariesVersions);
10428            }
10429            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10430            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10431
10432            // SIDE EFFECTS; modifies system state; move elsewhere
10433            if (pkgSetting.origPackage != null) {
10434                // If we are first transitioning from an original package,
10435                // fix up the new package's name now.  We need to do this after
10436                // looking up the package under its new name, so getPackageLP
10437                // can take care of fiddling things correctly.
10438                pkg.setPackageName(origPackage.name);
10439
10440                // File a report about this.
10441                String msg = "New package " + pkgSetting.realName
10442                        + " renamed to replace old package " + pkgSetting.name;
10443                reportSettingsProblem(Log.WARN, msg);
10444
10445                // Make a note of it.
10446                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10447                    mTransferedPackages.add(origPackage.name);
10448                }
10449
10450                // No longer need to retain this.
10451                pkgSetting.origPackage = null;
10452            }
10453
10454            // SIDE EFFECTS; modifies system state; move elsewhere
10455            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10456                // Make a note of it.
10457                mTransferedPackages.add(pkg.packageName);
10458            }
10459
10460            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10461                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10462            }
10463
10464            if ((scanFlags & SCAN_BOOTING) == 0
10465                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10466                // Check all shared libraries and map to their actual file path.
10467                // We only do this here for apps not on a system dir, because those
10468                // are the only ones that can fail an install due to this.  We
10469                // will take care of the system apps by updating all of their
10470                // library paths after the scan is done. Also during the initial
10471                // scan don't update any libs as we do this wholesale after all
10472                // apps are scanned to avoid dependency based scanning.
10473                updateSharedLibrariesLPr(pkg, null);
10474            }
10475
10476            if (mFoundPolicyFile) {
10477                SELinuxMMAC.assignSeInfoValue(pkg);
10478            }
10479            pkg.applicationInfo.uid = pkgSetting.appId;
10480            pkg.mExtras = pkgSetting;
10481
10482
10483            // Static shared libs have same package with different versions where
10484            // we internally use a synthetic package name to allow multiple versions
10485            // of the same package, therefore we need to compare signatures against
10486            // the package setting for the latest library version.
10487            PackageSetting signatureCheckPs = pkgSetting;
10488            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10489                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10490                if (libraryEntry != null) {
10491                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10492                }
10493            }
10494
10495            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10496                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10497                    // We just determined the app is signed correctly, so bring
10498                    // over the latest parsed certs.
10499                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10500                } else {
10501                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10502                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10503                                "Package " + pkg.packageName + " upgrade keys do not match the "
10504                                + "previously installed version");
10505                    } else {
10506                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10507                        String msg = "System package " + pkg.packageName
10508                                + " signature changed; retaining data.";
10509                        reportSettingsProblem(Log.WARN, msg);
10510                    }
10511                }
10512            } else {
10513                try {
10514                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10515                    verifySignaturesLP(signatureCheckPs, pkg);
10516                    // We just determined the app is signed correctly, so bring
10517                    // over the latest parsed certs.
10518                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10519                } catch (PackageManagerException e) {
10520                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10521                        throw e;
10522                    }
10523                    // The signature has changed, but this package is in the system
10524                    // image...  let's recover!
10525                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10526                    // However...  if this package is part of a shared user, but it
10527                    // doesn't match the signature of the shared user, let's fail.
10528                    // What this means is that you can't change the signatures
10529                    // associated with an overall shared user, which doesn't seem all
10530                    // that unreasonable.
10531                    if (signatureCheckPs.sharedUser != null) {
10532                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10533                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10534                            throw new PackageManagerException(
10535                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10536                                    "Signature mismatch for shared user: "
10537                                            + pkgSetting.sharedUser);
10538                        }
10539                    }
10540                    // File a report about this.
10541                    String msg = "System package " + pkg.packageName
10542                            + " signature changed; retaining data.";
10543                    reportSettingsProblem(Log.WARN, msg);
10544                }
10545            }
10546
10547            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10548                // This package wants to adopt ownership of permissions from
10549                // another package.
10550                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10551                    final String origName = pkg.mAdoptPermissions.get(i);
10552                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10553                    if (orig != null) {
10554                        if (verifyPackageUpdateLPr(orig, pkg)) {
10555                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10556                                    + pkg.packageName);
10557                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10558                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10559                        }
10560                    }
10561                }
10562            }
10563        }
10564
10565        pkg.applicationInfo.processName = fixProcessName(
10566                pkg.applicationInfo.packageName,
10567                pkg.applicationInfo.processName);
10568
10569        if (pkg != mPlatformPackage) {
10570            // Get all of our default paths setup
10571            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10572        }
10573
10574        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10575
10576        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10577            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10578                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10579                final boolean extractNativeLibs = !pkg.isLibrary();
10580                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10581                        mAppLib32InstallDir);
10582                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10583
10584                // Some system apps still use directory structure for native libraries
10585                // in which case we might end up not detecting abi solely based on apk
10586                // structure. Try to detect abi based on directory structure.
10587                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10588                        pkg.applicationInfo.primaryCpuAbi == null) {
10589                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10590                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10591                }
10592            } else {
10593                // This is not a first boot or an upgrade, don't bother deriving the
10594                // ABI during the scan. Instead, trust the value that was stored in the
10595                // package setting.
10596                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10597                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10598
10599                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10600
10601                if (DEBUG_ABI_SELECTION) {
10602                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10603                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10604                        pkg.applicationInfo.secondaryCpuAbi);
10605                }
10606            }
10607        } else {
10608            if ((scanFlags & SCAN_MOVE) != 0) {
10609                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10610                // but we already have this packages package info in the PackageSetting. We just
10611                // use that and derive the native library path based on the new codepath.
10612                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10613                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10614            }
10615
10616            // Set native library paths again. For moves, the path will be updated based on the
10617            // ABIs we've determined above. For non-moves, the path will be updated based on the
10618            // ABIs we determined during compilation, but the path will depend on the final
10619            // package path (after the rename away from the stage path).
10620            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10621        }
10622
10623        // This is a special case for the "system" package, where the ABI is
10624        // dictated by the zygote configuration (and init.rc). We should keep track
10625        // of this ABI so that we can deal with "normal" applications that run under
10626        // the same UID correctly.
10627        if (mPlatformPackage == pkg) {
10628            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10629                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10630        }
10631
10632        // If there's a mismatch between the abi-override in the package setting
10633        // and the abiOverride specified for the install. Warn about this because we
10634        // would've already compiled the app without taking the package setting into
10635        // account.
10636        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10637            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10638                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10639                        " for package " + pkg.packageName);
10640            }
10641        }
10642
10643        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10644        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10645        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10646
10647        // Copy the derived override back to the parsed package, so that we can
10648        // update the package settings accordingly.
10649        pkg.cpuAbiOverride = cpuAbiOverride;
10650
10651        if (DEBUG_ABI_SELECTION) {
10652            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10653                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10654                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10655        }
10656
10657        // Push the derived path down into PackageSettings so we know what to
10658        // clean up at uninstall time.
10659        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10660
10661        if (DEBUG_ABI_SELECTION) {
10662            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10663                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10664                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10665        }
10666
10667        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10668        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10669            // We don't do this here during boot because we can do it all
10670            // at once after scanning all existing packages.
10671            //
10672            // We also do this *before* we perform dexopt on this package, so that
10673            // we can avoid redundant dexopts, and also to make sure we've got the
10674            // code and package path correct.
10675            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10676        }
10677
10678        if (mFactoryTest && pkg.requestedPermissions.contains(
10679                android.Manifest.permission.FACTORY_TEST)) {
10680            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10681        }
10682
10683        if (isSystemApp(pkg)) {
10684            pkgSetting.isOrphaned = true;
10685        }
10686
10687        // Take care of first install / last update times.
10688        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10689        if (currentTime != 0) {
10690            if (pkgSetting.firstInstallTime == 0) {
10691                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10692            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10693                pkgSetting.lastUpdateTime = currentTime;
10694            }
10695        } else if (pkgSetting.firstInstallTime == 0) {
10696            // We need *something*.  Take time time stamp of the file.
10697            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10698        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10699            if (scanFileTime != pkgSetting.timeStamp) {
10700                // A package on the system image has changed; consider this
10701                // to be an update.
10702                pkgSetting.lastUpdateTime = scanFileTime;
10703            }
10704        }
10705        pkgSetting.setTimeStamp(scanFileTime);
10706
10707        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10708            if (nonMutatedPs != null) {
10709                synchronized (mPackages) {
10710                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10711                }
10712            }
10713        } else {
10714            final int userId = user == null ? 0 : user.getIdentifier();
10715            // Modify state for the given package setting
10716            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10717                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10718            if (pkgSetting.getInstantApp(userId)) {
10719                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10720            }
10721        }
10722        return pkg;
10723    }
10724
10725    /**
10726     * Applies policy to the parsed package based upon the given policy flags.
10727     * Ensures the package is in a good state.
10728     * <p>
10729     * Implementation detail: This method must NOT have any side effect. It would
10730     * ideally be static, but, it requires locks to read system state.
10731     */
10732    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10733        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10734            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10735            if (pkg.applicationInfo.isDirectBootAware()) {
10736                // we're direct boot aware; set for all components
10737                for (PackageParser.Service s : pkg.services) {
10738                    s.info.encryptionAware = s.info.directBootAware = true;
10739                }
10740                for (PackageParser.Provider p : pkg.providers) {
10741                    p.info.encryptionAware = p.info.directBootAware = true;
10742                }
10743                for (PackageParser.Activity a : pkg.activities) {
10744                    a.info.encryptionAware = a.info.directBootAware = true;
10745                }
10746                for (PackageParser.Activity r : pkg.receivers) {
10747                    r.info.encryptionAware = r.info.directBootAware = true;
10748                }
10749            }
10750        } else {
10751            // Only allow system apps to be flagged as core apps.
10752            pkg.coreApp = false;
10753            // clear flags not applicable to regular apps
10754            pkg.applicationInfo.privateFlags &=
10755                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10756            pkg.applicationInfo.privateFlags &=
10757                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10758        }
10759        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10760
10761        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10762            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10763        }
10764
10765        if (!isSystemApp(pkg)) {
10766            // Only system apps can use these features.
10767            pkg.mOriginalPackages = null;
10768            pkg.mRealPackage = null;
10769            pkg.mAdoptPermissions = null;
10770        }
10771    }
10772
10773    /**
10774     * Asserts the parsed package is valid according to the given policy. If the
10775     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10776     * <p>
10777     * Implementation detail: This method must NOT have any side effects. It would
10778     * ideally be static, but, it requires locks to read system state.
10779     *
10780     * @throws PackageManagerException If the package fails any of the validation checks
10781     */
10782    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10783            throws PackageManagerException {
10784        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10785            assertCodePolicy(pkg);
10786        }
10787
10788        if (pkg.applicationInfo.getCodePath() == null ||
10789                pkg.applicationInfo.getResourcePath() == null) {
10790            // Bail out. The resource and code paths haven't been set.
10791            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10792                    "Code and resource paths haven't been set correctly");
10793        }
10794
10795        // Make sure we're not adding any bogus keyset info
10796        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10797        ksms.assertScannedPackageValid(pkg);
10798
10799        synchronized (mPackages) {
10800            // The special "android" package can only be defined once
10801            if (pkg.packageName.equals("android")) {
10802                if (mAndroidApplication != null) {
10803                    Slog.w(TAG, "*************************************************");
10804                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10805                    Slog.w(TAG, " codePath=" + pkg.codePath);
10806                    Slog.w(TAG, "*************************************************");
10807                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10808                            "Core android package being redefined.  Skipping.");
10809                }
10810            }
10811
10812            // A package name must be unique; don't allow duplicates
10813            if (mPackages.containsKey(pkg.packageName)) {
10814                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10815                        "Application package " + pkg.packageName
10816                        + " already installed.  Skipping duplicate.");
10817            }
10818
10819            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10820                // Static libs have a synthetic package name containing the version
10821                // but we still want the base name to be unique.
10822                if (mPackages.containsKey(pkg.manifestPackageName)) {
10823                    throw new PackageManagerException(
10824                            "Duplicate static shared lib provider package");
10825                }
10826
10827                // Static shared libraries should have at least O target SDK
10828                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10829                    throw new PackageManagerException(
10830                            "Packages declaring static-shared libs must target O SDK or higher");
10831                }
10832
10833                // Package declaring static a shared lib cannot be instant apps
10834                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10835                    throw new PackageManagerException(
10836                            "Packages declaring static-shared libs cannot be instant apps");
10837                }
10838
10839                // Package declaring static a shared lib cannot be renamed since the package
10840                // name is synthetic and apps can't code around package manager internals.
10841                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10842                    throw new PackageManagerException(
10843                            "Packages declaring static-shared libs cannot be renamed");
10844                }
10845
10846                // Package declaring static a shared lib cannot declare child packages
10847                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10848                    throw new PackageManagerException(
10849                            "Packages declaring static-shared libs cannot have child packages");
10850                }
10851
10852                // Package declaring static a shared lib cannot declare dynamic libs
10853                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10854                    throw new PackageManagerException(
10855                            "Packages declaring static-shared libs cannot declare dynamic libs");
10856                }
10857
10858                // Package declaring static a shared lib cannot declare shared users
10859                if (pkg.mSharedUserId != null) {
10860                    throw new PackageManagerException(
10861                            "Packages declaring static-shared libs cannot declare shared users");
10862                }
10863
10864                // Static shared libs cannot declare activities
10865                if (!pkg.activities.isEmpty()) {
10866                    throw new PackageManagerException(
10867                            "Static shared libs cannot declare activities");
10868                }
10869
10870                // Static shared libs cannot declare services
10871                if (!pkg.services.isEmpty()) {
10872                    throw new PackageManagerException(
10873                            "Static shared libs cannot declare services");
10874                }
10875
10876                // Static shared libs cannot declare providers
10877                if (!pkg.providers.isEmpty()) {
10878                    throw new PackageManagerException(
10879                            "Static shared libs cannot declare content providers");
10880                }
10881
10882                // Static shared libs cannot declare receivers
10883                if (!pkg.receivers.isEmpty()) {
10884                    throw new PackageManagerException(
10885                            "Static shared libs cannot declare broadcast receivers");
10886                }
10887
10888                // Static shared libs cannot declare permission groups
10889                if (!pkg.permissionGroups.isEmpty()) {
10890                    throw new PackageManagerException(
10891                            "Static shared libs cannot declare permission groups");
10892                }
10893
10894                // Static shared libs cannot declare permissions
10895                if (!pkg.permissions.isEmpty()) {
10896                    throw new PackageManagerException(
10897                            "Static shared libs cannot declare permissions");
10898                }
10899
10900                // Static shared libs cannot declare protected broadcasts
10901                if (pkg.protectedBroadcasts != null) {
10902                    throw new PackageManagerException(
10903                            "Static shared libs cannot declare protected broadcasts");
10904                }
10905
10906                // Static shared libs cannot be overlay targets
10907                if (pkg.mOverlayTarget != null) {
10908                    throw new PackageManagerException(
10909                            "Static shared libs cannot be overlay targets");
10910                }
10911
10912                // The version codes must be ordered as lib versions
10913                int minVersionCode = Integer.MIN_VALUE;
10914                int maxVersionCode = Integer.MAX_VALUE;
10915
10916                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10917                        pkg.staticSharedLibName);
10918                if (versionedLib != null) {
10919                    final int versionCount = versionedLib.size();
10920                    for (int i = 0; i < versionCount; i++) {
10921                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10922                        final int libVersionCode = libInfo.getDeclaringPackage()
10923                                .getVersionCode();
10924                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10925                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10926                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10927                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10928                        } else {
10929                            minVersionCode = maxVersionCode = libVersionCode;
10930                            break;
10931                        }
10932                    }
10933                }
10934                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10935                    throw new PackageManagerException("Static shared"
10936                            + " lib version codes must be ordered as lib versions");
10937                }
10938            }
10939
10940            // Only privileged apps and updated privileged apps can add child packages.
10941            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10942                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10943                    throw new PackageManagerException("Only privileged apps can add child "
10944                            + "packages. Ignoring package " + pkg.packageName);
10945                }
10946                final int childCount = pkg.childPackages.size();
10947                for (int i = 0; i < childCount; i++) {
10948                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10949                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10950                            childPkg.packageName)) {
10951                        throw new PackageManagerException("Can't override child of "
10952                                + "another disabled app. Ignoring package " + pkg.packageName);
10953                    }
10954                }
10955            }
10956
10957            // If we're only installing presumed-existing packages, require that the
10958            // scanned APK is both already known and at the path previously established
10959            // for it.  Previously unknown packages we pick up normally, but if we have an
10960            // a priori expectation about this package's install presence, enforce it.
10961            // With a singular exception for new system packages. When an OTA contains
10962            // a new system package, we allow the codepath to change from a system location
10963            // to the user-installed location. If we don't allow this change, any newer,
10964            // user-installed version of the application will be ignored.
10965            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10966                if (mExpectingBetter.containsKey(pkg.packageName)) {
10967                    logCriticalInfo(Log.WARN,
10968                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10969                } else {
10970                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10971                    if (known != null) {
10972                        if (DEBUG_PACKAGE_SCANNING) {
10973                            Log.d(TAG, "Examining " + pkg.codePath
10974                                    + " and requiring known paths " + known.codePathString
10975                                    + " & " + known.resourcePathString);
10976                        }
10977                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10978                                || !pkg.applicationInfo.getResourcePath().equals(
10979                                        known.resourcePathString)) {
10980                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10981                                    "Application package " + pkg.packageName
10982                                    + " found at " + pkg.applicationInfo.getCodePath()
10983                                    + " but expected at " + known.codePathString
10984                                    + "; ignoring.");
10985                        }
10986                    }
10987                }
10988            }
10989
10990            // Verify that this new package doesn't have any content providers
10991            // that conflict with existing packages.  Only do this if the
10992            // package isn't already installed, since we don't want to break
10993            // things that are installed.
10994            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10995                final int N = pkg.providers.size();
10996                int i;
10997                for (i=0; i<N; i++) {
10998                    PackageParser.Provider p = pkg.providers.get(i);
10999                    if (p.info.authority != null) {
11000                        String names[] = p.info.authority.split(";");
11001                        for (int j = 0; j < names.length; j++) {
11002                            if (mProvidersByAuthority.containsKey(names[j])) {
11003                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11004                                final String otherPackageName =
11005                                        ((other != null && other.getComponentName() != null) ?
11006                                                other.getComponentName().getPackageName() : "?");
11007                                throw new PackageManagerException(
11008                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11009                                        "Can't install because provider name " + names[j]
11010                                                + " (in package " + pkg.applicationInfo.packageName
11011                                                + ") is already used by " + otherPackageName);
11012                            }
11013                        }
11014                    }
11015                }
11016            }
11017        }
11018    }
11019
11020    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11021            int type, String declaringPackageName, int declaringVersionCode) {
11022        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11023        if (versionedLib == null) {
11024            versionedLib = new SparseArray<>();
11025            mSharedLibraries.put(name, versionedLib);
11026            if (type == SharedLibraryInfo.TYPE_STATIC) {
11027                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11028            }
11029        } else if (versionedLib.indexOfKey(version) >= 0) {
11030            return false;
11031        }
11032        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11033                version, type, declaringPackageName, declaringVersionCode);
11034        versionedLib.put(version, libEntry);
11035        return true;
11036    }
11037
11038    private boolean removeSharedLibraryLPw(String name, int version) {
11039        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11040        if (versionedLib == null) {
11041            return false;
11042        }
11043        final int libIdx = versionedLib.indexOfKey(version);
11044        if (libIdx < 0) {
11045            return false;
11046        }
11047        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11048        versionedLib.remove(version);
11049        if (versionedLib.size() <= 0) {
11050            mSharedLibraries.remove(name);
11051            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11052                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11053                        .getPackageName());
11054            }
11055        }
11056        return true;
11057    }
11058
11059    /**
11060     * Adds a scanned package to the system. When this method is finished, the package will
11061     * be available for query, resolution, etc...
11062     */
11063    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11064            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11065        final String pkgName = pkg.packageName;
11066        if (mCustomResolverComponentName != null &&
11067                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11068            setUpCustomResolverActivity(pkg);
11069        }
11070
11071        if (pkg.packageName.equals("android")) {
11072            synchronized (mPackages) {
11073                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11074                    // Set up information for our fall-back user intent resolution activity.
11075                    mPlatformPackage = pkg;
11076                    pkg.mVersionCode = mSdkVersion;
11077                    mAndroidApplication = pkg.applicationInfo;
11078                    if (!mResolverReplaced) {
11079                        mResolveActivity.applicationInfo = mAndroidApplication;
11080                        mResolveActivity.name = ResolverActivity.class.getName();
11081                        mResolveActivity.packageName = mAndroidApplication.packageName;
11082                        mResolveActivity.processName = "system:ui";
11083                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11084                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11085                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11086                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11087                        mResolveActivity.exported = true;
11088                        mResolveActivity.enabled = true;
11089                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11090                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11091                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11092                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11093                                | ActivityInfo.CONFIG_ORIENTATION
11094                                | ActivityInfo.CONFIG_KEYBOARD
11095                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11096                        mResolveInfo.activityInfo = mResolveActivity;
11097                        mResolveInfo.priority = 0;
11098                        mResolveInfo.preferredOrder = 0;
11099                        mResolveInfo.match = 0;
11100                        mResolveComponentName = new ComponentName(
11101                                mAndroidApplication.packageName, mResolveActivity.name);
11102                    }
11103                }
11104            }
11105        }
11106
11107        ArrayList<PackageParser.Package> clientLibPkgs = null;
11108        // writer
11109        synchronized (mPackages) {
11110            boolean hasStaticSharedLibs = false;
11111
11112            // Any app can add new static shared libraries
11113            if (pkg.staticSharedLibName != null) {
11114                // Static shared libs don't allow renaming as they have synthetic package
11115                // names to allow install of multiple versions, so use name from manifest.
11116                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11117                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11118                        pkg.manifestPackageName, pkg.mVersionCode)) {
11119                    hasStaticSharedLibs = true;
11120                } else {
11121                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11122                                + pkg.staticSharedLibName + " already exists; skipping");
11123                }
11124                // Static shared libs cannot be updated once installed since they
11125                // use synthetic package name which includes the version code, so
11126                // not need to update other packages's shared lib dependencies.
11127            }
11128
11129            if (!hasStaticSharedLibs
11130                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11131                // Only system apps can add new dynamic shared libraries.
11132                if (pkg.libraryNames != null) {
11133                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11134                        String name = pkg.libraryNames.get(i);
11135                        boolean allowed = false;
11136                        if (pkg.isUpdatedSystemApp()) {
11137                            // New library entries can only be added through the
11138                            // system image.  This is important to get rid of a lot
11139                            // of nasty edge cases: for example if we allowed a non-
11140                            // system update of the app to add a library, then uninstalling
11141                            // the update would make the library go away, and assumptions
11142                            // we made such as through app install filtering would now
11143                            // have allowed apps on the device which aren't compatible
11144                            // with it.  Better to just have the restriction here, be
11145                            // conservative, and create many fewer cases that can negatively
11146                            // impact the user experience.
11147                            final PackageSetting sysPs = mSettings
11148                                    .getDisabledSystemPkgLPr(pkg.packageName);
11149                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11150                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11151                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11152                                        allowed = true;
11153                                        break;
11154                                    }
11155                                }
11156                            }
11157                        } else {
11158                            allowed = true;
11159                        }
11160                        if (allowed) {
11161                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11162                                    SharedLibraryInfo.VERSION_UNDEFINED,
11163                                    SharedLibraryInfo.TYPE_DYNAMIC,
11164                                    pkg.packageName, pkg.mVersionCode)) {
11165                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11166                                        + name + " already exists; skipping");
11167                            }
11168                        } else {
11169                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11170                                    + name + " that is not declared on system image; skipping");
11171                        }
11172                    }
11173
11174                    if ((scanFlags & SCAN_BOOTING) == 0) {
11175                        // If we are not booting, we need to update any applications
11176                        // that are clients of our shared library.  If we are booting,
11177                        // this will all be done once the scan is complete.
11178                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11179                    }
11180                }
11181            }
11182        }
11183
11184        if ((scanFlags & SCAN_BOOTING) != 0) {
11185            // No apps can run during boot scan, so they don't need to be frozen
11186        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11187            // Caller asked to not kill app, so it's probably not frozen
11188        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11189            // Caller asked us to ignore frozen check for some reason; they
11190            // probably didn't know the package name
11191        } else {
11192            // We're doing major surgery on this package, so it better be frozen
11193            // right now to keep it from launching
11194            checkPackageFrozen(pkgName);
11195        }
11196
11197        // Also need to kill any apps that are dependent on the library.
11198        if (clientLibPkgs != null) {
11199            for (int i=0; i<clientLibPkgs.size(); i++) {
11200                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11201                killApplication(clientPkg.applicationInfo.packageName,
11202                        clientPkg.applicationInfo.uid, "update lib");
11203            }
11204        }
11205
11206        // writer
11207        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11208
11209        synchronized (mPackages) {
11210            // We don't expect installation to fail beyond this point
11211
11212            // Add the new setting to mSettings
11213            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11214            // Add the new setting to mPackages
11215            mPackages.put(pkg.applicationInfo.packageName, pkg);
11216            // Make sure we don't accidentally delete its data.
11217            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11218            while (iter.hasNext()) {
11219                PackageCleanItem item = iter.next();
11220                if (pkgName.equals(item.packageName)) {
11221                    iter.remove();
11222                }
11223            }
11224
11225            // Add the package's KeySets to the global KeySetManagerService
11226            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11227            ksms.addScannedPackageLPw(pkg);
11228
11229            int N = pkg.providers.size();
11230            StringBuilder r = null;
11231            int i;
11232            for (i=0; i<N; i++) {
11233                PackageParser.Provider p = pkg.providers.get(i);
11234                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11235                        p.info.processName);
11236                mProviders.addProvider(p);
11237                p.syncable = p.info.isSyncable;
11238                if (p.info.authority != null) {
11239                    String names[] = p.info.authority.split(";");
11240                    p.info.authority = null;
11241                    for (int j = 0; j < names.length; j++) {
11242                        if (j == 1 && p.syncable) {
11243                            // We only want the first authority for a provider to possibly be
11244                            // syncable, so if we already added this provider using a different
11245                            // authority clear the syncable flag. We copy the provider before
11246                            // changing it because the mProviders object contains a reference
11247                            // to a provider that we don't want to change.
11248                            // Only do this for the second authority since the resulting provider
11249                            // object can be the same for all future authorities for this provider.
11250                            p = new PackageParser.Provider(p);
11251                            p.syncable = false;
11252                        }
11253                        if (!mProvidersByAuthority.containsKey(names[j])) {
11254                            mProvidersByAuthority.put(names[j], p);
11255                            if (p.info.authority == null) {
11256                                p.info.authority = names[j];
11257                            } else {
11258                                p.info.authority = p.info.authority + ";" + names[j];
11259                            }
11260                            if (DEBUG_PACKAGE_SCANNING) {
11261                                if (chatty)
11262                                    Log.d(TAG, "Registered content provider: " + names[j]
11263                                            + ", className = " + p.info.name + ", isSyncable = "
11264                                            + p.info.isSyncable);
11265                            }
11266                        } else {
11267                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11268                            Slog.w(TAG, "Skipping provider name " + names[j] +
11269                                    " (in package " + pkg.applicationInfo.packageName +
11270                                    "): name already used by "
11271                                    + ((other != null && other.getComponentName() != null)
11272                                            ? other.getComponentName().getPackageName() : "?"));
11273                        }
11274                    }
11275                }
11276                if (chatty) {
11277                    if (r == null) {
11278                        r = new StringBuilder(256);
11279                    } else {
11280                        r.append(' ');
11281                    }
11282                    r.append(p.info.name);
11283                }
11284            }
11285            if (r != null) {
11286                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11287            }
11288
11289            N = pkg.services.size();
11290            r = null;
11291            for (i=0; i<N; i++) {
11292                PackageParser.Service s = pkg.services.get(i);
11293                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11294                        s.info.processName);
11295                mServices.addService(s);
11296                if (chatty) {
11297                    if (r == null) {
11298                        r = new StringBuilder(256);
11299                    } else {
11300                        r.append(' ');
11301                    }
11302                    r.append(s.info.name);
11303                }
11304            }
11305            if (r != null) {
11306                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11307            }
11308
11309            N = pkg.receivers.size();
11310            r = null;
11311            for (i=0; i<N; i++) {
11312                PackageParser.Activity a = pkg.receivers.get(i);
11313                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11314                        a.info.processName);
11315                mReceivers.addActivity(a, "receiver");
11316                if (chatty) {
11317                    if (r == null) {
11318                        r = new StringBuilder(256);
11319                    } else {
11320                        r.append(' ');
11321                    }
11322                    r.append(a.info.name);
11323                }
11324            }
11325            if (r != null) {
11326                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11327            }
11328
11329            N = pkg.activities.size();
11330            r = null;
11331            for (i=0; i<N; i++) {
11332                PackageParser.Activity a = pkg.activities.get(i);
11333                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11334                        a.info.processName);
11335                mActivities.addActivity(a, "activity");
11336                if (chatty) {
11337                    if (r == null) {
11338                        r = new StringBuilder(256);
11339                    } else {
11340                        r.append(' ');
11341                    }
11342                    r.append(a.info.name);
11343                }
11344            }
11345            if (r != null) {
11346                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11347            }
11348
11349            N = pkg.permissionGroups.size();
11350            r = null;
11351            for (i=0; i<N; i++) {
11352                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11353                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11354                final String curPackageName = cur == null ? null : cur.info.packageName;
11355                // Dont allow ephemeral apps to define new permission groups.
11356                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11357                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11358                            + pg.info.packageName
11359                            + " ignored: instant apps cannot define new permission groups.");
11360                    continue;
11361                }
11362                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11363                if (cur == null || isPackageUpdate) {
11364                    mPermissionGroups.put(pg.info.name, pg);
11365                    if (chatty) {
11366                        if (r == null) {
11367                            r = new StringBuilder(256);
11368                        } else {
11369                            r.append(' ');
11370                        }
11371                        if (isPackageUpdate) {
11372                            r.append("UPD:");
11373                        }
11374                        r.append(pg.info.name);
11375                    }
11376                } else {
11377                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11378                            + pg.info.packageName + " ignored: original from "
11379                            + cur.info.packageName);
11380                    if (chatty) {
11381                        if (r == null) {
11382                            r = new StringBuilder(256);
11383                        } else {
11384                            r.append(' ');
11385                        }
11386                        r.append("DUP:");
11387                        r.append(pg.info.name);
11388                    }
11389                }
11390            }
11391            if (r != null) {
11392                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11393            }
11394
11395            N = pkg.permissions.size();
11396            r = null;
11397            for (i=0; i<N; i++) {
11398                PackageParser.Permission p = pkg.permissions.get(i);
11399
11400                // Dont allow ephemeral apps to define new permissions.
11401                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11402                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11403                            + p.info.packageName
11404                            + " ignored: instant apps cannot define new permissions.");
11405                    continue;
11406                }
11407
11408                // Assume by default that we did not install this permission into the system.
11409                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11410
11411                // Now that permission groups have a special meaning, we ignore permission
11412                // groups for legacy apps to prevent unexpected behavior. In particular,
11413                // permissions for one app being granted to someone just because they happen
11414                // to be in a group defined by another app (before this had no implications).
11415                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11416                    p.group = mPermissionGroups.get(p.info.group);
11417                    // Warn for a permission in an unknown group.
11418                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11419                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11420                                + p.info.packageName + " in an unknown group " + p.info.group);
11421                    }
11422                }
11423
11424                ArrayMap<String, BasePermission> permissionMap =
11425                        p.tree ? mSettings.mPermissionTrees
11426                                : mSettings.mPermissions;
11427                BasePermission bp = permissionMap.get(p.info.name);
11428
11429                // Allow system apps to redefine non-system permissions
11430                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11431                    final boolean currentOwnerIsSystem = (bp.perm != null
11432                            && isSystemApp(bp.perm.owner));
11433                    if (isSystemApp(p.owner)) {
11434                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11435                            // It's a built-in permission and no owner, take ownership now
11436                            bp.packageSetting = pkgSetting;
11437                            bp.perm = p;
11438                            bp.uid = pkg.applicationInfo.uid;
11439                            bp.sourcePackage = p.info.packageName;
11440                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11441                        } else if (!currentOwnerIsSystem) {
11442                            String msg = "New decl " + p.owner + " of permission  "
11443                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11444                            reportSettingsProblem(Log.WARN, msg);
11445                            bp = null;
11446                        }
11447                    }
11448                }
11449
11450                if (bp == null) {
11451                    bp = new BasePermission(p.info.name, p.info.packageName,
11452                            BasePermission.TYPE_NORMAL);
11453                    permissionMap.put(p.info.name, bp);
11454                }
11455
11456                if (bp.perm == null) {
11457                    if (bp.sourcePackage == null
11458                            || bp.sourcePackage.equals(p.info.packageName)) {
11459                        BasePermission tree = findPermissionTreeLP(p.info.name);
11460                        if (tree == null
11461                                || tree.sourcePackage.equals(p.info.packageName)) {
11462                            bp.packageSetting = pkgSetting;
11463                            bp.perm = p;
11464                            bp.uid = pkg.applicationInfo.uid;
11465                            bp.sourcePackage = p.info.packageName;
11466                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11467                            if (chatty) {
11468                                if (r == null) {
11469                                    r = new StringBuilder(256);
11470                                } else {
11471                                    r.append(' ');
11472                                }
11473                                r.append(p.info.name);
11474                            }
11475                        } else {
11476                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11477                                    + p.info.packageName + " ignored: base tree "
11478                                    + tree.name + " is from package "
11479                                    + tree.sourcePackage);
11480                        }
11481                    } else {
11482                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11483                                + p.info.packageName + " ignored: original from "
11484                                + bp.sourcePackage);
11485                    }
11486                } else if (chatty) {
11487                    if (r == null) {
11488                        r = new StringBuilder(256);
11489                    } else {
11490                        r.append(' ');
11491                    }
11492                    r.append("DUP:");
11493                    r.append(p.info.name);
11494                }
11495                if (bp.perm == p) {
11496                    bp.protectionLevel = p.info.protectionLevel;
11497                }
11498            }
11499
11500            if (r != null) {
11501                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11502            }
11503
11504            N = pkg.instrumentation.size();
11505            r = null;
11506            for (i=0; i<N; i++) {
11507                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11508                a.info.packageName = pkg.applicationInfo.packageName;
11509                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11510                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11511                a.info.splitNames = pkg.splitNames;
11512                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11513                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11514                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11515                a.info.dataDir = pkg.applicationInfo.dataDir;
11516                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11517                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11518                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11519                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11520                mInstrumentation.put(a.getComponentName(), a);
11521                if (chatty) {
11522                    if (r == null) {
11523                        r = new StringBuilder(256);
11524                    } else {
11525                        r.append(' ');
11526                    }
11527                    r.append(a.info.name);
11528                }
11529            }
11530            if (r != null) {
11531                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11532            }
11533
11534            if (pkg.protectedBroadcasts != null) {
11535                N = pkg.protectedBroadcasts.size();
11536                for (i=0; i<N; i++) {
11537                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11538                }
11539            }
11540        }
11541
11542        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11543    }
11544
11545    /**
11546     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11547     * is derived purely on the basis of the contents of {@code scanFile} and
11548     * {@code cpuAbiOverride}.
11549     *
11550     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11551     */
11552    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11553                                 String cpuAbiOverride, boolean extractLibs,
11554                                 File appLib32InstallDir)
11555            throws PackageManagerException {
11556        // Give ourselves some initial paths; we'll come back for another
11557        // pass once we've determined ABI below.
11558        setNativeLibraryPaths(pkg, appLib32InstallDir);
11559
11560        // We would never need to extract libs for forward-locked and external packages,
11561        // since the container service will do it for us. We shouldn't attempt to
11562        // extract libs from system app when it was not updated.
11563        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11564                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11565            extractLibs = false;
11566        }
11567
11568        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11569        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11570
11571        NativeLibraryHelper.Handle handle = null;
11572        try {
11573            handle = NativeLibraryHelper.Handle.create(pkg);
11574            // TODO(multiArch): This can be null for apps that didn't go through the
11575            // usual installation process. We can calculate it again, like we
11576            // do during install time.
11577            //
11578            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11579            // unnecessary.
11580            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11581
11582            // Null out the abis so that they can be recalculated.
11583            pkg.applicationInfo.primaryCpuAbi = null;
11584            pkg.applicationInfo.secondaryCpuAbi = null;
11585            if (isMultiArch(pkg.applicationInfo)) {
11586                // Warn if we've set an abiOverride for multi-lib packages..
11587                // By definition, we need to copy both 32 and 64 bit libraries for
11588                // such packages.
11589                if (pkg.cpuAbiOverride != null
11590                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11591                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11592                }
11593
11594                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11595                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11596                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11597                    if (extractLibs) {
11598                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11599                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11600                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11601                                useIsaSpecificSubdirs);
11602                    } else {
11603                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11604                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11605                    }
11606                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11607                }
11608
11609                // Shared library native code should be in the APK zip aligned
11610                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11611                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11612                            "Shared library native lib extraction not supported");
11613                }
11614
11615                maybeThrowExceptionForMultiArchCopy(
11616                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11617
11618                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11619                    if (extractLibs) {
11620                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11621                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11622                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11623                                useIsaSpecificSubdirs);
11624                    } else {
11625                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11626                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11627                    }
11628                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11629                }
11630
11631                maybeThrowExceptionForMultiArchCopy(
11632                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11633
11634                if (abi64 >= 0) {
11635                    // Shared library native libs should be in the APK zip aligned
11636                    if (extractLibs && pkg.isLibrary()) {
11637                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11638                                "Shared library native lib extraction not supported");
11639                    }
11640                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11641                }
11642
11643                if (abi32 >= 0) {
11644                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11645                    if (abi64 >= 0) {
11646                        if (pkg.use32bitAbi) {
11647                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11648                            pkg.applicationInfo.primaryCpuAbi = abi;
11649                        } else {
11650                            pkg.applicationInfo.secondaryCpuAbi = abi;
11651                        }
11652                    } else {
11653                        pkg.applicationInfo.primaryCpuAbi = abi;
11654                    }
11655                }
11656            } else {
11657                String[] abiList = (cpuAbiOverride != null) ?
11658                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11659
11660                // Enable gross and lame hacks for apps that are built with old
11661                // SDK tools. We must scan their APKs for renderscript bitcode and
11662                // not launch them if it's present. Don't bother checking on devices
11663                // that don't have 64 bit support.
11664                boolean needsRenderScriptOverride = false;
11665                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11666                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11667                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11668                    needsRenderScriptOverride = true;
11669                }
11670
11671                final int copyRet;
11672                if (extractLibs) {
11673                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11674                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11675                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11676                } else {
11677                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11678                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11679                }
11680                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11681
11682                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11683                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11684                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11685                }
11686
11687                if (copyRet >= 0) {
11688                    // Shared libraries that have native libs must be multi-architecture
11689                    if (pkg.isLibrary()) {
11690                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11691                                "Shared library with native libs must be multiarch");
11692                    }
11693                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11694                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11695                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11696                } else if (needsRenderScriptOverride) {
11697                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11698                }
11699            }
11700        } catch (IOException ioe) {
11701            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11702        } finally {
11703            IoUtils.closeQuietly(handle);
11704        }
11705
11706        // Now that we've calculated the ABIs and determined if it's an internal app,
11707        // we will go ahead and populate the nativeLibraryPath.
11708        setNativeLibraryPaths(pkg, appLib32InstallDir);
11709    }
11710
11711    /**
11712     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11713     * i.e, so that all packages can be run inside a single process if required.
11714     *
11715     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11716     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11717     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11718     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11719     * updating a package that belongs to a shared user.
11720     *
11721     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11722     * adds unnecessary complexity.
11723     */
11724    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11725            PackageParser.Package scannedPackage) {
11726        String requiredInstructionSet = null;
11727        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11728            requiredInstructionSet = VMRuntime.getInstructionSet(
11729                     scannedPackage.applicationInfo.primaryCpuAbi);
11730        }
11731
11732        PackageSetting requirer = null;
11733        for (PackageSetting ps : packagesForUser) {
11734            // If packagesForUser contains scannedPackage, we skip it. This will happen
11735            // when scannedPackage is an update of an existing package. Without this check,
11736            // we will never be able to change the ABI of any package belonging to a shared
11737            // user, even if it's compatible with other packages.
11738            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11739                if (ps.primaryCpuAbiString == null) {
11740                    continue;
11741                }
11742
11743                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11744                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11745                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11746                    // this but there's not much we can do.
11747                    String errorMessage = "Instruction set mismatch, "
11748                            + ((requirer == null) ? "[caller]" : requirer)
11749                            + " requires " + requiredInstructionSet + " whereas " + ps
11750                            + " requires " + instructionSet;
11751                    Slog.w(TAG, errorMessage);
11752                }
11753
11754                if (requiredInstructionSet == null) {
11755                    requiredInstructionSet = instructionSet;
11756                    requirer = ps;
11757                }
11758            }
11759        }
11760
11761        if (requiredInstructionSet != null) {
11762            String adjustedAbi;
11763            if (requirer != null) {
11764                // requirer != null implies that either scannedPackage was null or that scannedPackage
11765                // did not require an ABI, in which case we have to adjust scannedPackage to match
11766                // the ABI of the set (which is the same as requirer's ABI)
11767                adjustedAbi = requirer.primaryCpuAbiString;
11768                if (scannedPackage != null) {
11769                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11770                }
11771            } else {
11772                // requirer == null implies that we're updating all ABIs in the set to
11773                // match scannedPackage.
11774                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11775            }
11776
11777            for (PackageSetting ps : packagesForUser) {
11778                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11779                    if (ps.primaryCpuAbiString != null) {
11780                        continue;
11781                    }
11782
11783                    ps.primaryCpuAbiString = adjustedAbi;
11784                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11785                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11786                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11787                        if (DEBUG_ABI_SELECTION) {
11788                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11789                                    + " (requirer="
11790                                    + (requirer != null ? requirer.pkg : "null")
11791                                    + ", scannedPackage="
11792                                    + (scannedPackage != null ? scannedPackage : "null")
11793                                    + ")");
11794                        }
11795                        try {
11796                            mInstaller.rmdex(ps.codePathString,
11797                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11798                        } catch (InstallerException ignored) {
11799                        }
11800                    }
11801                }
11802            }
11803        }
11804    }
11805
11806    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11807        synchronized (mPackages) {
11808            mResolverReplaced = true;
11809            // Set up information for custom user intent resolution activity.
11810            mResolveActivity.applicationInfo = pkg.applicationInfo;
11811            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11812            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11813            mResolveActivity.processName = pkg.applicationInfo.packageName;
11814            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11815            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11816                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11817            mResolveActivity.theme = 0;
11818            mResolveActivity.exported = true;
11819            mResolveActivity.enabled = true;
11820            mResolveInfo.activityInfo = mResolveActivity;
11821            mResolveInfo.priority = 0;
11822            mResolveInfo.preferredOrder = 0;
11823            mResolveInfo.match = 0;
11824            mResolveComponentName = mCustomResolverComponentName;
11825            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11826                    mResolveComponentName);
11827        }
11828    }
11829
11830    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11831        if (installerActivity == null) {
11832            if (DEBUG_EPHEMERAL) {
11833                Slog.d(TAG, "Clear ephemeral installer activity");
11834            }
11835            mInstantAppInstallerActivity = null;
11836            return;
11837        }
11838
11839        if (DEBUG_EPHEMERAL) {
11840            Slog.d(TAG, "Set ephemeral installer activity: "
11841                    + installerActivity.getComponentName());
11842        }
11843        // Set up information for ephemeral installer activity
11844        mInstantAppInstallerActivity = installerActivity;
11845        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11846                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11847        mInstantAppInstallerActivity.exported = true;
11848        mInstantAppInstallerActivity.enabled = true;
11849        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11850        mInstantAppInstallerInfo.priority = 0;
11851        mInstantAppInstallerInfo.preferredOrder = 1;
11852        mInstantAppInstallerInfo.isDefault = true;
11853        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11854                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11855    }
11856
11857    private static String calculateBundledApkRoot(final String codePathString) {
11858        final File codePath = new File(codePathString);
11859        final File codeRoot;
11860        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11861            codeRoot = Environment.getRootDirectory();
11862        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11863            codeRoot = Environment.getOemDirectory();
11864        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11865            codeRoot = Environment.getVendorDirectory();
11866        } else {
11867            // Unrecognized code path; take its top real segment as the apk root:
11868            // e.g. /something/app/blah.apk => /something
11869            try {
11870                File f = codePath.getCanonicalFile();
11871                File parent = f.getParentFile();    // non-null because codePath is a file
11872                File tmp;
11873                while ((tmp = parent.getParentFile()) != null) {
11874                    f = parent;
11875                    parent = tmp;
11876                }
11877                codeRoot = f;
11878                Slog.w(TAG, "Unrecognized code path "
11879                        + codePath + " - using " + codeRoot);
11880            } catch (IOException e) {
11881                // Can't canonicalize the code path -- shenanigans?
11882                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11883                return Environment.getRootDirectory().getPath();
11884            }
11885        }
11886        return codeRoot.getPath();
11887    }
11888
11889    /**
11890     * Derive and set the location of native libraries for the given package,
11891     * which varies depending on where and how the package was installed.
11892     */
11893    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11894        final ApplicationInfo info = pkg.applicationInfo;
11895        final String codePath = pkg.codePath;
11896        final File codeFile = new File(codePath);
11897        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11898        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11899
11900        info.nativeLibraryRootDir = null;
11901        info.nativeLibraryRootRequiresIsa = false;
11902        info.nativeLibraryDir = null;
11903        info.secondaryNativeLibraryDir = null;
11904
11905        if (isApkFile(codeFile)) {
11906            // Monolithic install
11907            if (bundledApp) {
11908                // If "/system/lib64/apkname" exists, assume that is the per-package
11909                // native library directory to use; otherwise use "/system/lib/apkname".
11910                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11911                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11912                        getPrimaryInstructionSet(info));
11913
11914                // This is a bundled system app so choose the path based on the ABI.
11915                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11916                // is just the default path.
11917                final String apkName = deriveCodePathName(codePath);
11918                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11919                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11920                        apkName).getAbsolutePath();
11921
11922                if (info.secondaryCpuAbi != null) {
11923                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11924                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11925                            secondaryLibDir, apkName).getAbsolutePath();
11926                }
11927            } else if (asecApp) {
11928                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11929                        .getAbsolutePath();
11930            } else {
11931                final String apkName = deriveCodePathName(codePath);
11932                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11933                        .getAbsolutePath();
11934            }
11935
11936            info.nativeLibraryRootRequiresIsa = false;
11937            info.nativeLibraryDir = info.nativeLibraryRootDir;
11938        } else {
11939            // Cluster install
11940            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11941            info.nativeLibraryRootRequiresIsa = true;
11942
11943            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11944                    getPrimaryInstructionSet(info)).getAbsolutePath();
11945
11946            if (info.secondaryCpuAbi != null) {
11947                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11948                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11949            }
11950        }
11951    }
11952
11953    /**
11954     * Calculate the abis and roots for a bundled app. These can uniquely
11955     * be determined from the contents of the system partition, i.e whether
11956     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11957     * of this information, and instead assume that the system was built
11958     * sensibly.
11959     */
11960    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11961                                           PackageSetting pkgSetting) {
11962        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11963
11964        // If "/system/lib64/apkname" exists, assume that is the per-package
11965        // native library directory to use; otherwise use "/system/lib/apkname".
11966        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11967        setBundledAppAbi(pkg, apkRoot, apkName);
11968        // pkgSetting might be null during rescan following uninstall of updates
11969        // to a bundled app, so accommodate that possibility.  The settings in
11970        // that case will be established later from the parsed package.
11971        //
11972        // If the settings aren't null, sync them up with what we've just derived.
11973        // note that apkRoot isn't stored in the package settings.
11974        if (pkgSetting != null) {
11975            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11976            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11977        }
11978    }
11979
11980    /**
11981     * Deduces the ABI of a bundled app and sets the relevant fields on the
11982     * parsed pkg object.
11983     *
11984     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11985     *        under which system libraries are installed.
11986     * @param apkName the name of the installed package.
11987     */
11988    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11989        final File codeFile = new File(pkg.codePath);
11990
11991        final boolean has64BitLibs;
11992        final boolean has32BitLibs;
11993        if (isApkFile(codeFile)) {
11994            // Monolithic install
11995            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11996            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11997        } else {
11998            // Cluster install
11999            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12000            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12001                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12002                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12003                has64BitLibs = (new File(rootDir, isa)).exists();
12004            } else {
12005                has64BitLibs = false;
12006            }
12007            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12008                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12009                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12010                has32BitLibs = (new File(rootDir, isa)).exists();
12011            } else {
12012                has32BitLibs = false;
12013            }
12014        }
12015
12016        if (has64BitLibs && !has32BitLibs) {
12017            // The package has 64 bit libs, but not 32 bit libs. Its primary
12018            // ABI should be 64 bit. We can safely assume here that the bundled
12019            // native libraries correspond to the most preferred ABI in the list.
12020
12021            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12022            pkg.applicationInfo.secondaryCpuAbi = null;
12023        } else if (has32BitLibs && !has64BitLibs) {
12024            // The package has 32 bit libs but not 64 bit libs. Its primary
12025            // ABI should be 32 bit.
12026
12027            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12028            pkg.applicationInfo.secondaryCpuAbi = null;
12029        } else if (has32BitLibs && has64BitLibs) {
12030            // The application has both 64 and 32 bit bundled libraries. We check
12031            // here that the app declares multiArch support, and warn if it doesn't.
12032            //
12033            // We will be lenient here and record both ABIs. The primary will be the
12034            // ABI that's higher on the list, i.e, a device that's configured to prefer
12035            // 64 bit apps will see a 64 bit primary ABI,
12036
12037            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12038                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12039            }
12040
12041            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12042                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12043                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12044            } else {
12045                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12046                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12047            }
12048        } else {
12049            pkg.applicationInfo.primaryCpuAbi = null;
12050            pkg.applicationInfo.secondaryCpuAbi = null;
12051        }
12052    }
12053
12054    private void killApplication(String pkgName, int appId, String reason) {
12055        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12056    }
12057
12058    private void killApplication(String pkgName, int appId, int userId, String reason) {
12059        // Request the ActivityManager to kill the process(only for existing packages)
12060        // so that we do not end up in a confused state while the user is still using the older
12061        // version of the application while the new one gets installed.
12062        final long token = Binder.clearCallingIdentity();
12063        try {
12064            IActivityManager am = ActivityManager.getService();
12065            if (am != null) {
12066                try {
12067                    am.killApplication(pkgName, appId, userId, reason);
12068                } catch (RemoteException e) {
12069                }
12070            }
12071        } finally {
12072            Binder.restoreCallingIdentity(token);
12073        }
12074    }
12075
12076    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12077        // Remove the parent package setting
12078        PackageSetting ps = (PackageSetting) pkg.mExtras;
12079        if (ps != null) {
12080            removePackageLI(ps, chatty);
12081        }
12082        // Remove the child package setting
12083        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12084        for (int i = 0; i < childCount; i++) {
12085            PackageParser.Package childPkg = pkg.childPackages.get(i);
12086            ps = (PackageSetting) childPkg.mExtras;
12087            if (ps != null) {
12088                removePackageLI(ps, chatty);
12089            }
12090        }
12091    }
12092
12093    void removePackageLI(PackageSetting ps, boolean chatty) {
12094        if (DEBUG_INSTALL) {
12095            if (chatty)
12096                Log.d(TAG, "Removing package " + ps.name);
12097        }
12098
12099        // writer
12100        synchronized (mPackages) {
12101            mPackages.remove(ps.name);
12102            final PackageParser.Package pkg = ps.pkg;
12103            if (pkg != null) {
12104                cleanPackageDataStructuresLILPw(pkg, chatty);
12105            }
12106        }
12107    }
12108
12109    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12110        if (DEBUG_INSTALL) {
12111            if (chatty)
12112                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12113        }
12114
12115        // writer
12116        synchronized (mPackages) {
12117            // Remove the parent package
12118            mPackages.remove(pkg.applicationInfo.packageName);
12119            cleanPackageDataStructuresLILPw(pkg, chatty);
12120
12121            // Remove the child packages
12122            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12123            for (int i = 0; i < childCount; i++) {
12124                PackageParser.Package childPkg = pkg.childPackages.get(i);
12125                mPackages.remove(childPkg.applicationInfo.packageName);
12126                cleanPackageDataStructuresLILPw(childPkg, chatty);
12127            }
12128        }
12129    }
12130
12131    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12132        int N = pkg.providers.size();
12133        StringBuilder r = null;
12134        int i;
12135        for (i=0; i<N; i++) {
12136            PackageParser.Provider p = pkg.providers.get(i);
12137            mProviders.removeProvider(p);
12138            if (p.info.authority == null) {
12139
12140                /* There was another ContentProvider with this authority when
12141                 * this app was installed so this authority is null,
12142                 * Ignore it as we don't have to unregister the provider.
12143                 */
12144                continue;
12145            }
12146            String names[] = p.info.authority.split(";");
12147            for (int j = 0; j < names.length; j++) {
12148                if (mProvidersByAuthority.get(names[j]) == p) {
12149                    mProvidersByAuthority.remove(names[j]);
12150                    if (DEBUG_REMOVE) {
12151                        if (chatty)
12152                            Log.d(TAG, "Unregistered content provider: " + names[j]
12153                                    + ", className = " + p.info.name + ", isSyncable = "
12154                                    + p.info.isSyncable);
12155                    }
12156                }
12157            }
12158            if (DEBUG_REMOVE && chatty) {
12159                if (r == null) {
12160                    r = new StringBuilder(256);
12161                } else {
12162                    r.append(' ');
12163                }
12164                r.append(p.info.name);
12165            }
12166        }
12167        if (r != null) {
12168            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12169        }
12170
12171        N = pkg.services.size();
12172        r = null;
12173        for (i=0; i<N; i++) {
12174            PackageParser.Service s = pkg.services.get(i);
12175            mServices.removeService(s);
12176            if (chatty) {
12177                if (r == null) {
12178                    r = new StringBuilder(256);
12179                } else {
12180                    r.append(' ');
12181                }
12182                r.append(s.info.name);
12183            }
12184        }
12185        if (r != null) {
12186            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12187        }
12188
12189        N = pkg.receivers.size();
12190        r = null;
12191        for (i=0; i<N; i++) {
12192            PackageParser.Activity a = pkg.receivers.get(i);
12193            mReceivers.removeActivity(a, "receiver");
12194            if (DEBUG_REMOVE && chatty) {
12195                if (r == null) {
12196                    r = new StringBuilder(256);
12197                } else {
12198                    r.append(' ');
12199                }
12200                r.append(a.info.name);
12201            }
12202        }
12203        if (r != null) {
12204            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12205        }
12206
12207        N = pkg.activities.size();
12208        r = null;
12209        for (i=0; i<N; i++) {
12210            PackageParser.Activity a = pkg.activities.get(i);
12211            mActivities.removeActivity(a, "activity");
12212            if (DEBUG_REMOVE && chatty) {
12213                if (r == null) {
12214                    r = new StringBuilder(256);
12215                } else {
12216                    r.append(' ');
12217                }
12218                r.append(a.info.name);
12219            }
12220        }
12221        if (r != null) {
12222            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12223        }
12224
12225        N = pkg.permissions.size();
12226        r = null;
12227        for (i=0; i<N; i++) {
12228            PackageParser.Permission p = pkg.permissions.get(i);
12229            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12230            if (bp == null) {
12231                bp = mSettings.mPermissionTrees.get(p.info.name);
12232            }
12233            if (bp != null && bp.perm == p) {
12234                bp.perm = null;
12235                if (DEBUG_REMOVE && chatty) {
12236                    if (r == null) {
12237                        r = new StringBuilder(256);
12238                    } else {
12239                        r.append(' ');
12240                    }
12241                    r.append(p.info.name);
12242                }
12243            }
12244            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12245                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12246                if (appOpPkgs != null) {
12247                    appOpPkgs.remove(pkg.packageName);
12248                }
12249            }
12250        }
12251        if (r != null) {
12252            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12253        }
12254
12255        N = pkg.requestedPermissions.size();
12256        r = null;
12257        for (i=0; i<N; i++) {
12258            String perm = pkg.requestedPermissions.get(i);
12259            BasePermission bp = mSettings.mPermissions.get(perm);
12260            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12261                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12262                if (appOpPkgs != null) {
12263                    appOpPkgs.remove(pkg.packageName);
12264                    if (appOpPkgs.isEmpty()) {
12265                        mAppOpPermissionPackages.remove(perm);
12266                    }
12267                }
12268            }
12269        }
12270        if (r != null) {
12271            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12272        }
12273
12274        N = pkg.instrumentation.size();
12275        r = null;
12276        for (i=0; i<N; i++) {
12277            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12278            mInstrumentation.remove(a.getComponentName());
12279            if (DEBUG_REMOVE && chatty) {
12280                if (r == null) {
12281                    r = new StringBuilder(256);
12282                } else {
12283                    r.append(' ');
12284                }
12285                r.append(a.info.name);
12286            }
12287        }
12288        if (r != null) {
12289            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12290        }
12291
12292        r = null;
12293        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12294            // Only system apps can hold shared libraries.
12295            if (pkg.libraryNames != null) {
12296                for (i = 0; i < pkg.libraryNames.size(); i++) {
12297                    String name = pkg.libraryNames.get(i);
12298                    if (removeSharedLibraryLPw(name, 0)) {
12299                        if (DEBUG_REMOVE && chatty) {
12300                            if (r == null) {
12301                                r = new StringBuilder(256);
12302                            } else {
12303                                r.append(' ');
12304                            }
12305                            r.append(name);
12306                        }
12307                    }
12308                }
12309            }
12310        }
12311
12312        r = null;
12313
12314        // Any package can hold static shared libraries.
12315        if (pkg.staticSharedLibName != null) {
12316            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12317                if (DEBUG_REMOVE && chatty) {
12318                    if (r == null) {
12319                        r = new StringBuilder(256);
12320                    } else {
12321                        r.append(' ');
12322                    }
12323                    r.append(pkg.staticSharedLibName);
12324                }
12325            }
12326        }
12327
12328        if (r != null) {
12329            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12330        }
12331    }
12332
12333    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12334        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12335            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12336                return true;
12337            }
12338        }
12339        return false;
12340    }
12341
12342    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12343    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12344    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12345
12346    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12347        // Update the parent permissions
12348        updatePermissionsLPw(pkg.packageName, pkg, flags);
12349        // Update the child permissions
12350        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12351        for (int i = 0; i < childCount; i++) {
12352            PackageParser.Package childPkg = pkg.childPackages.get(i);
12353            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12354        }
12355    }
12356
12357    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12358            int flags) {
12359        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12360        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12361    }
12362
12363    private void updatePermissionsLPw(String changingPkg,
12364            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12365        // Make sure there are no dangling permission trees.
12366        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12367        while (it.hasNext()) {
12368            final BasePermission bp = it.next();
12369            if (bp.packageSetting == null) {
12370                // We may not yet have parsed the package, so just see if
12371                // we still know about its settings.
12372                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12373            }
12374            if (bp.packageSetting == null) {
12375                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12376                        + " from package " + bp.sourcePackage);
12377                it.remove();
12378            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12379                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12380                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12381                            + " from package " + bp.sourcePackage);
12382                    flags |= UPDATE_PERMISSIONS_ALL;
12383                    it.remove();
12384                }
12385            }
12386        }
12387
12388        // Make sure all dynamic permissions have been assigned to a package,
12389        // and make sure there are no dangling permissions.
12390        it = mSettings.mPermissions.values().iterator();
12391        while (it.hasNext()) {
12392            final BasePermission bp = it.next();
12393            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12394                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12395                        + bp.name + " pkg=" + bp.sourcePackage
12396                        + " info=" + bp.pendingInfo);
12397                if (bp.packageSetting == null && bp.pendingInfo != null) {
12398                    final BasePermission tree = findPermissionTreeLP(bp.name);
12399                    if (tree != null && tree.perm != null) {
12400                        bp.packageSetting = tree.packageSetting;
12401                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12402                                new PermissionInfo(bp.pendingInfo));
12403                        bp.perm.info.packageName = tree.perm.info.packageName;
12404                        bp.perm.info.name = bp.name;
12405                        bp.uid = tree.uid;
12406                    }
12407                }
12408            }
12409            if (bp.packageSetting == null) {
12410                // We may not yet have parsed the package, so just see if
12411                // we still know about its settings.
12412                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12413            }
12414            if (bp.packageSetting == null) {
12415                Slog.w(TAG, "Removing dangling permission: " + bp.name
12416                        + " from package " + bp.sourcePackage);
12417                it.remove();
12418            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12419                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12420                    Slog.i(TAG, "Removing old permission: " + bp.name
12421                            + " from package " + bp.sourcePackage);
12422                    flags |= UPDATE_PERMISSIONS_ALL;
12423                    it.remove();
12424                }
12425            }
12426        }
12427
12428        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12429        // Now update the permissions for all packages, in particular
12430        // replace the granted permissions of the system packages.
12431        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12432            for (PackageParser.Package pkg : mPackages.values()) {
12433                if (pkg != pkgInfo) {
12434                    // Only replace for packages on requested volume
12435                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12436                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12437                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12438                    grantPermissionsLPw(pkg, replace, changingPkg);
12439                }
12440            }
12441        }
12442
12443        if (pkgInfo != null) {
12444            // Only replace for packages on requested volume
12445            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12446            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12447                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12448            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12449        }
12450        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12451    }
12452
12453    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12454            String packageOfInterest) {
12455        // IMPORTANT: There are two types of permissions: install and runtime.
12456        // Install time permissions are granted when the app is installed to
12457        // all device users and users added in the future. Runtime permissions
12458        // are granted at runtime explicitly to specific users. Normal and signature
12459        // protected permissions are install time permissions. Dangerous permissions
12460        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12461        // otherwise they are runtime permissions. This function does not manage
12462        // runtime permissions except for the case an app targeting Lollipop MR1
12463        // being upgraded to target a newer SDK, in which case dangerous permissions
12464        // are transformed from install time to runtime ones.
12465
12466        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12467        if (ps == null) {
12468            return;
12469        }
12470
12471        PermissionsState permissionsState = ps.getPermissionsState();
12472        PermissionsState origPermissions = permissionsState;
12473
12474        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12475
12476        boolean runtimePermissionsRevoked = false;
12477        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12478
12479        boolean changedInstallPermission = false;
12480
12481        if (replace) {
12482            ps.installPermissionsFixed = false;
12483            if (!ps.isSharedUser()) {
12484                origPermissions = new PermissionsState(permissionsState);
12485                permissionsState.reset();
12486            } else {
12487                // We need to know only about runtime permission changes since the
12488                // calling code always writes the install permissions state but
12489                // the runtime ones are written only if changed. The only cases of
12490                // changed runtime permissions here are promotion of an install to
12491                // runtime and revocation of a runtime from a shared user.
12492                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12493                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12494                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12495                    runtimePermissionsRevoked = true;
12496                }
12497            }
12498        }
12499
12500        permissionsState.setGlobalGids(mGlobalGids);
12501
12502        final int N = pkg.requestedPermissions.size();
12503        for (int i=0; i<N; i++) {
12504            final String name = pkg.requestedPermissions.get(i);
12505            final BasePermission bp = mSettings.mPermissions.get(name);
12506            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12507                    >= Build.VERSION_CODES.M;
12508
12509            if (DEBUG_INSTALL) {
12510                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12511            }
12512
12513            if (bp == null || bp.packageSetting == null) {
12514                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12515                    if (DEBUG_PERMISSIONS) {
12516                        Slog.i(TAG, "Unknown permission " + name
12517                                + " in package " + pkg.packageName);
12518                    }
12519                }
12520                continue;
12521            }
12522
12523
12524            // Limit ephemeral apps to ephemeral allowed permissions.
12525            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12526                if (DEBUG_PERMISSIONS) {
12527                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12528                            + pkg.packageName);
12529                }
12530                continue;
12531            }
12532
12533            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12534                if (DEBUG_PERMISSIONS) {
12535                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12536                            + pkg.packageName);
12537                }
12538                continue;
12539            }
12540
12541            final String perm = bp.name;
12542            boolean allowedSig = false;
12543            int grant = GRANT_DENIED;
12544
12545            // Keep track of app op permissions.
12546            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12547                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12548                if (pkgs == null) {
12549                    pkgs = new ArraySet<>();
12550                    mAppOpPermissionPackages.put(bp.name, pkgs);
12551                }
12552                pkgs.add(pkg.packageName);
12553            }
12554
12555            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12556            switch (level) {
12557                case PermissionInfo.PROTECTION_NORMAL: {
12558                    // For all apps normal permissions are install time ones.
12559                    grant = GRANT_INSTALL;
12560                } break;
12561
12562                case PermissionInfo.PROTECTION_DANGEROUS: {
12563                    // If a permission review is required for legacy apps we represent
12564                    // their permissions as always granted runtime ones since we need
12565                    // to keep the review required permission flag per user while an
12566                    // install permission's state is shared across all users.
12567                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12568                        // For legacy apps dangerous permissions are install time ones.
12569                        grant = GRANT_INSTALL;
12570                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12571                        // For legacy apps that became modern, install becomes runtime.
12572                        grant = GRANT_UPGRADE;
12573                    } else if (mPromoteSystemApps
12574                            && isSystemApp(ps)
12575                            && mExistingSystemPackages.contains(ps.name)) {
12576                        // For legacy system apps, install becomes runtime.
12577                        // We cannot check hasInstallPermission() for system apps since those
12578                        // permissions were granted implicitly and not persisted pre-M.
12579                        grant = GRANT_UPGRADE;
12580                    } else {
12581                        // For modern apps keep runtime permissions unchanged.
12582                        grant = GRANT_RUNTIME;
12583                    }
12584                } break;
12585
12586                case PermissionInfo.PROTECTION_SIGNATURE: {
12587                    // For all apps signature permissions are install time ones.
12588                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12589                    if (allowedSig) {
12590                        grant = GRANT_INSTALL;
12591                    }
12592                } break;
12593            }
12594
12595            if (DEBUG_PERMISSIONS) {
12596                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12597            }
12598
12599            if (grant != GRANT_DENIED) {
12600                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12601                    // If this is an existing, non-system package, then
12602                    // we can't add any new permissions to it.
12603                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12604                        // Except...  if this is a permission that was added
12605                        // to the platform (note: need to only do this when
12606                        // updating the platform).
12607                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12608                            grant = GRANT_DENIED;
12609                        }
12610                    }
12611                }
12612
12613                switch (grant) {
12614                    case GRANT_INSTALL: {
12615                        // Revoke this as runtime permission to handle the case of
12616                        // a runtime permission being downgraded to an install one.
12617                        // Also in permission review mode we keep dangerous permissions
12618                        // for legacy apps
12619                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12620                            if (origPermissions.getRuntimePermissionState(
12621                                    bp.name, userId) != null) {
12622                                // Revoke the runtime permission and clear the flags.
12623                                origPermissions.revokeRuntimePermission(bp, userId);
12624                                origPermissions.updatePermissionFlags(bp, userId,
12625                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12626                                // If we revoked a permission permission, we have to write.
12627                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12628                                        changedRuntimePermissionUserIds, userId);
12629                            }
12630                        }
12631                        // Grant an install permission.
12632                        if (permissionsState.grantInstallPermission(bp) !=
12633                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12634                            changedInstallPermission = true;
12635                        }
12636                    } break;
12637
12638                    case GRANT_RUNTIME: {
12639                        // Grant previously granted runtime permissions.
12640                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12641                            PermissionState permissionState = origPermissions
12642                                    .getRuntimePermissionState(bp.name, userId);
12643                            int flags = permissionState != null
12644                                    ? permissionState.getFlags() : 0;
12645                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12646                                // Don't propagate the permission in a permission review mode if
12647                                // the former was revoked, i.e. marked to not propagate on upgrade.
12648                                // Note that in a permission review mode install permissions are
12649                                // represented as constantly granted runtime ones since we need to
12650                                // keep a per user state associated with the permission. Also the
12651                                // revoke on upgrade flag is no longer applicable and is reset.
12652                                final boolean revokeOnUpgrade = (flags & PackageManager
12653                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12654                                if (revokeOnUpgrade) {
12655                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12656                                    // Since we changed the flags, we have to write.
12657                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12658                                            changedRuntimePermissionUserIds, userId);
12659                                }
12660                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12661                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12662                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12663                                        // If we cannot put the permission as it was,
12664                                        // we have to write.
12665                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12666                                                changedRuntimePermissionUserIds, userId);
12667                                    }
12668                                }
12669
12670                                // If the app supports runtime permissions no need for a review.
12671                                if (mPermissionReviewRequired
12672                                        && appSupportsRuntimePermissions
12673                                        && (flags & PackageManager
12674                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12675                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12676                                    // Since we changed the flags, we have to write.
12677                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12678                                            changedRuntimePermissionUserIds, userId);
12679                                }
12680                            } else if (mPermissionReviewRequired
12681                                    && !appSupportsRuntimePermissions) {
12682                                // For legacy apps that need a permission review, every new
12683                                // runtime permission is granted but it is pending a review.
12684                                // We also need to review only platform defined runtime
12685                                // permissions as these are the only ones the platform knows
12686                                // how to disable the API to simulate revocation as legacy
12687                                // apps don't expect to run with revoked permissions.
12688                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12689                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12690                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12691                                        // We changed the flags, hence have to write.
12692                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12693                                                changedRuntimePermissionUserIds, userId);
12694                                    }
12695                                }
12696                                if (permissionsState.grantRuntimePermission(bp, userId)
12697                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12698                                    // We changed the permission, hence have to write.
12699                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12700                                            changedRuntimePermissionUserIds, userId);
12701                                }
12702                            }
12703                            // Propagate the permission flags.
12704                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12705                        }
12706                    } break;
12707
12708                    case GRANT_UPGRADE: {
12709                        // Grant runtime permissions for a previously held install permission.
12710                        PermissionState permissionState = origPermissions
12711                                .getInstallPermissionState(bp.name);
12712                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12713
12714                        if (origPermissions.revokeInstallPermission(bp)
12715                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12716                            // We will be transferring the permission flags, so clear them.
12717                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12718                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12719                            changedInstallPermission = true;
12720                        }
12721
12722                        // If the permission is not to be promoted to runtime we ignore it and
12723                        // also its other flags as they are not applicable to install permissions.
12724                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12725                            for (int userId : currentUserIds) {
12726                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12727                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12728                                    // Transfer the permission flags.
12729                                    permissionsState.updatePermissionFlags(bp, userId,
12730                                            flags, flags);
12731                                    // If we granted the permission, we have to write.
12732                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12733                                            changedRuntimePermissionUserIds, userId);
12734                                }
12735                            }
12736                        }
12737                    } break;
12738
12739                    default: {
12740                        if (packageOfInterest == null
12741                                || packageOfInterest.equals(pkg.packageName)) {
12742                            if (DEBUG_PERMISSIONS) {
12743                                Slog.i(TAG, "Not granting permission " + perm
12744                                        + " to package " + pkg.packageName
12745                                        + " because it was previously installed without");
12746                            }
12747                        }
12748                    } break;
12749                }
12750            } else {
12751                if (permissionsState.revokeInstallPermission(bp) !=
12752                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12753                    // Also drop the permission flags.
12754                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12755                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12756                    changedInstallPermission = true;
12757                    Slog.i(TAG, "Un-granting permission " + perm
12758                            + " from package " + pkg.packageName
12759                            + " (protectionLevel=" + bp.protectionLevel
12760                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12761                            + ")");
12762                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12763                    // Don't print warning for app op permissions, since it is fine for them
12764                    // not to be granted, there is a UI for the user to decide.
12765                    if (DEBUG_PERMISSIONS
12766                            && (packageOfInterest == null
12767                                    || packageOfInterest.equals(pkg.packageName))) {
12768                        Slog.i(TAG, "Not granting permission " + perm
12769                                + " to package " + pkg.packageName
12770                                + " (protectionLevel=" + bp.protectionLevel
12771                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12772                                + ")");
12773                    }
12774                }
12775            }
12776        }
12777
12778        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12779                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12780            // This is the first that we have heard about this package, so the
12781            // permissions we have now selected are fixed until explicitly
12782            // changed.
12783            ps.installPermissionsFixed = true;
12784        }
12785
12786        // Persist the runtime permissions state for users with changes. If permissions
12787        // were revoked because no app in the shared user declares them we have to
12788        // write synchronously to avoid losing runtime permissions state.
12789        for (int userId : changedRuntimePermissionUserIds) {
12790            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12791        }
12792    }
12793
12794    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12795        boolean allowed = false;
12796        final int NP = PackageParser.NEW_PERMISSIONS.length;
12797        for (int ip=0; ip<NP; ip++) {
12798            final PackageParser.NewPermissionInfo npi
12799                    = PackageParser.NEW_PERMISSIONS[ip];
12800            if (npi.name.equals(perm)
12801                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12802                allowed = true;
12803                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12804                        + pkg.packageName);
12805                break;
12806            }
12807        }
12808        return allowed;
12809    }
12810
12811    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12812            BasePermission bp, PermissionsState origPermissions) {
12813        boolean privilegedPermission = (bp.protectionLevel
12814                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12815        boolean privappPermissionsDisable =
12816                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12817        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12818        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12819        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12820                && !platformPackage && platformPermission) {
12821            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12822                    .getPrivAppPermissions(pkg.packageName);
12823            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12824            if (!whitelisted) {
12825                Slog.w(TAG, "Privileged permission " + perm + " for package "
12826                        + pkg.packageName + " - not in privapp-permissions whitelist");
12827                // Only report violations for apps on system image
12828                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12829                    if (mPrivappPermissionsViolations == null) {
12830                        mPrivappPermissionsViolations = new ArraySet<>();
12831                    }
12832                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12833                }
12834                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12835                    return false;
12836                }
12837            }
12838        }
12839        boolean allowed = (compareSignatures(
12840                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12841                        == PackageManager.SIGNATURE_MATCH)
12842                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12843                        == PackageManager.SIGNATURE_MATCH);
12844        if (!allowed && privilegedPermission) {
12845            if (isSystemApp(pkg)) {
12846                // For updated system applications, a system permission
12847                // is granted only if it had been defined by the original application.
12848                if (pkg.isUpdatedSystemApp()) {
12849                    final PackageSetting sysPs = mSettings
12850                            .getDisabledSystemPkgLPr(pkg.packageName);
12851                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12852                        // If the original was granted this permission, we take
12853                        // that grant decision as read and propagate it to the
12854                        // update.
12855                        if (sysPs.isPrivileged()) {
12856                            allowed = true;
12857                        }
12858                    } else {
12859                        // The system apk may have been updated with an older
12860                        // version of the one on the data partition, but which
12861                        // granted a new system permission that it didn't have
12862                        // before.  In this case we do want to allow the app to
12863                        // now get the new permission if the ancestral apk is
12864                        // privileged to get it.
12865                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12866                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12867                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12868                                    allowed = true;
12869                                    break;
12870                                }
12871                            }
12872                        }
12873                        // Also if a privileged parent package on the system image or any of
12874                        // its children requested a privileged permission, the updated child
12875                        // packages can also get the permission.
12876                        if (pkg.parentPackage != null) {
12877                            final PackageSetting disabledSysParentPs = mSettings
12878                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12879                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12880                                    && disabledSysParentPs.isPrivileged()) {
12881                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12882                                    allowed = true;
12883                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12884                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12885                                    for (int i = 0; i < count; i++) {
12886                                        PackageParser.Package disabledSysChildPkg =
12887                                                disabledSysParentPs.pkg.childPackages.get(i);
12888                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12889                                                perm)) {
12890                                            allowed = true;
12891                                            break;
12892                                        }
12893                                    }
12894                                }
12895                            }
12896                        }
12897                    }
12898                } else {
12899                    allowed = isPrivilegedApp(pkg);
12900                }
12901            }
12902        }
12903        if (!allowed) {
12904            if (!allowed && (bp.protectionLevel
12905                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12906                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12907                // If this was a previously normal/dangerous permission that got moved
12908                // to a system permission as part of the runtime permission redesign, then
12909                // we still want to blindly grant it to old apps.
12910                allowed = true;
12911            }
12912            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12913                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12914                // If this permission is to be granted to the system installer and
12915                // this app is an installer, then it gets the permission.
12916                allowed = true;
12917            }
12918            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12919                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12920                // If this permission is to be granted to the system verifier and
12921                // this app is a verifier, then it gets the permission.
12922                allowed = true;
12923            }
12924            if (!allowed && (bp.protectionLevel
12925                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12926                    && isSystemApp(pkg)) {
12927                // Any pre-installed system app is allowed to get this permission.
12928                allowed = true;
12929            }
12930            if (!allowed && (bp.protectionLevel
12931                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12932                // For development permissions, a development permission
12933                // is granted only if it was already granted.
12934                allowed = origPermissions.hasInstallPermission(perm);
12935            }
12936            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12937                    && pkg.packageName.equals(mSetupWizardPackage)) {
12938                // If this permission is to be granted to the system setup wizard and
12939                // this app is a setup wizard, then it gets the permission.
12940                allowed = true;
12941            }
12942        }
12943        return allowed;
12944    }
12945
12946    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12947        final int permCount = pkg.requestedPermissions.size();
12948        for (int j = 0; j < permCount; j++) {
12949            String requestedPermission = pkg.requestedPermissions.get(j);
12950            if (permission.equals(requestedPermission)) {
12951                return true;
12952            }
12953        }
12954        return false;
12955    }
12956
12957    final class ActivityIntentResolver
12958            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12959        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12960                boolean defaultOnly, int userId) {
12961            if (!sUserManager.exists(userId)) return null;
12962            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12963            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12964        }
12965
12966        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12967                int userId) {
12968            if (!sUserManager.exists(userId)) return null;
12969            mFlags = flags;
12970            return super.queryIntent(intent, resolvedType,
12971                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12972                    userId);
12973        }
12974
12975        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12976                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12977            if (!sUserManager.exists(userId)) return null;
12978            if (packageActivities == null) {
12979                return null;
12980            }
12981            mFlags = flags;
12982            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12983            final int N = packageActivities.size();
12984            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12985                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12986
12987            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12988            for (int i = 0; i < N; ++i) {
12989                intentFilters = packageActivities.get(i).intents;
12990                if (intentFilters != null && intentFilters.size() > 0) {
12991                    PackageParser.ActivityIntentInfo[] array =
12992                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12993                    intentFilters.toArray(array);
12994                    listCut.add(array);
12995                }
12996            }
12997            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12998        }
12999
13000        /**
13001         * Finds a privileged activity that matches the specified activity names.
13002         */
13003        private PackageParser.Activity findMatchingActivity(
13004                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13005            for (PackageParser.Activity sysActivity : activityList) {
13006                if (sysActivity.info.name.equals(activityInfo.name)) {
13007                    return sysActivity;
13008                }
13009                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13010                    return sysActivity;
13011                }
13012                if (sysActivity.info.targetActivity != null) {
13013                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13014                        return sysActivity;
13015                    }
13016                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13017                        return sysActivity;
13018                    }
13019                }
13020            }
13021            return null;
13022        }
13023
13024        public class IterGenerator<E> {
13025            public Iterator<E> generate(ActivityIntentInfo info) {
13026                return null;
13027            }
13028        }
13029
13030        public class ActionIterGenerator extends IterGenerator<String> {
13031            @Override
13032            public Iterator<String> generate(ActivityIntentInfo info) {
13033                return info.actionsIterator();
13034            }
13035        }
13036
13037        public class CategoriesIterGenerator extends IterGenerator<String> {
13038            @Override
13039            public Iterator<String> generate(ActivityIntentInfo info) {
13040                return info.categoriesIterator();
13041            }
13042        }
13043
13044        public class SchemesIterGenerator extends IterGenerator<String> {
13045            @Override
13046            public Iterator<String> generate(ActivityIntentInfo info) {
13047                return info.schemesIterator();
13048            }
13049        }
13050
13051        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13052            @Override
13053            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13054                return info.authoritiesIterator();
13055            }
13056        }
13057
13058        /**
13059         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13060         * MODIFIED. Do not pass in a list that should not be changed.
13061         */
13062        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13063                IterGenerator<T> generator, Iterator<T> searchIterator) {
13064            // loop through the set of actions; every one must be found in the intent filter
13065            while (searchIterator.hasNext()) {
13066                // we must have at least one filter in the list to consider a match
13067                if (intentList.size() == 0) {
13068                    break;
13069                }
13070
13071                final T searchAction = searchIterator.next();
13072
13073                // loop through the set of intent filters
13074                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13075                while (intentIter.hasNext()) {
13076                    final ActivityIntentInfo intentInfo = intentIter.next();
13077                    boolean selectionFound = false;
13078
13079                    // loop through the intent filter's selection criteria; at least one
13080                    // of them must match the searched criteria
13081                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13082                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13083                        final T intentSelection = intentSelectionIter.next();
13084                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13085                            selectionFound = true;
13086                            break;
13087                        }
13088                    }
13089
13090                    // the selection criteria wasn't found in this filter's set; this filter
13091                    // is not a potential match
13092                    if (!selectionFound) {
13093                        intentIter.remove();
13094                    }
13095                }
13096            }
13097        }
13098
13099        private boolean isProtectedAction(ActivityIntentInfo filter) {
13100            final Iterator<String> actionsIter = filter.actionsIterator();
13101            while (actionsIter != null && actionsIter.hasNext()) {
13102                final String filterAction = actionsIter.next();
13103                if (PROTECTED_ACTIONS.contains(filterAction)) {
13104                    return true;
13105                }
13106            }
13107            return false;
13108        }
13109
13110        /**
13111         * Adjusts the priority of the given intent filter according to policy.
13112         * <p>
13113         * <ul>
13114         * <li>The priority for non privileged applications is capped to '0'</li>
13115         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13116         * <li>The priority for unbundled updates to privileged applications is capped to the
13117         *      priority defined on the system partition</li>
13118         * </ul>
13119         * <p>
13120         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13121         * allowed to obtain any priority on any action.
13122         */
13123        private void adjustPriority(
13124                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13125            // nothing to do; priority is fine as-is
13126            if (intent.getPriority() <= 0) {
13127                return;
13128            }
13129
13130            final ActivityInfo activityInfo = intent.activity.info;
13131            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13132
13133            final boolean privilegedApp =
13134                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13135            if (!privilegedApp) {
13136                // non-privileged applications can never define a priority >0
13137                if (DEBUG_FILTERS) {
13138                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13139                            + " package: " + applicationInfo.packageName
13140                            + " activity: " + intent.activity.className
13141                            + " origPrio: " + intent.getPriority());
13142                }
13143                intent.setPriority(0);
13144                return;
13145            }
13146
13147            if (systemActivities == null) {
13148                // the system package is not disabled; we're parsing the system partition
13149                if (isProtectedAction(intent)) {
13150                    if (mDeferProtectedFilters) {
13151                        // We can't deal with these just yet. No component should ever obtain a
13152                        // >0 priority for a protected actions, with ONE exception -- the setup
13153                        // wizard. The setup wizard, however, cannot be known until we're able to
13154                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13155                        // until all intent filters have been processed. Chicken, meet egg.
13156                        // Let the filter temporarily have a high priority and rectify the
13157                        // priorities after all system packages have been scanned.
13158                        mProtectedFilters.add(intent);
13159                        if (DEBUG_FILTERS) {
13160                            Slog.i(TAG, "Protected action; save for later;"
13161                                    + " package: " + applicationInfo.packageName
13162                                    + " activity: " + intent.activity.className
13163                                    + " origPrio: " + intent.getPriority());
13164                        }
13165                        return;
13166                    } else {
13167                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13168                            Slog.i(TAG, "No setup wizard;"
13169                                + " All protected intents capped to priority 0");
13170                        }
13171                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13172                            if (DEBUG_FILTERS) {
13173                                Slog.i(TAG, "Found setup wizard;"
13174                                    + " allow priority " + intent.getPriority() + ";"
13175                                    + " package: " + intent.activity.info.packageName
13176                                    + " activity: " + intent.activity.className
13177                                    + " priority: " + intent.getPriority());
13178                            }
13179                            // setup wizard gets whatever it wants
13180                            return;
13181                        }
13182                        if (DEBUG_FILTERS) {
13183                            Slog.i(TAG, "Protected action; cap priority to 0;"
13184                                    + " package: " + intent.activity.info.packageName
13185                                    + " activity: " + intent.activity.className
13186                                    + " origPrio: " + intent.getPriority());
13187                        }
13188                        intent.setPriority(0);
13189                        return;
13190                    }
13191                }
13192                // privileged apps on the system image get whatever priority they request
13193                return;
13194            }
13195
13196            // privileged app unbundled update ... try to find the same activity
13197            final PackageParser.Activity foundActivity =
13198                    findMatchingActivity(systemActivities, activityInfo);
13199            if (foundActivity == null) {
13200                // this is a new activity; it cannot obtain >0 priority
13201                if (DEBUG_FILTERS) {
13202                    Slog.i(TAG, "New activity; cap priority to 0;"
13203                            + " package: " + applicationInfo.packageName
13204                            + " activity: " + intent.activity.className
13205                            + " origPrio: " + intent.getPriority());
13206                }
13207                intent.setPriority(0);
13208                return;
13209            }
13210
13211            // found activity, now check for filter equivalence
13212
13213            // a shallow copy is enough; we modify the list, not its contents
13214            final List<ActivityIntentInfo> intentListCopy =
13215                    new ArrayList<>(foundActivity.intents);
13216            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13217
13218            // find matching action subsets
13219            final Iterator<String> actionsIterator = intent.actionsIterator();
13220            if (actionsIterator != null) {
13221                getIntentListSubset(
13222                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13223                if (intentListCopy.size() == 0) {
13224                    // no more intents to match; we're not equivalent
13225                    if (DEBUG_FILTERS) {
13226                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13227                                + " package: " + applicationInfo.packageName
13228                                + " activity: " + intent.activity.className
13229                                + " origPrio: " + intent.getPriority());
13230                    }
13231                    intent.setPriority(0);
13232                    return;
13233                }
13234            }
13235
13236            // find matching category subsets
13237            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13238            if (categoriesIterator != null) {
13239                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13240                        categoriesIterator);
13241                if (intentListCopy.size() == 0) {
13242                    // no more intents to match; we're not equivalent
13243                    if (DEBUG_FILTERS) {
13244                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13245                                + " package: " + applicationInfo.packageName
13246                                + " activity: " + intent.activity.className
13247                                + " origPrio: " + intent.getPriority());
13248                    }
13249                    intent.setPriority(0);
13250                    return;
13251                }
13252            }
13253
13254            // find matching schemes subsets
13255            final Iterator<String> schemesIterator = intent.schemesIterator();
13256            if (schemesIterator != null) {
13257                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13258                        schemesIterator);
13259                if (intentListCopy.size() == 0) {
13260                    // no more intents to match; we're not equivalent
13261                    if (DEBUG_FILTERS) {
13262                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13263                                + " package: " + applicationInfo.packageName
13264                                + " activity: " + intent.activity.className
13265                                + " origPrio: " + intent.getPriority());
13266                    }
13267                    intent.setPriority(0);
13268                    return;
13269                }
13270            }
13271
13272            // find matching authorities subsets
13273            final Iterator<IntentFilter.AuthorityEntry>
13274                    authoritiesIterator = intent.authoritiesIterator();
13275            if (authoritiesIterator != null) {
13276                getIntentListSubset(intentListCopy,
13277                        new AuthoritiesIterGenerator(),
13278                        authoritiesIterator);
13279                if (intentListCopy.size() == 0) {
13280                    // no more intents to match; we're not equivalent
13281                    if (DEBUG_FILTERS) {
13282                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13283                                + " package: " + applicationInfo.packageName
13284                                + " activity: " + intent.activity.className
13285                                + " origPrio: " + intent.getPriority());
13286                    }
13287                    intent.setPriority(0);
13288                    return;
13289                }
13290            }
13291
13292            // we found matching filter(s); app gets the max priority of all intents
13293            int cappedPriority = 0;
13294            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13295                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13296            }
13297            if (intent.getPriority() > cappedPriority) {
13298                if (DEBUG_FILTERS) {
13299                    Slog.i(TAG, "Found matching filter(s);"
13300                            + " cap priority to " + cappedPriority + ";"
13301                            + " package: " + applicationInfo.packageName
13302                            + " activity: " + intent.activity.className
13303                            + " origPrio: " + intent.getPriority());
13304                }
13305                intent.setPriority(cappedPriority);
13306                return;
13307            }
13308            // all this for nothing; the requested priority was <= what was on the system
13309        }
13310
13311        public final void addActivity(PackageParser.Activity a, String type) {
13312            mActivities.put(a.getComponentName(), a);
13313            if (DEBUG_SHOW_INFO)
13314                Log.v(
13315                TAG, "  " + type + " " +
13316                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13317            if (DEBUG_SHOW_INFO)
13318                Log.v(TAG, "    Class=" + a.info.name);
13319            final int NI = a.intents.size();
13320            for (int j=0; j<NI; j++) {
13321                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13322                if ("activity".equals(type)) {
13323                    final PackageSetting ps =
13324                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13325                    final List<PackageParser.Activity> systemActivities =
13326                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13327                    adjustPriority(systemActivities, intent);
13328                }
13329                if (DEBUG_SHOW_INFO) {
13330                    Log.v(TAG, "    IntentFilter:");
13331                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13332                }
13333                if (!intent.debugCheck()) {
13334                    Log.w(TAG, "==> For Activity " + a.info.name);
13335                }
13336                addFilter(intent);
13337            }
13338        }
13339
13340        public final void removeActivity(PackageParser.Activity a, String type) {
13341            mActivities.remove(a.getComponentName());
13342            if (DEBUG_SHOW_INFO) {
13343                Log.v(TAG, "  " + type + " "
13344                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13345                                : a.info.name) + ":");
13346                Log.v(TAG, "    Class=" + a.info.name);
13347            }
13348            final int NI = a.intents.size();
13349            for (int j=0; j<NI; j++) {
13350                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13351                if (DEBUG_SHOW_INFO) {
13352                    Log.v(TAG, "    IntentFilter:");
13353                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13354                }
13355                removeFilter(intent);
13356            }
13357        }
13358
13359        @Override
13360        protected boolean allowFilterResult(
13361                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13362            ActivityInfo filterAi = filter.activity.info;
13363            for (int i=dest.size()-1; i>=0; i--) {
13364                ActivityInfo destAi = dest.get(i).activityInfo;
13365                if (destAi.name == filterAi.name
13366                        && destAi.packageName == filterAi.packageName) {
13367                    return false;
13368                }
13369            }
13370            return true;
13371        }
13372
13373        @Override
13374        protected ActivityIntentInfo[] newArray(int size) {
13375            return new ActivityIntentInfo[size];
13376        }
13377
13378        @Override
13379        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13380            if (!sUserManager.exists(userId)) return true;
13381            PackageParser.Package p = filter.activity.owner;
13382            if (p != null) {
13383                PackageSetting ps = (PackageSetting)p.mExtras;
13384                if (ps != null) {
13385                    // System apps are never considered stopped for purposes of
13386                    // filtering, because there may be no way for the user to
13387                    // actually re-launch them.
13388                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13389                            && ps.getStopped(userId);
13390                }
13391            }
13392            return false;
13393        }
13394
13395        @Override
13396        protected boolean isPackageForFilter(String packageName,
13397                PackageParser.ActivityIntentInfo info) {
13398            return packageName.equals(info.activity.owner.packageName);
13399        }
13400
13401        @Override
13402        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13403                int match, int userId) {
13404            if (!sUserManager.exists(userId)) return null;
13405            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13406                return null;
13407            }
13408            final PackageParser.Activity activity = info.activity;
13409            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13410            if (ps == null) {
13411                return null;
13412            }
13413            final PackageUserState userState = ps.readUserState(userId);
13414            ActivityInfo ai =
13415                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13416            if (ai == null) {
13417                return null;
13418            }
13419            final boolean matchExplicitlyVisibleOnly =
13420                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13421            final boolean matchVisibleToInstantApp =
13422                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13423            final boolean componentVisible =
13424                    matchVisibleToInstantApp
13425                    && info.isVisibleToInstantApp()
13426                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13427            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13428            // throw out filters that aren't visible to ephemeral apps
13429            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13430                return null;
13431            }
13432            // throw out instant app filters if we're not explicitly requesting them
13433            if (!matchInstantApp && userState.instantApp) {
13434                return null;
13435            }
13436            // throw out instant app filters if updates are available; will trigger
13437            // instant app resolution
13438            if (userState.instantApp && ps.isUpdateAvailable()) {
13439                return null;
13440            }
13441            final ResolveInfo res = new ResolveInfo();
13442            res.activityInfo = ai;
13443            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13444                res.filter = info;
13445            }
13446            if (info != null) {
13447                res.handleAllWebDataURI = info.handleAllWebDataURI();
13448            }
13449            res.priority = info.getPriority();
13450            res.preferredOrder = activity.owner.mPreferredOrder;
13451            //System.out.println("Result: " + res.activityInfo.className +
13452            //                   " = " + res.priority);
13453            res.match = match;
13454            res.isDefault = info.hasDefault;
13455            res.labelRes = info.labelRes;
13456            res.nonLocalizedLabel = info.nonLocalizedLabel;
13457            if (userNeedsBadging(userId)) {
13458                res.noResourceId = true;
13459            } else {
13460                res.icon = info.icon;
13461            }
13462            res.iconResourceId = info.icon;
13463            res.system = res.activityInfo.applicationInfo.isSystemApp();
13464            res.isInstantAppAvailable = userState.instantApp;
13465            return res;
13466        }
13467
13468        @Override
13469        protected void sortResults(List<ResolveInfo> results) {
13470            Collections.sort(results, mResolvePrioritySorter);
13471        }
13472
13473        @Override
13474        protected void dumpFilter(PrintWriter out, String prefix,
13475                PackageParser.ActivityIntentInfo filter) {
13476            out.print(prefix); out.print(
13477                    Integer.toHexString(System.identityHashCode(filter.activity)));
13478                    out.print(' ');
13479                    filter.activity.printComponentShortName(out);
13480                    out.print(" filter ");
13481                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13482        }
13483
13484        @Override
13485        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13486            return filter.activity;
13487        }
13488
13489        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13490            PackageParser.Activity activity = (PackageParser.Activity)label;
13491            out.print(prefix); out.print(
13492                    Integer.toHexString(System.identityHashCode(activity)));
13493                    out.print(' ');
13494                    activity.printComponentShortName(out);
13495            if (count > 1) {
13496                out.print(" ("); out.print(count); out.print(" filters)");
13497            }
13498            out.println();
13499        }
13500
13501        // Keys are String (activity class name), values are Activity.
13502        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13503                = new ArrayMap<ComponentName, PackageParser.Activity>();
13504        private int mFlags;
13505    }
13506
13507    private final class ServiceIntentResolver
13508            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13509        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13510                boolean defaultOnly, int userId) {
13511            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13512            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13513        }
13514
13515        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13516                int userId) {
13517            if (!sUserManager.exists(userId)) return null;
13518            mFlags = flags;
13519            return super.queryIntent(intent, resolvedType,
13520                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13521                    userId);
13522        }
13523
13524        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13525                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13526            if (!sUserManager.exists(userId)) return null;
13527            if (packageServices == null) {
13528                return null;
13529            }
13530            mFlags = flags;
13531            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13532            final int N = packageServices.size();
13533            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13534                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13535
13536            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13537            for (int i = 0; i < N; ++i) {
13538                intentFilters = packageServices.get(i).intents;
13539                if (intentFilters != null && intentFilters.size() > 0) {
13540                    PackageParser.ServiceIntentInfo[] array =
13541                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13542                    intentFilters.toArray(array);
13543                    listCut.add(array);
13544                }
13545            }
13546            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13547        }
13548
13549        public final void addService(PackageParser.Service s) {
13550            mServices.put(s.getComponentName(), s);
13551            if (DEBUG_SHOW_INFO) {
13552                Log.v(TAG, "  "
13553                        + (s.info.nonLocalizedLabel != null
13554                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13555                Log.v(TAG, "    Class=" + s.info.name);
13556            }
13557            final int NI = s.intents.size();
13558            int j;
13559            for (j=0; j<NI; j++) {
13560                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13561                if (DEBUG_SHOW_INFO) {
13562                    Log.v(TAG, "    IntentFilter:");
13563                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13564                }
13565                if (!intent.debugCheck()) {
13566                    Log.w(TAG, "==> For Service " + s.info.name);
13567                }
13568                addFilter(intent);
13569            }
13570        }
13571
13572        public final void removeService(PackageParser.Service s) {
13573            mServices.remove(s.getComponentName());
13574            if (DEBUG_SHOW_INFO) {
13575                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13576                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13577                Log.v(TAG, "    Class=" + s.info.name);
13578            }
13579            final int NI = s.intents.size();
13580            int j;
13581            for (j=0; j<NI; j++) {
13582                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13583                if (DEBUG_SHOW_INFO) {
13584                    Log.v(TAG, "    IntentFilter:");
13585                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13586                }
13587                removeFilter(intent);
13588            }
13589        }
13590
13591        @Override
13592        protected boolean allowFilterResult(
13593                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13594            ServiceInfo filterSi = filter.service.info;
13595            for (int i=dest.size()-1; i>=0; i--) {
13596                ServiceInfo destAi = dest.get(i).serviceInfo;
13597                if (destAi.name == filterSi.name
13598                        && destAi.packageName == filterSi.packageName) {
13599                    return false;
13600                }
13601            }
13602            return true;
13603        }
13604
13605        @Override
13606        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13607            return new PackageParser.ServiceIntentInfo[size];
13608        }
13609
13610        @Override
13611        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13612            if (!sUserManager.exists(userId)) return true;
13613            PackageParser.Package p = filter.service.owner;
13614            if (p != null) {
13615                PackageSetting ps = (PackageSetting)p.mExtras;
13616                if (ps != null) {
13617                    // System apps are never considered stopped for purposes of
13618                    // filtering, because there may be no way for the user to
13619                    // actually re-launch them.
13620                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13621                            && ps.getStopped(userId);
13622                }
13623            }
13624            return false;
13625        }
13626
13627        @Override
13628        protected boolean isPackageForFilter(String packageName,
13629                PackageParser.ServiceIntentInfo info) {
13630            return packageName.equals(info.service.owner.packageName);
13631        }
13632
13633        @Override
13634        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13635                int match, int userId) {
13636            if (!sUserManager.exists(userId)) return null;
13637            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13638            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13639                return null;
13640            }
13641            final PackageParser.Service service = info.service;
13642            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13643            if (ps == null) {
13644                return null;
13645            }
13646            final PackageUserState userState = ps.readUserState(userId);
13647            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13648                    userState, userId);
13649            if (si == null) {
13650                return null;
13651            }
13652            final boolean matchVisibleToInstantApp =
13653                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13654            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13655            // throw out filters that aren't visible to ephemeral apps
13656            if (matchVisibleToInstantApp
13657                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13658                return null;
13659            }
13660            // throw out ephemeral filters if we're not explicitly requesting them
13661            if (!isInstantApp && userState.instantApp) {
13662                return null;
13663            }
13664            // throw out instant app filters if updates are available; will trigger
13665            // instant app resolution
13666            if (userState.instantApp && ps.isUpdateAvailable()) {
13667                return null;
13668            }
13669            final ResolveInfo res = new ResolveInfo();
13670            res.serviceInfo = si;
13671            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13672                res.filter = filter;
13673            }
13674            res.priority = info.getPriority();
13675            res.preferredOrder = service.owner.mPreferredOrder;
13676            res.match = match;
13677            res.isDefault = info.hasDefault;
13678            res.labelRes = info.labelRes;
13679            res.nonLocalizedLabel = info.nonLocalizedLabel;
13680            res.icon = info.icon;
13681            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13682            return res;
13683        }
13684
13685        @Override
13686        protected void sortResults(List<ResolveInfo> results) {
13687            Collections.sort(results, mResolvePrioritySorter);
13688        }
13689
13690        @Override
13691        protected void dumpFilter(PrintWriter out, String prefix,
13692                PackageParser.ServiceIntentInfo filter) {
13693            out.print(prefix); out.print(
13694                    Integer.toHexString(System.identityHashCode(filter.service)));
13695                    out.print(' ');
13696                    filter.service.printComponentShortName(out);
13697                    out.print(" filter ");
13698                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13699        }
13700
13701        @Override
13702        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13703            return filter.service;
13704        }
13705
13706        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13707            PackageParser.Service service = (PackageParser.Service)label;
13708            out.print(prefix); out.print(
13709                    Integer.toHexString(System.identityHashCode(service)));
13710                    out.print(' ');
13711                    service.printComponentShortName(out);
13712            if (count > 1) {
13713                out.print(" ("); out.print(count); out.print(" filters)");
13714            }
13715            out.println();
13716        }
13717
13718//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13719//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13720//            final List<ResolveInfo> retList = Lists.newArrayList();
13721//            while (i.hasNext()) {
13722//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13723//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13724//                    retList.add(resolveInfo);
13725//                }
13726//            }
13727//            return retList;
13728//        }
13729
13730        // Keys are String (activity class name), values are Activity.
13731        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13732                = new ArrayMap<ComponentName, PackageParser.Service>();
13733        private int mFlags;
13734    }
13735
13736    private final class ProviderIntentResolver
13737            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13738        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13739                boolean defaultOnly, int userId) {
13740            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13741            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13742        }
13743
13744        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13745                int userId) {
13746            if (!sUserManager.exists(userId))
13747                return null;
13748            mFlags = flags;
13749            return super.queryIntent(intent, resolvedType,
13750                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13751                    userId);
13752        }
13753
13754        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13755                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13756            if (!sUserManager.exists(userId))
13757                return null;
13758            if (packageProviders == null) {
13759                return null;
13760            }
13761            mFlags = flags;
13762            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13763            final int N = packageProviders.size();
13764            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13765                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13766
13767            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13768            for (int i = 0; i < N; ++i) {
13769                intentFilters = packageProviders.get(i).intents;
13770                if (intentFilters != null && intentFilters.size() > 0) {
13771                    PackageParser.ProviderIntentInfo[] array =
13772                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13773                    intentFilters.toArray(array);
13774                    listCut.add(array);
13775                }
13776            }
13777            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13778        }
13779
13780        public final void addProvider(PackageParser.Provider p) {
13781            if (mProviders.containsKey(p.getComponentName())) {
13782                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13783                return;
13784            }
13785
13786            mProviders.put(p.getComponentName(), p);
13787            if (DEBUG_SHOW_INFO) {
13788                Log.v(TAG, "  "
13789                        + (p.info.nonLocalizedLabel != null
13790                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13791                Log.v(TAG, "    Class=" + p.info.name);
13792            }
13793            final int NI = p.intents.size();
13794            int j;
13795            for (j = 0; j < NI; j++) {
13796                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13797                if (DEBUG_SHOW_INFO) {
13798                    Log.v(TAG, "    IntentFilter:");
13799                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13800                }
13801                if (!intent.debugCheck()) {
13802                    Log.w(TAG, "==> For Provider " + p.info.name);
13803                }
13804                addFilter(intent);
13805            }
13806        }
13807
13808        public final void removeProvider(PackageParser.Provider p) {
13809            mProviders.remove(p.getComponentName());
13810            if (DEBUG_SHOW_INFO) {
13811                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13812                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13813                Log.v(TAG, "    Class=" + p.info.name);
13814            }
13815            final int NI = p.intents.size();
13816            int j;
13817            for (j = 0; j < NI; j++) {
13818                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13819                if (DEBUG_SHOW_INFO) {
13820                    Log.v(TAG, "    IntentFilter:");
13821                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13822                }
13823                removeFilter(intent);
13824            }
13825        }
13826
13827        @Override
13828        protected boolean allowFilterResult(
13829                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13830            ProviderInfo filterPi = filter.provider.info;
13831            for (int i = dest.size() - 1; i >= 0; i--) {
13832                ProviderInfo destPi = dest.get(i).providerInfo;
13833                if (destPi.name == filterPi.name
13834                        && destPi.packageName == filterPi.packageName) {
13835                    return false;
13836                }
13837            }
13838            return true;
13839        }
13840
13841        @Override
13842        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13843            return new PackageParser.ProviderIntentInfo[size];
13844        }
13845
13846        @Override
13847        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13848            if (!sUserManager.exists(userId))
13849                return true;
13850            PackageParser.Package p = filter.provider.owner;
13851            if (p != null) {
13852                PackageSetting ps = (PackageSetting) p.mExtras;
13853                if (ps != null) {
13854                    // System apps are never considered stopped for purposes of
13855                    // filtering, because there may be no way for the user to
13856                    // actually re-launch them.
13857                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13858                            && ps.getStopped(userId);
13859                }
13860            }
13861            return false;
13862        }
13863
13864        @Override
13865        protected boolean isPackageForFilter(String packageName,
13866                PackageParser.ProviderIntentInfo info) {
13867            return packageName.equals(info.provider.owner.packageName);
13868        }
13869
13870        @Override
13871        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13872                int match, int userId) {
13873            if (!sUserManager.exists(userId))
13874                return null;
13875            final PackageParser.ProviderIntentInfo info = filter;
13876            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13877                return null;
13878            }
13879            final PackageParser.Provider provider = info.provider;
13880            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13881            if (ps == null) {
13882                return null;
13883            }
13884            final PackageUserState userState = ps.readUserState(userId);
13885            final boolean matchVisibleToInstantApp =
13886                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13887            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13888            // throw out filters that aren't visible to instant applications
13889            if (matchVisibleToInstantApp
13890                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13891                return null;
13892            }
13893            // throw out instant application filters if we're not explicitly requesting them
13894            if (!isInstantApp && userState.instantApp) {
13895                return null;
13896            }
13897            // throw out instant application filters if updates are available; will trigger
13898            // instant application resolution
13899            if (userState.instantApp && ps.isUpdateAvailable()) {
13900                return null;
13901            }
13902            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13903                    userState, userId);
13904            if (pi == null) {
13905                return null;
13906            }
13907            final ResolveInfo res = new ResolveInfo();
13908            res.providerInfo = pi;
13909            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13910                res.filter = filter;
13911            }
13912            res.priority = info.getPriority();
13913            res.preferredOrder = provider.owner.mPreferredOrder;
13914            res.match = match;
13915            res.isDefault = info.hasDefault;
13916            res.labelRes = info.labelRes;
13917            res.nonLocalizedLabel = info.nonLocalizedLabel;
13918            res.icon = info.icon;
13919            res.system = res.providerInfo.applicationInfo.isSystemApp();
13920            return res;
13921        }
13922
13923        @Override
13924        protected void sortResults(List<ResolveInfo> results) {
13925            Collections.sort(results, mResolvePrioritySorter);
13926        }
13927
13928        @Override
13929        protected void dumpFilter(PrintWriter out, String prefix,
13930                PackageParser.ProviderIntentInfo filter) {
13931            out.print(prefix);
13932            out.print(
13933                    Integer.toHexString(System.identityHashCode(filter.provider)));
13934            out.print(' ');
13935            filter.provider.printComponentShortName(out);
13936            out.print(" filter ");
13937            out.println(Integer.toHexString(System.identityHashCode(filter)));
13938        }
13939
13940        @Override
13941        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13942            return filter.provider;
13943        }
13944
13945        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13946            PackageParser.Provider provider = (PackageParser.Provider)label;
13947            out.print(prefix); out.print(
13948                    Integer.toHexString(System.identityHashCode(provider)));
13949                    out.print(' ');
13950                    provider.printComponentShortName(out);
13951            if (count > 1) {
13952                out.print(" ("); out.print(count); out.print(" filters)");
13953            }
13954            out.println();
13955        }
13956
13957        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13958                = new ArrayMap<ComponentName, PackageParser.Provider>();
13959        private int mFlags;
13960    }
13961
13962    static final class EphemeralIntentResolver
13963            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13964        /**
13965         * The result that has the highest defined order. Ordering applies on a
13966         * per-package basis. Mapping is from package name to Pair of order and
13967         * EphemeralResolveInfo.
13968         * <p>
13969         * NOTE: This is implemented as a field variable for convenience and efficiency.
13970         * By having a field variable, we're able to track filter ordering as soon as
13971         * a non-zero order is defined. Otherwise, multiple loops across the result set
13972         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13973         * this needs to be contained entirely within {@link #filterResults}.
13974         */
13975        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13976
13977        @Override
13978        protected AuxiliaryResolveInfo[] newArray(int size) {
13979            return new AuxiliaryResolveInfo[size];
13980        }
13981
13982        @Override
13983        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13984            return true;
13985        }
13986
13987        @Override
13988        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13989                int userId) {
13990            if (!sUserManager.exists(userId)) {
13991                return null;
13992            }
13993            final String packageName = responseObj.resolveInfo.getPackageName();
13994            final Integer order = responseObj.getOrder();
13995            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13996                    mOrderResult.get(packageName);
13997            // ordering is enabled and this item's order isn't high enough
13998            if (lastOrderResult != null && lastOrderResult.first >= order) {
13999                return null;
14000            }
14001            final InstantAppResolveInfo res = responseObj.resolveInfo;
14002            if (order > 0) {
14003                // non-zero order, enable ordering
14004                mOrderResult.put(packageName, new Pair<>(order, res));
14005            }
14006            return responseObj;
14007        }
14008
14009        @Override
14010        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14011            // only do work if ordering is enabled [most of the time it won't be]
14012            if (mOrderResult.size() == 0) {
14013                return;
14014            }
14015            int resultSize = results.size();
14016            for (int i = 0; i < resultSize; i++) {
14017                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14018                final String packageName = info.getPackageName();
14019                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14020                if (savedInfo == null) {
14021                    // package doesn't having ordering
14022                    continue;
14023                }
14024                if (savedInfo.second == info) {
14025                    // circled back to the highest ordered item; remove from order list
14026                    mOrderResult.remove(savedInfo);
14027                    if (mOrderResult.size() == 0) {
14028                        // no more ordered items
14029                        break;
14030                    }
14031                    continue;
14032                }
14033                // item has a worse order, remove it from the result list
14034                results.remove(i);
14035                resultSize--;
14036                i--;
14037            }
14038        }
14039    }
14040
14041    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14042            new Comparator<ResolveInfo>() {
14043        public int compare(ResolveInfo r1, ResolveInfo r2) {
14044            int v1 = r1.priority;
14045            int v2 = r2.priority;
14046            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14047            if (v1 != v2) {
14048                return (v1 > v2) ? -1 : 1;
14049            }
14050            v1 = r1.preferredOrder;
14051            v2 = r2.preferredOrder;
14052            if (v1 != v2) {
14053                return (v1 > v2) ? -1 : 1;
14054            }
14055            if (r1.isDefault != r2.isDefault) {
14056                return r1.isDefault ? -1 : 1;
14057            }
14058            v1 = r1.match;
14059            v2 = r2.match;
14060            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14061            if (v1 != v2) {
14062                return (v1 > v2) ? -1 : 1;
14063            }
14064            if (r1.system != r2.system) {
14065                return r1.system ? -1 : 1;
14066            }
14067            if (r1.activityInfo != null) {
14068                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14069            }
14070            if (r1.serviceInfo != null) {
14071                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14072            }
14073            if (r1.providerInfo != null) {
14074                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14075            }
14076            return 0;
14077        }
14078    };
14079
14080    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14081            new Comparator<ProviderInfo>() {
14082        public int compare(ProviderInfo p1, ProviderInfo p2) {
14083            final int v1 = p1.initOrder;
14084            final int v2 = p2.initOrder;
14085            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14086        }
14087    };
14088
14089    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14090            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14091            final int[] userIds) {
14092        mHandler.post(new Runnable() {
14093            @Override
14094            public void run() {
14095                try {
14096                    final IActivityManager am = ActivityManager.getService();
14097                    if (am == null) return;
14098                    final int[] resolvedUserIds;
14099                    if (userIds == null) {
14100                        resolvedUserIds = am.getRunningUserIds();
14101                    } else {
14102                        resolvedUserIds = userIds;
14103                    }
14104                    for (int id : resolvedUserIds) {
14105                        final Intent intent = new Intent(action,
14106                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14107                        if (extras != null) {
14108                            intent.putExtras(extras);
14109                        }
14110                        if (targetPkg != null) {
14111                            intent.setPackage(targetPkg);
14112                        }
14113                        // Modify the UID when posting to other users
14114                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14115                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14116                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14117                            intent.putExtra(Intent.EXTRA_UID, uid);
14118                        }
14119                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14120                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14121                        if (DEBUG_BROADCASTS) {
14122                            RuntimeException here = new RuntimeException("here");
14123                            here.fillInStackTrace();
14124                            Slog.d(TAG, "Sending to user " + id + ": "
14125                                    + intent.toShortString(false, true, false, false)
14126                                    + " " + intent.getExtras(), here);
14127                        }
14128                        am.broadcastIntent(null, intent, null, finishedReceiver,
14129                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14130                                null, finishedReceiver != null, false, id);
14131                    }
14132                } catch (RemoteException ex) {
14133                }
14134            }
14135        });
14136    }
14137
14138    /**
14139     * Check if the external storage media is available. This is true if there
14140     * is a mounted external storage medium or if the external storage is
14141     * emulated.
14142     */
14143    private boolean isExternalMediaAvailable() {
14144        return mMediaMounted || Environment.isExternalStorageEmulated();
14145    }
14146
14147    @Override
14148    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14149        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14150            return null;
14151        }
14152        // writer
14153        synchronized (mPackages) {
14154            if (!isExternalMediaAvailable()) {
14155                // If the external storage is no longer mounted at this point,
14156                // the caller may not have been able to delete all of this
14157                // packages files and can not delete any more.  Bail.
14158                return null;
14159            }
14160            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14161            if (lastPackage != null) {
14162                pkgs.remove(lastPackage);
14163            }
14164            if (pkgs.size() > 0) {
14165                return pkgs.get(0);
14166            }
14167        }
14168        return null;
14169    }
14170
14171    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14172        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14173                userId, andCode ? 1 : 0, packageName);
14174        if (mSystemReady) {
14175            msg.sendToTarget();
14176        } else {
14177            if (mPostSystemReadyMessages == null) {
14178                mPostSystemReadyMessages = new ArrayList<>();
14179            }
14180            mPostSystemReadyMessages.add(msg);
14181        }
14182    }
14183
14184    void startCleaningPackages() {
14185        // reader
14186        if (!isExternalMediaAvailable()) {
14187            return;
14188        }
14189        synchronized (mPackages) {
14190            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14191                return;
14192            }
14193        }
14194        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14195        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14196        IActivityManager am = ActivityManager.getService();
14197        if (am != null) {
14198            int dcsUid = -1;
14199            synchronized (mPackages) {
14200                if (!mDefaultContainerWhitelisted) {
14201                    mDefaultContainerWhitelisted = true;
14202                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14203                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14204                }
14205            }
14206            try {
14207                if (dcsUid > 0) {
14208                    am.backgroundWhitelistUid(dcsUid);
14209                }
14210                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14211                        UserHandle.USER_SYSTEM);
14212            } catch (RemoteException e) {
14213            }
14214        }
14215    }
14216
14217    @Override
14218    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14219            int installFlags, String installerPackageName, int userId) {
14220        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14221
14222        final int callingUid = Binder.getCallingUid();
14223        enforceCrossUserPermission(callingUid, userId,
14224                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14225
14226        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14227            try {
14228                if (observer != null) {
14229                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14230                }
14231            } catch (RemoteException re) {
14232            }
14233            return;
14234        }
14235
14236        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14237            installFlags |= PackageManager.INSTALL_FROM_ADB;
14238
14239        } else {
14240            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14241            // about installerPackageName.
14242
14243            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14244            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14245        }
14246
14247        UserHandle user;
14248        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14249            user = UserHandle.ALL;
14250        } else {
14251            user = new UserHandle(userId);
14252        }
14253
14254        // Only system components can circumvent runtime permissions when installing.
14255        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14256                && mContext.checkCallingOrSelfPermission(Manifest.permission
14257                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14258            throw new SecurityException("You need the "
14259                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14260                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14261        }
14262
14263        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14264                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14265            throw new IllegalArgumentException(
14266                    "New installs into ASEC containers no longer supported");
14267        }
14268
14269        final File originFile = new File(originPath);
14270        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14271
14272        final Message msg = mHandler.obtainMessage(INIT_COPY);
14273        final VerificationInfo verificationInfo = new VerificationInfo(
14274                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14275        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14276                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14277                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14278                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14279        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14280        msg.obj = params;
14281
14282        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14283                System.identityHashCode(msg.obj));
14284        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14285                System.identityHashCode(msg.obj));
14286
14287        mHandler.sendMessage(msg);
14288    }
14289
14290
14291    /**
14292     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14293     * it is acting on behalf on an enterprise or the user).
14294     *
14295     * Note that the ordering of the conditionals in this method is important. The checks we perform
14296     * are as follows, in this order:
14297     *
14298     * 1) If the install is being performed by a system app, we can trust the app to have set the
14299     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14300     *    what it is.
14301     * 2) If the install is being performed by a device or profile owner app, the install reason
14302     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14303     *    set the install reason correctly. If the app targets an older SDK version where install
14304     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14305     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14306     * 3) In all other cases, the install is being performed by a regular app that is neither part
14307     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14308     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14309     *    set to enterprise policy and if so, change it to unknown instead.
14310     */
14311    private int fixUpInstallReason(String installerPackageName, int installerUid,
14312            int installReason) {
14313        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14314                == PERMISSION_GRANTED) {
14315            // If the install is being performed by a system app, we trust that app to have set the
14316            // install reason correctly.
14317            return installReason;
14318        }
14319
14320        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14321            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14322        if (dpm != null) {
14323            ComponentName owner = null;
14324            try {
14325                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14326                if (owner == null) {
14327                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14328                }
14329            } catch (RemoteException e) {
14330            }
14331            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14332                // If the install is being performed by a device or profile owner, the install
14333                // reason should be enterprise policy.
14334                return PackageManager.INSTALL_REASON_POLICY;
14335            }
14336        }
14337
14338        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14339            // If the install is being performed by a regular app (i.e. neither system app nor
14340            // device or profile owner), we have no reason to believe that the app is acting on
14341            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14342            // change it to unknown instead.
14343            return PackageManager.INSTALL_REASON_UNKNOWN;
14344        }
14345
14346        // If the install is being performed by a regular app and the install reason was set to any
14347        // value but enterprise policy, leave the install reason unchanged.
14348        return installReason;
14349    }
14350
14351    void installStage(String packageName, File stagedDir, String stagedCid,
14352            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14353            String installerPackageName, int installerUid, UserHandle user,
14354            Certificate[][] certificates) {
14355        if (DEBUG_EPHEMERAL) {
14356            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14357                Slog.d(TAG, "Ephemeral install of " + packageName);
14358            }
14359        }
14360        final VerificationInfo verificationInfo = new VerificationInfo(
14361                sessionParams.originatingUri, sessionParams.referrerUri,
14362                sessionParams.originatingUid, installerUid);
14363
14364        final OriginInfo origin;
14365        if (stagedDir != null) {
14366            origin = OriginInfo.fromStagedFile(stagedDir);
14367        } else {
14368            origin = OriginInfo.fromStagedContainer(stagedCid);
14369        }
14370
14371        final Message msg = mHandler.obtainMessage(INIT_COPY);
14372        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14373                sessionParams.installReason);
14374        final InstallParams params = new InstallParams(origin, null, observer,
14375                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14376                verificationInfo, user, sessionParams.abiOverride,
14377                sessionParams.grantedRuntimePermissions, certificates, installReason);
14378        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14379        msg.obj = params;
14380
14381        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14382                System.identityHashCode(msg.obj));
14383        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14384                System.identityHashCode(msg.obj));
14385
14386        mHandler.sendMessage(msg);
14387    }
14388
14389    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14390            int userId) {
14391        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14392        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14393
14394        // Send a session commit broadcast
14395        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14396        info.installReason = pkgSetting.getInstallReason(userId);
14397        info.appPackageName = packageName;
14398        sendSessionCommitBroadcast(info, userId);
14399    }
14400
14401    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14402        if (ArrayUtils.isEmpty(userIds)) {
14403            return;
14404        }
14405        Bundle extras = new Bundle(1);
14406        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14407        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14408
14409        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14410                packageName, extras, 0, null, null, userIds);
14411        if (isSystem) {
14412            mHandler.post(() -> {
14413                        for (int userId : userIds) {
14414                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14415                        }
14416                    }
14417            );
14418        }
14419    }
14420
14421    /**
14422     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14423     * automatically without needing an explicit launch.
14424     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14425     */
14426    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14427        // If user is not running, the app didn't miss any broadcast
14428        if (!mUserManagerInternal.isUserRunning(userId)) {
14429            return;
14430        }
14431        final IActivityManager am = ActivityManager.getService();
14432        try {
14433            // Deliver LOCKED_BOOT_COMPLETED first
14434            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14435                    .setPackage(packageName);
14436            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14437            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14438                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14439
14440            // Deliver BOOT_COMPLETED only if user is unlocked
14441            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14442                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14443                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14444                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14445            }
14446        } catch (RemoteException e) {
14447            throw e.rethrowFromSystemServer();
14448        }
14449    }
14450
14451    @Override
14452    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14453            int userId) {
14454        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14455        PackageSetting pkgSetting;
14456        final int callingUid = Binder.getCallingUid();
14457        enforceCrossUserPermission(callingUid, userId,
14458                true /* requireFullPermission */, true /* checkShell */,
14459                "setApplicationHiddenSetting for user " + userId);
14460
14461        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14462            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14463            return false;
14464        }
14465
14466        long callingId = Binder.clearCallingIdentity();
14467        try {
14468            boolean sendAdded = false;
14469            boolean sendRemoved = false;
14470            // writer
14471            synchronized (mPackages) {
14472                pkgSetting = mSettings.mPackages.get(packageName);
14473                if (pkgSetting == null) {
14474                    return false;
14475                }
14476                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14477                    return false;
14478                }
14479                // Do not allow "android" is being disabled
14480                if ("android".equals(packageName)) {
14481                    Slog.w(TAG, "Cannot hide package: android");
14482                    return false;
14483                }
14484                // Cannot hide static shared libs as they are considered
14485                // a part of the using app (emulating static linking). Also
14486                // static libs are installed always on internal storage.
14487                PackageParser.Package pkg = mPackages.get(packageName);
14488                if (pkg != null && pkg.staticSharedLibName != null) {
14489                    Slog.w(TAG, "Cannot hide package: " + packageName
14490                            + " providing static shared library: "
14491                            + pkg.staticSharedLibName);
14492                    return false;
14493                }
14494                // Only allow protected packages to hide themselves.
14495                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14496                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14497                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14498                    return false;
14499                }
14500
14501                if (pkgSetting.getHidden(userId) != hidden) {
14502                    pkgSetting.setHidden(hidden, userId);
14503                    mSettings.writePackageRestrictionsLPr(userId);
14504                    if (hidden) {
14505                        sendRemoved = true;
14506                    } else {
14507                        sendAdded = true;
14508                    }
14509                }
14510            }
14511            if (sendAdded) {
14512                sendPackageAddedForUser(packageName, pkgSetting, userId);
14513                return true;
14514            }
14515            if (sendRemoved) {
14516                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14517                        "hiding pkg");
14518                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14519                return true;
14520            }
14521        } finally {
14522            Binder.restoreCallingIdentity(callingId);
14523        }
14524        return false;
14525    }
14526
14527    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14528            int userId) {
14529        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14530        info.removedPackage = packageName;
14531        info.installerPackageName = pkgSetting.installerPackageName;
14532        info.removedUsers = new int[] {userId};
14533        info.broadcastUsers = new int[] {userId};
14534        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14535        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14536    }
14537
14538    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14539        if (pkgList.length > 0) {
14540            Bundle extras = new Bundle(1);
14541            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14542
14543            sendPackageBroadcast(
14544                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14545                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14546                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14547                    new int[] {userId});
14548        }
14549    }
14550
14551    /**
14552     * Returns true if application is not found or there was an error. Otherwise it returns
14553     * the hidden state of the package for the given user.
14554     */
14555    @Override
14556    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14557        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14558        final int callingUid = Binder.getCallingUid();
14559        enforceCrossUserPermission(callingUid, userId,
14560                true /* requireFullPermission */, false /* checkShell */,
14561                "getApplicationHidden for user " + userId);
14562        PackageSetting ps;
14563        long callingId = Binder.clearCallingIdentity();
14564        try {
14565            // writer
14566            synchronized (mPackages) {
14567                ps = mSettings.mPackages.get(packageName);
14568                if (ps == null) {
14569                    return true;
14570                }
14571                if (filterAppAccessLPr(ps, callingUid, userId)) {
14572                    return true;
14573                }
14574                return ps.getHidden(userId);
14575            }
14576        } finally {
14577            Binder.restoreCallingIdentity(callingId);
14578        }
14579    }
14580
14581    /**
14582     * @hide
14583     */
14584    @Override
14585    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14586            int installReason) {
14587        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14588                null);
14589        PackageSetting pkgSetting;
14590        final int callingUid = Binder.getCallingUid();
14591        enforceCrossUserPermission(callingUid, userId,
14592                true /* requireFullPermission */, true /* checkShell */,
14593                "installExistingPackage for user " + userId);
14594        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14595            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14596        }
14597
14598        long callingId = Binder.clearCallingIdentity();
14599        try {
14600            boolean installed = false;
14601            final boolean instantApp =
14602                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14603            final boolean fullApp =
14604                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14605
14606            // writer
14607            synchronized (mPackages) {
14608                pkgSetting = mSettings.mPackages.get(packageName);
14609                if (pkgSetting == null) {
14610                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14611                }
14612                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14613                    // only allow the existing package to be used if it's installed as a full
14614                    // application for at least one user
14615                    boolean installAllowed = false;
14616                    for (int checkUserId : sUserManager.getUserIds()) {
14617                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14618                        if (installAllowed) {
14619                            break;
14620                        }
14621                    }
14622                    if (!installAllowed) {
14623                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14624                    }
14625                }
14626                if (!pkgSetting.getInstalled(userId)) {
14627                    pkgSetting.setInstalled(true, userId);
14628                    pkgSetting.setHidden(false, userId);
14629                    pkgSetting.setInstallReason(installReason, userId);
14630                    mSettings.writePackageRestrictionsLPr(userId);
14631                    mSettings.writeKernelMappingLPr(pkgSetting);
14632                    installed = true;
14633                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14634                    // upgrade app from instant to full; we don't allow app downgrade
14635                    installed = true;
14636                }
14637                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14638            }
14639
14640            if (installed) {
14641                if (pkgSetting.pkg != null) {
14642                    synchronized (mInstallLock) {
14643                        // We don't need to freeze for a brand new install
14644                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14645                    }
14646                }
14647                sendPackageAddedForUser(packageName, pkgSetting, userId);
14648                synchronized (mPackages) {
14649                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14650                }
14651            }
14652        } finally {
14653            Binder.restoreCallingIdentity(callingId);
14654        }
14655
14656        return PackageManager.INSTALL_SUCCEEDED;
14657    }
14658
14659    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14660            boolean instantApp, boolean fullApp) {
14661        // no state specified; do nothing
14662        if (!instantApp && !fullApp) {
14663            return;
14664        }
14665        if (userId != UserHandle.USER_ALL) {
14666            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14667                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14668            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14669                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14670            }
14671        } else {
14672            for (int currentUserId : sUserManager.getUserIds()) {
14673                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14674                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14675                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14676                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14677                }
14678            }
14679        }
14680    }
14681
14682    boolean isUserRestricted(int userId, String restrictionKey) {
14683        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14684        if (restrictions.getBoolean(restrictionKey, false)) {
14685            Log.w(TAG, "User is restricted: " + restrictionKey);
14686            return true;
14687        }
14688        return false;
14689    }
14690
14691    @Override
14692    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14693            int userId) {
14694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14695        final int callingUid = Binder.getCallingUid();
14696        enforceCrossUserPermission(callingUid, userId,
14697                true /* requireFullPermission */, true /* checkShell */,
14698                "setPackagesSuspended for user " + userId);
14699
14700        if (ArrayUtils.isEmpty(packageNames)) {
14701            return packageNames;
14702        }
14703
14704        // List of package names for whom the suspended state has changed.
14705        List<String> changedPackages = new ArrayList<>(packageNames.length);
14706        // List of package names for whom the suspended state is not set as requested in this
14707        // method.
14708        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14709        long callingId = Binder.clearCallingIdentity();
14710        try {
14711            for (int i = 0; i < packageNames.length; i++) {
14712                String packageName = packageNames[i];
14713                boolean changed = false;
14714                final int appId;
14715                synchronized (mPackages) {
14716                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14717                    if (pkgSetting == null
14718                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14719                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14720                                + "\". Skipping suspending/un-suspending.");
14721                        unactionedPackages.add(packageName);
14722                        continue;
14723                    }
14724                    appId = pkgSetting.appId;
14725                    if (pkgSetting.getSuspended(userId) != suspended) {
14726                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14727                            unactionedPackages.add(packageName);
14728                            continue;
14729                        }
14730                        pkgSetting.setSuspended(suspended, userId);
14731                        mSettings.writePackageRestrictionsLPr(userId);
14732                        changed = true;
14733                        changedPackages.add(packageName);
14734                    }
14735                }
14736
14737                if (changed && suspended) {
14738                    killApplication(packageName, UserHandle.getUid(userId, appId),
14739                            "suspending package");
14740                }
14741            }
14742        } finally {
14743            Binder.restoreCallingIdentity(callingId);
14744        }
14745
14746        if (!changedPackages.isEmpty()) {
14747            sendPackagesSuspendedForUser(changedPackages.toArray(
14748                    new String[changedPackages.size()]), userId, suspended);
14749        }
14750
14751        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14752    }
14753
14754    @Override
14755    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14756        final int callingUid = Binder.getCallingUid();
14757        enforceCrossUserPermission(callingUid, userId,
14758                true /* requireFullPermission */, false /* checkShell */,
14759                "isPackageSuspendedForUser for user " + userId);
14760        synchronized (mPackages) {
14761            final PackageSetting ps = mSettings.mPackages.get(packageName);
14762            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14763                throw new IllegalArgumentException("Unknown target package: " + packageName);
14764            }
14765            return ps.getSuspended(userId);
14766        }
14767    }
14768
14769    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14770        if (isPackageDeviceAdmin(packageName, userId)) {
14771            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14772                    + "\": has an active device admin");
14773            return false;
14774        }
14775
14776        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14777        if (packageName.equals(activeLauncherPackageName)) {
14778            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14779                    + "\": contains the active launcher");
14780            return false;
14781        }
14782
14783        if (packageName.equals(mRequiredInstallerPackage)) {
14784            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14785                    + "\": required for package installation");
14786            return false;
14787        }
14788
14789        if (packageName.equals(mRequiredUninstallerPackage)) {
14790            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14791                    + "\": required for package uninstallation");
14792            return false;
14793        }
14794
14795        if (packageName.equals(mRequiredVerifierPackage)) {
14796            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14797                    + "\": required for package verification");
14798            return false;
14799        }
14800
14801        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14802            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14803                    + "\": is the default dialer");
14804            return false;
14805        }
14806
14807        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14808            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14809                    + "\": protected package");
14810            return false;
14811        }
14812
14813        // Cannot suspend static shared libs as they are considered
14814        // a part of the using app (emulating static linking). Also
14815        // static libs are installed always on internal storage.
14816        PackageParser.Package pkg = mPackages.get(packageName);
14817        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14818            Slog.w(TAG, "Cannot suspend package: " + packageName
14819                    + " providing static shared library: "
14820                    + pkg.staticSharedLibName);
14821            return false;
14822        }
14823
14824        return true;
14825    }
14826
14827    private String getActiveLauncherPackageName(int userId) {
14828        Intent intent = new Intent(Intent.ACTION_MAIN);
14829        intent.addCategory(Intent.CATEGORY_HOME);
14830        ResolveInfo resolveInfo = resolveIntent(
14831                intent,
14832                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14833                PackageManager.MATCH_DEFAULT_ONLY,
14834                userId);
14835
14836        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14837    }
14838
14839    private String getDefaultDialerPackageName(int userId) {
14840        synchronized (mPackages) {
14841            return mSettings.getDefaultDialerPackageNameLPw(userId);
14842        }
14843    }
14844
14845    @Override
14846    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14847        mContext.enforceCallingOrSelfPermission(
14848                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14849                "Only package verification agents can verify applications");
14850
14851        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14852        final PackageVerificationResponse response = new PackageVerificationResponse(
14853                verificationCode, Binder.getCallingUid());
14854        msg.arg1 = id;
14855        msg.obj = response;
14856        mHandler.sendMessage(msg);
14857    }
14858
14859    @Override
14860    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14861            long millisecondsToDelay) {
14862        mContext.enforceCallingOrSelfPermission(
14863                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14864                "Only package verification agents can extend verification timeouts");
14865
14866        final PackageVerificationState state = mPendingVerification.get(id);
14867        final PackageVerificationResponse response = new PackageVerificationResponse(
14868                verificationCodeAtTimeout, Binder.getCallingUid());
14869
14870        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14871            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14872        }
14873        if (millisecondsToDelay < 0) {
14874            millisecondsToDelay = 0;
14875        }
14876        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14877                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14878            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14879        }
14880
14881        if ((state != null) && !state.timeoutExtended()) {
14882            state.extendTimeout();
14883
14884            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14885            msg.arg1 = id;
14886            msg.obj = response;
14887            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14888        }
14889    }
14890
14891    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14892            int verificationCode, UserHandle user) {
14893        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14894        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14895        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14896        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14897        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14898
14899        mContext.sendBroadcastAsUser(intent, user,
14900                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14901    }
14902
14903    private ComponentName matchComponentForVerifier(String packageName,
14904            List<ResolveInfo> receivers) {
14905        ActivityInfo targetReceiver = null;
14906
14907        final int NR = receivers.size();
14908        for (int i = 0; i < NR; i++) {
14909            final ResolveInfo info = receivers.get(i);
14910            if (info.activityInfo == null) {
14911                continue;
14912            }
14913
14914            if (packageName.equals(info.activityInfo.packageName)) {
14915                targetReceiver = info.activityInfo;
14916                break;
14917            }
14918        }
14919
14920        if (targetReceiver == null) {
14921            return null;
14922        }
14923
14924        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14925    }
14926
14927    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14928            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14929        if (pkgInfo.verifiers.length == 0) {
14930            return null;
14931        }
14932
14933        final int N = pkgInfo.verifiers.length;
14934        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14935        for (int i = 0; i < N; i++) {
14936            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14937
14938            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14939                    receivers);
14940            if (comp == null) {
14941                continue;
14942            }
14943
14944            final int verifierUid = getUidForVerifier(verifierInfo);
14945            if (verifierUid == -1) {
14946                continue;
14947            }
14948
14949            if (DEBUG_VERIFY) {
14950                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14951                        + " with the correct signature");
14952            }
14953            sufficientVerifiers.add(comp);
14954            verificationState.addSufficientVerifier(verifierUid);
14955        }
14956
14957        return sufficientVerifiers;
14958    }
14959
14960    private int getUidForVerifier(VerifierInfo verifierInfo) {
14961        synchronized (mPackages) {
14962            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14963            if (pkg == null) {
14964                return -1;
14965            } else if (pkg.mSignatures.length != 1) {
14966                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14967                        + " has more than one signature; ignoring");
14968                return -1;
14969            }
14970
14971            /*
14972             * If the public key of the package's signature does not match
14973             * our expected public key, then this is a different package and
14974             * we should skip.
14975             */
14976
14977            final byte[] expectedPublicKey;
14978            try {
14979                final Signature verifierSig = pkg.mSignatures[0];
14980                final PublicKey publicKey = verifierSig.getPublicKey();
14981                expectedPublicKey = publicKey.getEncoded();
14982            } catch (CertificateException e) {
14983                return -1;
14984            }
14985
14986            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14987
14988            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14989                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14990                        + " does not have the expected public key; ignoring");
14991                return -1;
14992            }
14993
14994            return pkg.applicationInfo.uid;
14995        }
14996    }
14997
14998    @Override
14999    public void finishPackageInstall(int token, boolean didLaunch) {
15000        enforceSystemOrRoot("Only the system is allowed to finish installs");
15001
15002        if (DEBUG_INSTALL) {
15003            Slog.v(TAG, "BM finishing package install for " + token);
15004        }
15005        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15006
15007        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15008        mHandler.sendMessage(msg);
15009    }
15010
15011    /**
15012     * Get the verification agent timeout.  Used for both the APK verifier and the
15013     * intent filter verifier.
15014     *
15015     * @return verification timeout in milliseconds
15016     */
15017    private long getVerificationTimeout() {
15018        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15019                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15020                DEFAULT_VERIFICATION_TIMEOUT);
15021    }
15022
15023    /**
15024     * Get the default verification agent response code.
15025     *
15026     * @return default verification response code
15027     */
15028    private int getDefaultVerificationResponse(UserHandle user) {
15029        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15030            return PackageManager.VERIFICATION_REJECT;
15031        }
15032        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15033                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15034                DEFAULT_VERIFICATION_RESPONSE);
15035    }
15036
15037    /**
15038     * Check whether or not package verification has been enabled.
15039     *
15040     * @return true if verification should be performed
15041     */
15042    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15043        if (!DEFAULT_VERIFY_ENABLE) {
15044            return false;
15045        }
15046
15047        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15048
15049        // Check if installing from ADB
15050        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15051            // Do not run verification in a test harness environment
15052            if (ActivityManager.isRunningInTestHarness()) {
15053                return false;
15054            }
15055            if (ensureVerifyAppsEnabled) {
15056                return true;
15057            }
15058            // Check if the developer does not want package verification for ADB installs
15059            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15060                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15061                return false;
15062            }
15063        } else {
15064            // only when not installed from ADB, skip verification for instant apps when
15065            // the installer and verifier are the same.
15066            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15067                if (mInstantAppInstallerActivity != null
15068                        && mInstantAppInstallerActivity.packageName.equals(
15069                                mRequiredVerifierPackage)) {
15070                    try {
15071                        mContext.getSystemService(AppOpsManager.class)
15072                                .checkPackage(installerUid, mRequiredVerifierPackage);
15073                        if (DEBUG_VERIFY) {
15074                            Slog.i(TAG, "disable verification for instant app");
15075                        }
15076                        return false;
15077                    } catch (SecurityException ignore) { }
15078                }
15079            }
15080        }
15081
15082        if (ensureVerifyAppsEnabled) {
15083            return true;
15084        }
15085
15086        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15087                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15088    }
15089
15090    @Override
15091    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15092            throws RemoteException {
15093        mContext.enforceCallingOrSelfPermission(
15094                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15095                "Only intentfilter verification agents can verify applications");
15096
15097        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15098        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15099                Binder.getCallingUid(), verificationCode, failedDomains);
15100        msg.arg1 = id;
15101        msg.obj = response;
15102        mHandler.sendMessage(msg);
15103    }
15104
15105    @Override
15106    public int getIntentVerificationStatus(String packageName, int userId) {
15107        final int callingUid = Binder.getCallingUid();
15108        if (getInstantAppPackageName(callingUid) != null) {
15109            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15110        }
15111        synchronized (mPackages) {
15112            final PackageSetting ps = mSettings.mPackages.get(packageName);
15113            if (ps == null
15114                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15115                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15116            }
15117            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15118        }
15119    }
15120
15121    @Override
15122    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15123        mContext.enforceCallingOrSelfPermission(
15124                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15125
15126        boolean result = false;
15127        synchronized (mPackages) {
15128            final PackageSetting ps = mSettings.mPackages.get(packageName);
15129            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15130                return false;
15131            }
15132            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15133        }
15134        if (result) {
15135            scheduleWritePackageRestrictionsLocked(userId);
15136        }
15137        return result;
15138    }
15139
15140    @Override
15141    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15142            String packageName) {
15143        final int callingUid = Binder.getCallingUid();
15144        if (getInstantAppPackageName(callingUid) != null) {
15145            return ParceledListSlice.emptyList();
15146        }
15147        synchronized (mPackages) {
15148            final PackageSetting ps = mSettings.mPackages.get(packageName);
15149            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15150                return ParceledListSlice.emptyList();
15151            }
15152            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15153        }
15154    }
15155
15156    @Override
15157    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15158        if (TextUtils.isEmpty(packageName)) {
15159            return ParceledListSlice.emptyList();
15160        }
15161        final int callingUid = Binder.getCallingUid();
15162        final int callingUserId = UserHandle.getUserId(callingUid);
15163        synchronized (mPackages) {
15164            PackageParser.Package pkg = mPackages.get(packageName);
15165            if (pkg == null || pkg.activities == null) {
15166                return ParceledListSlice.emptyList();
15167            }
15168            if (pkg.mExtras == null) {
15169                return ParceledListSlice.emptyList();
15170            }
15171            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15172            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15173                return ParceledListSlice.emptyList();
15174            }
15175            final int count = pkg.activities.size();
15176            ArrayList<IntentFilter> result = new ArrayList<>();
15177            for (int n=0; n<count; n++) {
15178                PackageParser.Activity activity = pkg.activities.get(n);
15179                if (activity.intents != null && activity.intents.size() > 0) {
15180                    result.addAll(activity.intents);
15181                }
15182            }
15183            return new ParceledListSlice<>(result);
15184        }
15185    }
15186
15187    @Override
15188    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15189        mContext.enforceCallingOrSelfPermission(
15190                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15191
15192        synchronized (mPackages) {
15193            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15194            if (packageName != null) {
15195                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15196                        packageName, userId);
15197            }
15198            return result;
15199        }
15200    }
15201
15202    @Override
15203    public String getDefaultBrowserPackageName(int userId) {
15204        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15205            return null;
15206        }
15207        synchronized (mPackages) {
15208            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15209        }
15210    }
15211
15212    /**
15213     * Get the "allow unknown sources" setting.
15214     *
15215     * @return the current "allow unknown sources" setting
15216     */
15217    private int getUnknownSourcesSettings() {
15218        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15219                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15220                -1);
15221    }
15222
15223    @Override
15224    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15225        final int callingUid = Binder.getCallingUid();
15226        if (getInstantAppPackageName(callingUid) != null) {
15227            return;
15228        }
15229        // writer
15230        synchronized (mPackages) {
15231            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15232            if (targetPackageSetting == null
15233                    || filterAppAccessLPr(
15234                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15235                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15236            }
15237
15238            PackageSetting installerPackageSetting;
15239            if (installerPackageName != null) {
15240                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15241                if (installerPackageSetting == null) {
15242                    throw new IllegalArgumentException("Unknown installer package: "
15243                            + installerPackageName);
15244                }
15245            } else {
15246                installerPackageSetting = null;
15247            }
15248
15249            Signature[] callerSignature;
15250            Object obj = mSettings.getUserIdLPr(callingUid);
15251            if (obj != null) {
15252                if (obj instanceof SharedUserSetting) {
15253                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15254                } else if (obj instanceof PackageSetting) {
15255                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15256                } else {
15257                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15258                }
15259            } else {
15260                throw new SecurityException("Unknown calling UID: " + callingUid);
15261            }
15262
15263            // Verify: can't set installerPackageName to a package that is
15264            // not signed with the same cert as the caller.
15265            if (installerPackageSetting != null) {
15266                if (compareSignatures(callerSignature,
15267                        installerPackageSetting.signatures.mSignatures)
15268                        != PackageManager.SIGNATURE_MATCH) {
15269                    throw new SecurityException(
15270                            "Caller does not have same cert as new installer package "
15271                            + installerPackageName);
15272                }
15273            }
15274
15275            // Verify: if target already has an installer package, it must
15276            // be signed with the same cert as the caller.
15277            if (targetPackageSetting.installerPackageName != null) {
15278                PackageSetting setting = mSettings.mPackages.get(
15279                        targetPackageSetting.installerPackageName);
15280                // If the currently set package isn't valid, then it's always
15281                // okay to change it.
15282                if (setting != null) {
15283                    if (compareSignatures(callerSignature,
15284                            setting.signatures.mSignatures)
15285                            != PackageManager.SIGNATURE_MATCH) {
15286                        throw new SecurityException(
15287                                "Caller does not have same cert as old installer package "
15288                                + targetPackageSetting.installerPackageName);
15289                    }
15290                }
15291            }
15292
15293            // Okay!
15294            targetPackageSetting.installerPackageName = installerPackageName;
15295            if (installerPackageName != null) {
15296                mSettings.mInstallerPackages.add(installerPackageName);
15297            }
15298            scheduleWriteSettingsLocked();
15299        }
15300    }
15301
15302    @Override
15303    public void setApplicationCategoryHint(String packageName, int categoryHint,
15304            String callerPackageName) {
15305        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15306            throw new SecurityException("Instant applications don't have access to this method");
15307        }
15308        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15309                callerPackageName);
15310        synchronized (mPackages) {
15311            PackageSetting ps = mSettings.mPackages.get(packageName);
15312            if (ps == null) {
15313                throw new IllegalArgumentException("Unknown target package " + packageName);
15314            }
15315            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15316                throw new IllegalArgumentException("Unknown target package " + packageName);
15317            }
15318            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15319                throw new IllegalArgumentException("Calling package " + callerPackageName
15320                        + " is not installer for " + packageName);
15321            }
15322
15323            if (ps.categoryHint != categoryHint) {
15324                ps.categoryHint = categoryHint;
15325                scheduleWriteSettingsLocked();
15326            }
15327        }
15328    }
15329
15330    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15331        // Queue up an async operation since the package installation may take a little while.
15332        mHandler.post(new Runnable() {
15333            public void run() {
15334                mHandler.removeCallbacks(this);
15335                 // Result object to be returned
15336                PackageInstalledInfo res = new PackageInstalledInfo();
15337                res.setReturnCode(currentStatus);
15338                res.uid = -1;
15339                res.pkg = null;
15340                res.removedInfo = null;
15341                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15342                    args.doPreInstall(res.returnCode);
15343                    synchronized (mInstallLock) {
15344                        installPackageTracedLI(args, res);
15345                    }
15346                    args.doPostInstall(res.returnCode, res.uid);
15347                }
15348
15349                // A restore should be performed at this point if (a) the install
15350                // succeeded, (b) the operation is not an update, and (c) the new
15351                // package has not opted out of backup participation.
15352                final boolean update = res.removedInfo != null
15353                        && res.removedInfo.removedPackage != null;
15354                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15355                boolean doRestore = !update
15356                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15357
15358                // Set up the post-install work request bookkeeping.  This will be used
15359                // and cleaned up by the post-install event handling regardless of whether
15360                // there's a restore pass performed.  Token values are >= 1.
15361                int token;
15362                if (mNextInstallToken < 0) mNextInstallToken = 1;
15363                token = mNextInstallToken++;
15364
15365                PostInstallData data = new PostInstallData(args, res);
15366                mRunningInstalls.put(token, data);
15367                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15368
15369                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15370                    // Pass responsibility to the Backup Manager.  It will perform a
15371                    // restore if appropriate, then pass responsibility back to the
15372                    // Package Manager to run the post-install observer callbacks
15373                    // and broadcasts.
15374                    IBackupManager bm = IBackupManager.Stub.asInterface(
15375                            ServiceManager.getService(Context.BACKUP_SERVICE));
15376                    if (bm != null) {
15377                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15378                                + " to BM for possible restore");
15379                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15380                        try {
15381                            // TODO: http://b/22388012
15382                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15383                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15384                            } else {
15385                                doRestore = false;
15386                            }
15387                        } catch (RemoteException e) {
15388                            // can't happen; the backup manager is local
15389                        } catch (Exception e) {
15390                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15391                            doRestore = false;
15392                        }
15393                    } else {
15394                        Slog.e(TAG, "Backup Manager not found!");
15395                        doRestore = false;
15396                    }
15397                }
15398
15399                if (!doRestore) {
15400                    // No restore possible, or the Backup Manager was mysteriously not
15401                    // available -- just fire the post-install work request directly.
15402                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15403
15404                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15405
15406                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15407                    mHandler.sendMessage(msg);
15408                }
15409            }
15410        });
15411    }
15412
15413    /**
15414     * Callback from PackageSettings whenever an app is first transitioned out of the
15415     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15416     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15417     * here whether the app is the target of an ongoing install, and only send the
15418     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15419     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15420     * handling.
15421     */
15422    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15423        // Serialize this with the rest of the install-process message chain.  In the
15424        // restore-at-install case, this Runnable will necessarily run before the
15425        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15426        // are coherent.  In the non-restore case, the app has already completed install
15427        // and been launched through some other means, so it is not in a problematic
15428        // state for observers to see the FIRST_LAUNCH signal.
15429        mHandler.post(new Runnable() {
15430            @Override
15431            public void run() {
15432                for (int i = 0; i < mRunningInstalls.size(); i++) {
15433                    final PostInstallData data = mRunningInstalls.valueAt(i);
15434                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15435                        continue;
15436                    }
15437                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15438                        // right package; but is it for the right user?
15439                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15440                            if (userId == data.res.newUsers[uIndex]) {
15441                                if (DEBUG_BACKUP) {
15442                                    Slog.i(TAG, "Package " + pkgName
15443                                            + " being restored so deferring FIRST_LAUNCH");
15444                                }
15445                                return;
15446                            }
15447                        }
15448                    }
15449                }
15450                // didn't find it, so not being restored
15451                if (DEBUG_BACKUP) {
15452                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15453                }
15454                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15455            }
15456        });
15457    }
15458
15459    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15460        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15461                installerPkg, null, userIds);
15462    }
15463
15464    private abstract class HandlerParams {
15465        private static final int MAX_RETRIES = 4;
15466
15467        /**
15468         * Number of times startCopy() has been attempted and had a non-fatal
15469         * error.
15470         */
15471        private int mRetries = 0;
15472
15473        /** User handle for the user requesting the information or installation. */
15474        private final UserHandle mUser;
15475        String traceMethod;
15476        int traceCookie;
15477
15478        HandlerParams(UserHandle user) {
15479            mUser = user;
15480        }
15481
15482        UserHandle getUser() {
15483            return mUser;
15484        }
15485
15486        HandlerParams setTraceMethod(String traceMethod) {
15487            this.traceMethod = traceMethod;
15488            return this;
15489        }
15490
15491        HandlerParams setTraceCookie(int traceCookie) {
15492            this.traceCookie = traceCookie;
15493            return this;
15494        }
15495
15496        final boolean startCopy() {
15497            boolean res;
15498            try {
15499                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15500
15501                if (++mRetries > MAX_RETRIES) {
15502                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15503                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15504                    handleServiceError();
15505                    return false;
15506                } else {
15507                    handleStartCopy();
15508                    res = true;
15509                }
15510            } catch (RemoteException e) {
15511                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15512                mHandler.sendEmptyMessage(MCS_RECONNECT);
15513                res = false;
15514            }
15515            handleReturnCode();
15516            return res;
15517        }
15518
15519        final void serviceError() {
15520            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15521            handleServiceError();
15522            handleReturnCode();
15523        }
15524
15525        abstract void handleStartCopy() throws RemoteException;
15526        abstract void handleServiceError();
15527        abstract void handleReturnCode();
15528    }
15529
15530    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15531        for (File path : paths) {
15532            try {
15533                mcs.clearDirectory(path.getAbsolutePath());
15534            } catch (RemoteException e) {
15535            }
15536        }
15537    }
15538
15539    static class OriginInfo {
15540        /**
15541         * Location where install is coming from, before it has been
15542         * copied/renamed into place. This could be a single monolithic APK
15543         * file, or a cluster directory. This location may be untrusted.
15544         */
15545        final File file;
15546        final String cid;
15547
15548        /**
15549         * Flag indicating that {@link #file} or {@link #cid} has already been
15550         * staged, meaning downstream users don't need to defensively copy the
15551         * contents.
15552         */
15553        final boolean staged;
15554
15555        /**
15556         * Flag indicating that {@link #file} or {@link #cid} is an already
15557         * installed app that is being moved.
15558         */
15559        final boolean existing;
15560
15561        final String resolvedPath;
15562        final File resolvedFile;
15563
15564        static OriginInfo fromNothing() {
15565            return new OriginInfo(null, null, false, false);
15566        }
15567
15568        static OriginInfo fromUntrustedFile(File file) {
15569            return new OriginInfo(file, null, false, false);
15570        }
15571
15572        static OriginInfo fromExistingFile(File file) {
15573            return new OriginInfo(file, null, false, true);
15574        }
15575
15576        static OriginInfo fromStagedFile(File file) {
15577            return new OriginInfo(file, null, true, false);
15578        }
15579
15580        static OriginInfo fromStagedContainer(String cid) {
15581            return new OriginInfo(null, cid, true, false);
15582        }
15583
15584        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15585            this.file = file;
15586            this.cid = cid;
15587            this.staged = staged;
15588            this.existing = existing;
15589
15590            if (cid != null) {
15591                resolvedPath = PackageHelper.getSdDir(cid);
15592                resolvedFile = new File(resolvedPath);
15593            } else if (file != null) {
15594                resolvedPath = file.getAbsolutePath();
15595                resolvedFile = file;
15596            } else {
15597                resolvedPath = null;
15598                resolvedFile = null;
15599            }
15600        }
15601    }
15602
15603    static class MoveInfo {
15604        final int moveId;
15605        final String fromUuid;
15606        final String toUuid;
15607        final String packageName;
15608        final String dataAppName;
15609        final int appId;
15610        final String seinfo;
15611        final int targetSdkVersion;
15612
15613        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15614                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15615            this.moveId = moveId;
15616            this.fromUuid = fromUuid;
15617            this.toUuid = toUuid;
15618            this.packageName = packageName;
15619            this.dataAppName = dataAppName;
15620            this.appId = appId;
15621            this.seinfo = seinfo;
15622            this.targetSdkVersion = targetSdkVersion;
15623        }
15624    }
15625
15626    static class VerificationInfo {
15627        /** A constant used to indicate that a uid value is not present. */
15628        public static final int NO_UID = -1;
15629
15630        /** URI referencing where the package was downloaded from. */
15631        final Uri originatingUri;
15632
15633        /** HTTP referrer URI associated with the originatingURI. */
15634        final Uri referrer;
15635
15636        /** UID of the application that the install request originated from. */
15637        final int originatingUid;
15638
15639        /** UID of application requesting the install */
15640        final int installerUid;
15641
15642        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15643            this.originatingUri = originatingUri;
15644            this.referrer = referrer;
15645            this.originatingUid = originatingUid;
15646            this.installerUid = installerUid;
15647        }
15648    }
15649
15650    class InstallParams extends HandlerParams {
15651        final OriginInfo origin;
15652        final MoveInfo move;
15653        final IPackageInstallObserver2 observer;
15654        int installFlags;
15655        final String installerPackageName;
15656        final String volumeUuid;
15657        private InstallArgs mArgs;
15658        private int mRet;
15659        final String packageAbiOverride;
15660        final String[] grantedRuntimePermissions;
15661        final VerificationInfo verificationInfo;
15662        final Certificate[][] certificates;
15663        final int installReason;
15664
15665        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15666                int installFlags, String installerPackageName, String volumeUuid,
15667                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15668                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15669            super(user);
15670            this.origin = origin;
15671            this.move = move;
15672            this.observer = observer;
15673            this.installFlags = installFlags;
15674            this.installerPackageName = installerPackageName;
15675            this.volumeUuid = volumeUuid;
15676            this.verificationInfo = verificationInfo;
15677            this.packageAbiOverride = packageAbiOverride;
15678            this.grantedRuntimePermissions = grantedPermissions;
15679            this.certificates = certificates;
15680            this.installReason = installReason;
15681        }
15682
15683        @Override
15684        public String toString() {
15685            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15686                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15687        }
15688
15689        private int installLocationPolicy(PackageInfoLite pkgLite) {
15690            String packageName = pkgLite.packageName;
15691            int installLocation = pkgLite.installLocation;
15692            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15693            // reader
15694            synchronized (mPackages) {
15695                // Currently installed package which the new package is attempting to replace or
15696                // null if no such package is installed.
15697                PackageParser.Package installedPkg = mPackages.get(packageName);
15698                // Package which currently owns the data which the new package will own if installed.
15699                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15700                // will be null whereas dataOwnerPkg will contain information about the package
15701                // which was uninstalled while keeping its data.
15702                PackageParser.Package dataOwnerPkg = installedPkg;
15703                if (dataOwnerPkg  == null) {
15704                    PackageSetting ps = mSettings.mPackages.get(packageName);
15705                    if (ps != null) {
15706                        dataOwnerPkg = ps.pkg;
15707                    }
15708                }
15709
15710                if (dataOwnerPkg != null) {
15711                    // If installed, the package will get access to data left on the device by its
15712                    // predecessor. As a security measure, this is permited only if this is not a
15713                    // version downgrade or if the predecessor package is marked as debuggable and
15714                    // a downgrade is explicitly requested.
15715                    //
15716                    // On debuggable platform builds, downgrades are permitted even for
15717                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15718                    // not offer security guarantees and thus it's OK to disable some security
15719                    // mechanisms to make debugging/testing easier on those builds. However, even on
15720                    // debuggable builds downgrades of packages are permitted only if requested via
15721                    // installFlags. This is because we aim to keep the behavior of debuggable
15722                    // platform builds as close as possible to the behavior of non-debuggable
15723                    // platform builds.
15724                    final boolean downgradeRequested =
15725                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15726                    final boolean packageDebuggable =
15727                                (dataOwnerPkg.applicationInfo.flags
15728                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15729                    final boolean downgradePermitted =
15730                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15731                    if (!downgradePermitted) {
15732                        try {
15733                            checkDowngrade(dataOwnerPkg, pkgLite);
15734                        } catch (PackageManagerException e) {
15735                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15736                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15737                        }
15738                    }
15739                }
15740
15741                if (installedPkg != null) {
15742                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15743                        // Check for updated system application.
15744                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15745                            if (onSd) {
15746                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15747                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15748                            }
15749                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15750                        } else {
15751                            if (onSd) {
15752                                // Install flag overrides everything.
15753                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15754                            }
15755                            // If current upgrade specifies particular preference
15756                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15757                                // Application explicitly specified internal.
15758                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15759                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15760                                // App explictly prefers external. Let policy decide
15761                            } else {
15762                                // Prefer previous location
15763                                if (isExternal(installedPkg)) {
15764                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15765                                }
15766                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15767                            }
15768                        }
15769                    } else {
15770                        // Invalid install. Return error code
15771                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15772                    }
15773                }
15774            }
15775            // All the special cases have been taken care of.
15776            // Return result based on recommended install location.
15777            if (onSd) {
15778                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15779            }
15780            return pkgLite.recommendedInstallLocation;
15781        }
15782
15783        /*
15784         * Invoke remote method to get package information and install
15785         * location values. Override install location based on default
15786         * policy if needed and then create install arguments based
15787         * on the install location.
15788         */
15789        public void handleStartCopy() throws RemoteException {
15790            int ret = PackageManager.INSTALL_SUCCEEDED;
15791
15792            // If we're already staged, we've firmly committed to an install location
15793            if (origin.staged) {
15794                if (origin.file != null) {
15795                    installFlags |= PackageManager.INSTALL_INTERNAL;
15796                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15797                } else if (origin.cid != null) {
15798                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15799                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15800                } else {
15801                    throw new IllegalStateException("Invalid stage location");
15802                }
15803            }
15804
15805            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15806            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15807            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15808            PackageInfoLite pkgLite = null;
15809
15810            if (onInt && onSd) {
15811                // Check if both bits are set.
15812                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15813                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15814            } else if (onSd && ephemeral) {
15815                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15816                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15817            } else {
15818                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15819                        packageAbiOverride);
15820
15821                if (DEBUG_EPHEMERAL && ephemeral) {
15822                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15823                }
15824
15825                /*
15826                 * If we have too little free space, try to free cache
15827                 * before giving up.
15828                 */
15829                if (!origin.staged && pkgLite.recommendedInstallLocation
15830                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15831                    // TODO: focus freeing disk space on the target device
15832                    final StorageManager storage = StorageManager.from(mContext);
15833                    final long lowThreshold = storage.getStorageLowBytes(
15834                            Environment.getDataDirectory());
15835
15836                    final long sizeBytes = mContainerService.calculateInstalledSize(
15837                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15838
15839                    try {
15840                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15841                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15842                                installFlags, packageAbiOverride);
15843                    } catch (InstallerException e) {
15844                        Slog.w(TAG, "Failed to free cache", e);
15845                    }
15846
15847                    /*
15848                     * The cache free must have deleted the file we
15849                     * downloaded to install.
15850                     *
15851                     * TODO: fix the "freeCache" call to not delete
15852                     *       the file we care about.
15853                     */
15854                    if (pkgLite.recommendedInstallLocation
15855                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15856                        pkgLite.recommendedInstallLocation
15857                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15858                    }
15859                }
15860            }
15861
15862            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15863                int loc = pkgLite.recommendedInstallLocation;
15864                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15865                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15866                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15867                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15868                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15869                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15870                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15871                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15872                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15873                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15874                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15875                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15876                } else {
15877                    // Override with defaults if needed.
15878                    loc = installLocationPolicy(pkgLite);
15879                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15880                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15881                    } else if (!onSd && !onInt) {
15882                        // Override install location with flags
15883                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15884                            // Set the flag to install on external media.
15885                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15886                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15887                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15888                            if (DEBUG_EPHEMERAL) {
15889                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15890                            }
15891                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15892                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15893                                    |PackageManager.INSTALL_INTERNAL);
15894                        } else {
15895                            // Make sure the flag for installing on external
15896                            // media is unset
15897                            installFlags |= PackageManager.INSTALL_INTERNAL;
15898                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15899                        }
15900                    }
15901                }
15902            }
15903
15904            final InstallArgs args = createInstallArgs(this);
15905            mArgs = args;
15906
15907            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15908                // TODO: http://b/22976637
15909                // Apps installed for "all" users use the device owner to verify the app
15910                UserHandle verifierUser = getUser();
15911                if (verifierUser == UserHandle.ALL) {
15912                    verifierUser = UserHandle.SYSTEM;
15913                }
15914
15915                /*
15916                 * Determine if we have any installed package verifiers. If we
15917                 * do, then we'll defer to them to verify the packages.
15918                 */
15919                final int requiredUid = mRequiredVerifierPackage == null ? -1
15920                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15921                                verifierUser.getIdentifier());
15922                final int installerUid =
15923                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15924                if (!origin.existing && requiredUid != -1
15925                        && isVerificationEnabled(
15926                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15927                    final Intent verification = new Intent(
15928                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15929                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15930                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15931                            PACKAGE_MIME_TYPE);
15932                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15933
15934                    // Query all live verifiers based on current user state
15935                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15936                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15937
15938                    if (DEBUG_VERIFY) {
15939                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15940                                + verification.toString() + " with " + pkgLite.verifiers.length
15941                                + " optional verifiers");
15942                    }
15943
15944                    final int verificationId = mPendingVerificationToken++;
15945
15946                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15947
15948                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15949                            installerPackageName);
15950
15951                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15952                            installFlags);
15953
15954                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15955                            pkgLite.packageName);
15956
15957                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15958                            pkgLite.versionCode);
15959
15960                    if (verificationInfo != null) {
15961                        if (verificationInfo.originatingUri != null) {
15962                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15963                                    verificationInfo.originatingUri);
15964                        }
15965                        if (verificationInfo.referrer != null) {
15966                            verification.putExtra(Intent.EXTRA_REFERRER,
15967                                    verificationInfo.referrer);
15968                        }
15969                        if (verificationInfo.originatingUid >= 0) {
15970                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15971                                    verificationInfo.originatingUid);
15972                        }
15973                        if (verificationInfo.installerUid >= 0) {
15974                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15975                                    verificationInfo.installerUid);
15976                        }
15977                    }
15978
15979                    final PackageVerificationState verificationState = new PackageVerificationState(
15980                            requiredUid, args);
15981
15982                    mPendingVerification.append(verificationId, verificationState);
15983
15984                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15985                            receivers, verificationState);
15986
15987                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15988                    final long idleDuration = getVerificationTimeout();
15989
15990                    /*
15991                     * If any sufficient verifiers were listed in the package
15992                     * manifest, attempt to ask them.
15993                     */
15994                    if (sufficientVerifiers != null) {
15995                        final int N = sufficientVerifiers.size();
15996                        if (N == 0) {
15997                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15998                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15999                        } else {
16000                            for (int i = 0; i < N; i++) {
16001                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16002                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16003                                        verifierComponent.getPackageName(), idleDuration,
16004                                        verifierUser.getIdentifier(), false, "package verifier");
16005
16006                                final Intent sufficientIntent = new Intent(verification);
16007                                sufficientIntent.setComponent(verifierComponent);
16008                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16009                            }
16010                        }
16011                    }
16012
16013                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16014                            mRequiredVerifierPackage, receivers);
16015                    if (ret == PackageManager.INSTALL_SUCCEEDED
16016                            && mRequiredVerifierPackage != null) {
16017                        Trace.asyncTraceBegin(
16018                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16019                        /*
16020                         * Send the intent to the required verification agent,
16021                         * but only start the verification timeout after the
16022                         * target BroadcastReceivers have run.
16023                         */
16024                        verification.setComponent(requiredVerifierComponent);
16025                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16026                                mRequiredVerifierPackage, idleDuration,
16027                                verifierUser.getIdentifier(), false, "package verifier");
16028                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16029                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16030                                new BroadcastReceiver() {
16031                                    @Override
16032                                    public void onReceive(Context context, Intent intent) {
16033                                        final Message msg = mHandler
16034                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16035                                        msg.arg1 = verificationId;
16036                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16037                                    }
16038                                }, null, 0, null, null);
16039
16040                        /*
16041                         * We don't want the copy to proceed until verification
16042                         * succeeds, so null out this field.
16043                         */
16044                        mArgs = null;
16045                    }
16046                } else {
16047                    /*
16048                     * No package verification is enabled, so immediately start
16049                     * the remote call to initiate copy using temporary file.
16050                     */
16051                    ret = args.copyApk(mContainerService, true);
16052                }
16053            }
16054
16055            mRet = ret;
16056        }
16057
16058        @Override
16059        void handleReturnCode() {
16060            // If mArgs is null, then MCS couldn't be reached. When it
16061            // reconnects, it will try again to install. At that point, this
16062            // will succeed.
16063            if (mArgs != null) {
16064                processPendingInstall(mArgs, mRet);
16065            }
16066        }
16067
16068        @Override
16069        void handleServiceError() {
16070            mArgs = createInstallArgs(this);
16071            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16072        }
16073
16074        public boolean isForwardLocked() {
16075            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16076        }
16077    }
16078
16079    /**
16080     * Used during creation of InstallArgs
16081     *
16082     * @param installFlags package installation flags
16083     * @return true if should be installed on external storage
16084     */
16085    private static boolean installOnExternalAsec(int installFlags) {
16086        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16087            return false;
16088        }
16089        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16090            return true;
16091        }
16092        return false;
16093    }
16094
16095    /**
16096     * Used during creation of InstallArgs
16097     *
16098     * @param installFlags package installation flags
16099     * @return true if should be installed as forward locked
16100     */
16101    private static boolean installForwardLocked(int installFlags) {
16102        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16103    }
16104
16105    private InstallArgs createInstallArgs(InstallParams params) {
16106        if (params.move != null) {
16107            return new MoveInstallArgs(params);
16108        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16109            return new AsecInstallArgs(params);
16110        } else {
16111            return new FileInstallArgs(params);
16112        }
16113    }
16114
16115    /**
16116     * Create args that describe an existing installed package. Typically used
16117     * when cleaning up old installs, or used as a move source.
16118     */
16119    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16120            String resourcePath, String[] instructionSets) {
16121        final boolean isInAsec;
16122        if (installOnExternalAsec(installFlags)) {
16123            /* Apps on SD card are always in ASEC containers. */
16124            isInAsec = true;
16125        } else if (installForwardLocked(installFlags)
16126                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16127            /*
16128             * Forward-locked apps are only in ASEC containers if they're the
16129             * new style
16130             */
16131            isInAsec = true;
16132        } else {
16133            isInAsec = false;
16134        }
16135
16136        if (isInAsec) {
16137            return new AsecInstallArgs(codePath, instructionSets,
16138                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16139        } else {
16140            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16141        }
16142    }
16143
16144    static abstract class InstallArgs {
16145        /** @see InstallParams#origin */
16146        final OriginInfo origin;
16147        /** @see InstallParams#move */
16148        final MoveInfo move;
16149
16150        final IPackageInstallObserver2 observer;
16151        // Always refers to PackageManager flags only
16152        final int installFlags;
16153        final String installerPackageName;
16154        final String volumeUuid;
16155        final UserHandle user;
16156        final String abiOverride;
16157        final String[] installGrantPermissions;
16158        /** If non-null, drop an async trace when the install completes */
16159        final String traceMethod;
16160        final int traceCookie;
16161        final Certificate[][] certificates;
16162        final int installReason;
16163
16164        // The list of instruction sets supported by this app. This is currently
16165        // only used during the rmdex() phase to clean up resources. We can get rid of this
16166        // if we move dex files under the common app path.
16167        /* nullable */ String[] instructionSets;
16168
16169        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16170                int installFlags, String installerPackageName, String volumeUuid,
16171                UserHandle user, String[] instructionSets,
16172                String abiOverride, String[] installGrantPermissions,
16173                String traceMethod, int traceCookie, Certificate[][] certificates,
16174                int installReason) {
16175            this.origin = origin;
16176            this.move = move;
16177            this.installFlags = installFlags;
16178            this.observer = observer;
16179            this.installerPackageName = installerPackageName;
16180            this.volumeUuid = volumeUuid;
16181            this.user = user;
16182            this.instructionSets = instructionSets;
16183            this.abiOverride = abiOverride;
16184            this.installGrantPermissions = installGrantPermissions;
16185            this.traceMethod = traceMethod;
16186            this.traceCookie = traceCookie;
16187            this.certificates = certificates;
16188            this.installReason = installReason;
16189        }
16190
16191        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16192        abstract int doPreInstall(int status);
16193
16194        /**
16195         * Rename package into final resting place. All paths on the given
16196         * scanned package should be updated to reflect the rename.
16197         */
16198        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16199        abstract int doPostInstall(int status, int uid);
16200
16201        /** @see PackageSettingBase#codePathString */
16202        abstract String getCodePath();
16203        /** @see PackageSettingBase#resourcePathString */
16204        abstract String getResourcePath();
16205
16206        // Need installer lock especially for dex file removal.
16207        abstract void cleanUpResourcesLI();
16208        abstract boolean doPostDeleteLI(boolean delete);
16209
16210        /**
16211         * Called before the source arguments are copied. This is used mostly
16212         * for MoveParams when it needs to read the source file to put it in the
16213         * destination.
16214         */
16215        int doPreCopy() {
16216            return PackageManager.INSTALL_SUCCEEDED;
16217        }
16218
16219        /**
16220         * Called after the source arguments are copied. This is used mostly for
16221         * MoveParams when it needs to read the source file to put it in the
16222         * destination.
16223         */
16224        int doPostCopy(int uid) {
16225            return PackageManager.INSTALL_SUCCEEDED;
16226        }
16227
16228        protected boolean isFwdLocked() {
16229            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16230        }
16231
16232        protected boolean isExternalAsec() {
16233            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16234        }
16235
16236        protected boolean isEphemeral() {
16237            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16238        }
16239
16240        UserHandle getUser() {
16241            return user;
16242        }
16243    }
16244
16245    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16246        if (!allCodePaths.isEmpty()) {
16247            if (instructionSets == null) {
16248                throw new IllegalStateException("instructionSet == null");
16249            }
16250            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16251            for (String codePath : allCodePaths) {
16252                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16253                    try {
16254                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16255                    } catch (InstallerException ignored) {
16256                    }
16257                }
16258            }
16259        }
16260    }
16261
16262    /**
16263     * Logic to handle installation of non-ASEC applications, including copying
16264     * and renaming logic.
16265     */
16266    class FileInstallArgs extends InstallArgs {
16267        private File codeFile;
16268        private File resourceFile;
16269
16270        // Example topology:
16271        // /data/app/com.example/base.apk
16272        // /data/app/com.example/split_foo.apk
16273        // /data/app/com.example/lib/arm/libfoo.so
16274        // /data/app/com.example/lib/arm64/libfoo.so
16275        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16276
16277        /** New install */
16278        FileInstallArgs(InstallParams params) {
16279            super(params.origin, params.move, params.observer, params.installFlags,
16280                    params.installerPackageName, params.volumeUuid,
16281                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16282                    params.grantedRuntimePermissions,
16283                    params.traceMethod, params.traceCookie, params.certificates,
16284                    params.installReason);
16285            if (isFwdLocked()) {
16286                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16287            }
16288        }
16289
16290        /** Existing install */
16291        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16292            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16293                    null, null, null, 0, null /*certificates*/,
16294                    PackageManager.INSTALL_REASON_UNKNOWN);
16295            this.codeFile = (codePath != null) ? new File(codePath) : null;
16296            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16297        }
16298
16299        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16300            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16301            try {
16302                return doCopyApk(imcs, temp);
16303            } finally {
16304                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16305            }
16306        }
16307
16308        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16309            if (origin.staged) {
16310                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16311                codeFile = origin.file;
16312                resourceFile = origin.file;
16313                return PackageManager.INSTALL_SUCCEEDED;
16314            }
16315
16316            try {
16317                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16318                final File tempDir =
16319                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16320                codeFile = tempDir;
16321                resourceFile = tempDir;
16322            } catch (IOException e) {
16323                Slog.w(TAG, "Failed to create copy file: " + e);
16324                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16325            }
16326
16327            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16328                @Override
16329                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16330                    if (!FileUtils.isValidExtFilename(name)) {
16331                        throw new IllegalArgumentException("Invalid filename: " + name);
16332                    }
16333                    try {
16334                        final File file = new File(codeFile, name);
16335                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16336                                O_RDWR | O_CREAT, 0644);
16337                        Os.chmod(file.getAbsolutePath(), 0644);
16338                        return new ParcelFileDescriptor(fd);
16339                    } catch (ErrnoException e) {
16340                        throw new RemoteException("Failed to open: " + e.getMessage());
16341                    }
16342                }
16343            };
16344
16345            int ret = PackageManager.INSTALL_SUCCEEDED;
16346            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16347            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16348                Slog.e(TAG, "Failed to copy package");
16349                return ret;
16350            }
16351
16352            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16353            NativeLibraryHelper.Handle handle = null;
16354            try {
16355                handle = NativeLibraryHelper.Handle.create(codeFile);
16356                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16357                        abiOverride);
16358            } catch (IOException e) {
16359                Slog.e(TAG, "Copying native libraries failed", e);
16360                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16361            } finally {
16362                IoUtils.closeQuietly(handle);
16363            }
16364
16365            return ret;
16366        }
16367
16368        int doPreInstall(int status) {
16369            if (status != PackageManager.INSTALL_SUCCEEDED) {
16370                cleanUp();
16371            }
16372            return status;
16373        }
16374
16375        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16376            if (status != PackageManager.INSTALL_SUCCEEDED) {
16377                cleanUp();
16378                return false;
16379            }
16380
16381            final File targetDir = codeFile.getParentFile();
16382            final File beforeCodeFile = codeFile;
16383            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16384
16385            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16386            try {
16387                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16388            } catch (ErrnoException e) {
16389                Slog.w(TAG, "Failed to rename", e);
16390                return false;
16391            }
16392
16393            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16394                Slog.w(TAG, "Failed to restorecon");
16395                return false;
16396            }
16397
16398            // Reflect the rename internally
16399            codeFile = afterCodeFile;
16400            resourceFile = afterCodeFile;
16401
16402            // Reflect the rename in scanned details
16403            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16404            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16405                    afterCodeFile, pkg.baseCodePath));
16406            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16407                    afterCodeFile, pkg.splitCodePaths));
16408
16409            // Reflect the rename in app info
16410            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16411            pkg.setApplicationInfoCodePath(pkg.codePath);
16412            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16413            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16414            pkg.setApplicationInfoResourcePath(pkg.codePath);
16415            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16416            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16417
16418            return true;
16419        }
16420
16421        int doPostInstall(int status, int uid) {
16422            if (status != PackageManager.INSTALL_SUCCEEDED) {
16423                cleanUp();
16424            }
16425            return status;
16426        }
16427
16428        @Override
16429        String getCodePath() {
16430            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16431        }
16432
16433        @Override
16434        String getResourcePath() {
16435            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16436        }
16437
16438        private boolean cleanUp() {
16439            if (codeFile == null || !codeFile.exists()) {
16440                return false;
16441            }
16442
16443            removeCodePathLI(codeFile);
16444
16445            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16446                resourceFile.delete();
16447            }
16448
16449            return true;
16450        }
16451
16452        void cleanUpResourcesLI() {
16453            // Try enumerating all code paths before deleting
16454            List<String> allCodePaths = Collections.EMPTY_LIST;
16455            if (codeFile != null && codeFile.exists()) {
16456                try {
16457                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16458                    allCodePaths = pkg.getAllCodePaths();
16459                } catch (PackageParserException e) {
16460                    // Ignored; we tried our best
16461                }
16462            }
16463
16464            cleanUp();
16465            removeDexFiles(allCodePaths, instructionSets);
16466        }
16467
16468        boolean doPostDeleteLI(boolean delete) {
16469            // XXX err, shouldn't we respect the delete flag?
16470            cleanUpResourcesLI();
16471            return true;
16472        }
16473    }
16474
16475    private boolean isAsecExternal(String cid) {
16476        final String asecPath = PackageHelper.getSdFilesystem(cid);
16477        return !asecPath.startsWith(mAsecInternalPath);
16478    }
16479
16480    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16481            PackageManagerException {
16482        if (copyRet < 0) {
16483            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16484                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16485                throw new PackageManagerException(copyRet, message);
16486            }
16487        }
16488    }
16489
16490    /**
16491     * Extract the StorageManagerService "container ID" from the full code path of an
16492     * .apk.
16493     */
16494    static String cidFromCodePath(String fullCodePath) {
16495        int eidx = fullCodePath.lastIndexOf("/");
16496        String subStr1 = fullCodePath.substring(0, eidx);
16497        int sidx = subStr1.lastIndexOf("/");
16498        return subStr1.substring(sidx+1, eidx);
16499    }
16500
16501    /**
16502     * Logic to handle installation of ASEC applications, including copying and
16503     * renaming logic.
16504     */
16505    class AsecInstallArgs extends InstallArgs {
16506        static final String RES_FILE_NAME = "pkg.apk";
16507        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16508
16509        String cid;
16510        String packagePath;
16511        String resourcePath;
16512
16513        /** New install */
16514        AsecInstallArgs(InstallParams params) {
16515            super(params.origin, params.move, params.observer, params.installFlags,
16516                    params.installerPackageName, params.volumeUuid,
16517                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16518                    params.grantedRuntimePermissions,
16519                    params.traceMethod, params.traceCookie, params.certificates,
16520                    params.installReason);
16521        }
16522
16523        /** Existing install */
16524        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16525                        boolean isExternal, boolean isForwardLocked) {
16526            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16527                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16528                    instructionSets, null, null, null, 0, null /*certificates*/,
16529                    PackageManager.INSTALL_REASON_UNKNOWN);
16530            // Hackily pretend we're still looking at a full code path
16531            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16532                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16533            }
16534
16535            // Extract cid from fullCodePath
16536            int eidx = fullCodePath.lastIndexOf("/");
16537            String subStr1 = fullCodePath.substring(0, eidx);
16538            int sidx = subStr1.lastIndexOf("/");
16539            cid = subStr1.substring(sidx+1, eidx);
16540            setMountPath(subStr1);
16541        }
16542
16543        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16544            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16545                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16546                    instructionSets, null, null, null, 0, null /*certificates*/,
16547                    PackageManager.INSTALL_REASON_UNKNOWN);
16548            this.cid = cid;
16549            setMountPath(PackageHelper.getSdDir(cid));
16550        }
16551
16552        void createCopyFile() {
16553            cid = mInstallerService.allocateExternalStageCidLegacy();
16554        }
16555
16556        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16557            if (origin.staged && origin.cid != null) {
16558                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16559                cid = origin.cid;
16560                setMountPath(PackageHelper.getSdDir(cid));
16561                return PackageManager.INSTALL_SUCCEEDED;
16562            }
16563
16564            if (temp) {
16565                createCopyFile();
16566            } else {
16567                /*
16568                 * Pre-emptively destroy the container since it's destroyed if
16569                 * copying fails due to it existing anyway.
16570                 */
16571                PackageHelper.destroySdDir(cid);
16572            }
16573
16574            final String newMountPath = imcs.copyPackageToContainer(
16575                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16576                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16577
16578            if (newMountPath != null) {
16579                setMountPath(newMountPath);
16580                return PackageManager.INSTALL_SUCCEEDED;
16581            } else {
16582                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16583            }
16584        }
16585
16586        @Override
16587        String getCodePath() {
16588            return packagePath;
16589        }
16590
16591        @Override
16592        String getResourcePath() {
16593            return resourcePath;
16594        }
16595
16596        int doPreInstall(int status) {
16597            if (status != PackageManager.INSTALL_SUCCEEDED) {
16598                // Destroy container
16599                PackageHelper.destroySdDir(cid);
16600            } else {
16601                boolean mounted = PackageHelper.isContainerMounted(cid);
16602                if (!mounted) {
16603                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16604                            Process.SYSTEM_UID);
16605                    if (newMountPath != null) {
16606                        setMountPath(newMountPath);
16607                    } else {
16608                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16609                    }
16610                }
16611            }
16612            return status;
16613        }
16614
16615        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16616            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16617            String newMountPath = null;
16618            if (PackageHelper.isContainerMounted(cid)) {
16619                // Unmount the container
16620                if (!PackageHelper.unMountSdDir(cid)) {
16621                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16622                    return false;
16623                }
16624            }
16625            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16626                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16627                        " which might be stale. Will try to clean up.");
16628                // Clean up the stale container and proceed to recreate.
16629                if (!PackageHelper.destroySdDir(newCacheId)) {
16630                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16631                    return false;
16632                }
16633                // Successfully cleaned up stale container. Try to rename again.
16634                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16635                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16636                            + " inspite of cleaning it up.");
16637                    return false;
16638                }
16639            }
16640            if (!PackageHelper.isContainerMounted(newCacheId)) {
16641                Slog.w(TAG, "Mounting container " + newCacheId);
16642                newMountPath = PackageHelper.mountSdDir(newCacheId,
16643                        getEncryptKey(), Process.SYSTEM_UID);
16644            } else {
16645                newMountPath = PackageHelper.getSdDir(newCacheId);
16646            }
16647            if (newMountPath == null) {
16648                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16649                return false;
16650            }
16651            Log.i(TAG, "Succesfully renamed " + cid +
16652                    " to " + newCacheId +
16653                    " at new path: " + newMountPath);
16654            cid = newCacheId;
16655
16656            final File beforeCodeFile = new File(packagePath);
16657            setMountPath(newMountPath);
16658            final File afterCodeFile = new File(packagePath);
16659
16660            // Reflect the rename in scanned details
16661            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16662            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16663                    afterCodeFile, pkg.baseCodePath));
16664            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16665                    afterCodeFile, pkg.splitCodePaths));
16666
16667            // Reflect the rename in app info
16668            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16669            pkg.setApplicationInfoCodePath(pkg.codePath);
16670            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16671            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16672            pkg.setApplicationInfoResourcePath(pkg.codePath);
16673            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16674            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16675
16676            return true;
16677        }
16678
16679        private void setMountPath(String mountPath) {
16680            final File mountFile = new File(mountPath);
16681
16682            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16683            if (monolithicFile.exists()) {
16684                packagePath = monolithicFile.getAbsolutePath();
16685                if (isFwdLocked()) {
16686                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16687                } else {
16688                    resourcePath = packagePath;
16689                }
16690            } else {
16691                packagePath = mountFile.getAbsolutePath();
16692                resourcePath = packagePath;
16693            }
16694        }
16695
16696        int doPostInstall(int status, int uid) {
16697            if (status != PackageManager.INSTALL_SUCCEEDED) {
16698                cleanUp();
16699            } else {
16700                final int groupOwner;
16701                final String protectedFile;
16702                if (isFwdLocked()) {
16703                    groupOwner = UserHandle.getSharedAppGid(uid);
16704                    protectedFile = RES_FILE_NAME;
16705                } else {
16706                    groupOwner = -1;
16707                    protectedFile = null;
16708                }
16709
16710                if (uid < Process.FIRST_APPLICATION_UID
16711                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16712                    Slog.e(TAG, "Failed to finalize " + cid);
16713                    PackageHelper.destroySdDir(cid);
16714                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16715                }
16716
16717                boolean mounted = PackageHelper.isContainerMounted(cid);
16718                if (!mounted) {
16719                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16720                }
16721            }
16722            return status;
16723        }
16724
16725        private void cleanUp() {
16726            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16727
16728            // Destroy secure container
16729            PackageHelper.destroySdDir(cid);
16730        }
16731
16732        private List<String> getAllCodePaths() {
16733            final File codeFile = new File(getCodePath());
16734            if (codeFile != null && codeFile.exists()) {
16735                try {
16736                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16737                    return pkg.getAllCodePaths();
16738                } catch (PackageParserException e) {
16739                    // Ignored; we tried our best
16740                }
16741            }
16742            return Collections.EMPTY_LIST;
16743        }
16744
16745        void cleanUpResourcesLI() {
16746            // Enumerate all code paths before deleting
16747            cleanUpResourcesLI(getAllCodePaths());
16748        }
16749
16750        private void cleanUpResourcesLI(List<String> allCodePaths) {
16751            cleanUp();
16752            removeDexFiles(allCodePaths, instructionSets);
16753        }
16754
16755        String getPackageName() {
16756            return getAsecPackageName(cid);
16757        }
16758
16759        boolean doPostDeleteLI(boolean delete) {
16760            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16761            final List<String> allCodePaths = getAllCodePaths();
16762            boolean mounted = PackageHelper.isContainerMounted(cid);
16763            if (mounted) {
16764                // Unmount first
16765                if (PackageHelper.unMountSdDir(cid)) {
16766                    mounted = false;
16767                }
16768            }
16769            if (!mounted && delete) {
16770                cleanUpResourcesLI(allCodePaths);
16771            }
16772            return !mounted;
16773        }
16774
16775        @Override
16776        int doPreCopy() {
16777            if (isFwdLocked()) {
16778                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16779                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16780                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16781                }
16782            }
16783
16784            return PackageManager.INSTALL_SUCCEEDED;
16785        }
16786
16787        @Override
16788        int doPostCopy(int uid) {
16789            if (isFwdLocked()) {
16790                if (uid < Process.FIRST_APPLICATION_UID
16791                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16792                                RES_FILE_NAME)) {
16793                    Slog.e(TAG, "Failed to finalize " + cid);
16794                    PackageHelper.destroySdDir(cid);
16795                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16796                }
16797            }
16798
16799            return PackageManager.INSTALL_SUCCEEDED;
16800        }
16801    }
16802
16803    /**
16804     * Logic to handle movement of existing installed applications.
16805     */
16806    class MoveInstallArgs extends InstallArgs {
16807        private File codeFile;
16808        private File resourceFile;
16809
16810        /** New install */
16811        MoveInstallArgs(InstallParams params) {
16812            super(params.origin, params.move, params.observer, params.installFlags,
16813                    params.installerPackageName, params.volumeUuid,
16814                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16815                    params.grantedRuntimePermissions,
16816                    params.traceMethod, params.traceCookie, params.certificates,
16817                    params.installReason);
16818        }
16819
16820        int copyApk(IMediaContainerService imcs, boolean temp) {
16821            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16822                    + move.fromUuid + " to " + move.toUuid);
16823            synchronized (mInstaller) {
16824                try {
16825                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16826                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16827                } catch (InstallerException e) {
16828                    Slog.w(TAG, "Failed to move app", e);
16829                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16830                }
16831            }
16832
16833            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16834            resourceFile = codeFile;
16835            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16836
16837            return PackageManager.INSTALL_SUCCEEDED;
16838        }
16839
16840        int doPreInstall(int status) {
16841            if (status != PackageManager.INSTALL_SUCCEEDED) {
16842                cleanUp(move.toUuid);
16843            }
16844            return status;
16845        }
16846
16847        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16848            if (status != PackageManager.INSTALL_SUCCEEDED) {
16849                cleanUp(move.toUuid);
16850                return false;
16851            }
16852
16853            // Reflect the move in app info
16854            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16855            pkg.setApplicationInfoCodePath(pkg.codePath);
16856            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16857            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16858            pkg.setApplicationInfoResourcePath(pkg.codePath);
16859            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16860            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16861
16862            return true;
16863        }
16864
16865        int doPostInstall(int status, int uid) {
16866            if (status == PackageManager.INSTALL_SUCCEEDED) {
16867                cleanUp(move.fromUuid);
16868            } else {
16869                cleanUp(move.toUuid);
16870            }
16871            return status;
16872        }
16873
16874        @Override
16875        String getCodePath() {
16876            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16877        }
16878
16879        @Override
16880        String getResourcePath() {
16881            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16882        }
16883
16884        private boolean cleanUp(String volumeUuid) {
16885            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16886                    move.dataAppName);
16887            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16888            final int[] userIds = sUserManager.getUserIds();
16889            synchronized (mInstallLock) {
16890                // Clean up both app data and code
16891                // All package moves are frozen until finished
16892                for (int userId : userIds) {
16893                    try {
16894                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16895                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16896                    } catch (InstallerException e) {
16897                        Slog.w(TAG, String.valueOf(e));
16898                    }
16899                }
16900                removeCodePathLI(codeFile);
16901            }
16902            return true;
16903        }
16904
16905        void cleanUpResourcesLI() {
16906            throw new UnsupportedOperationException();
16907        }
16908
16909        boolean doPostDeleteLI(boolean delete) {
16910            throw new UnsupportedOperationException();
16911        }
16912    }
16913
16914    static String getAsecPackageName(String packageCid) {
16915        int idx = packageCid.lastIndexOf("-");
16916        if (idx == -1) {
16917            return packageCid;
16918        }
16919        return packageCid.substring(0, idx);
16920    }
16921
16922    // Utility method used to create code paths based on package name and available index.
16923    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16924        String idxStr = "";
16925        int idx = 1;
16926        // Fall back to default value of idx=1 if prefix is not
16927        // part of oldCodePath
16928        if (oldCodePath != null) {
16929            String subStr = oldCodePath;
16930            // Drop the suffix right away
16931            if (suffix != null && subStr.endsWith(suffix)) {
16932                subStr = subStr.substring(0, subStr.length() - suffix.length());
16933            }
16934            // If oldCodePath already contains prefix find out the
16935            // ending index to either increment or decrement.
16936            int sidx = subStr.lastIndexOf(prefix);
16937            if (sidx != -1) {
16938                subStr = subStr.substring(sidx + prefix.length());
16939                if (subStr != null) {
16940                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16941                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16942                    }
16943                    try {
16944                        idx = Integer.parseInt(subStr);
16945                        if (idx <= 1) {
16946                            idx++;
16947                        } else {
16948                            idx--;
16949                        }
16950                    } catch(NumberFormatException e) {
16951                    }
16952                }
16953            }
16954        }
16955        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16956        return prefix + idxStr;
16957    }
16958
16959    private File getNextCodePath(File targetDir, String packageName) {
16960        File result;
16961        SecureRandom random = new SecureRandom();
16962        byte[] bytes = new byte[16];
16963        do {
16964            random.nextBytes(bytes);
16965            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16966            result = new File(targetDir, packageName + "-" + suffix);
16967        } while (result.exists());
16968        return result;
16969    }
16970
16971    // Utility method that returns the relative package path with respect
16972    // to the installation directory. Like say for /data/data/com.test-1.apk
16973    // string com.test-1 is returned.
16974    static String deriveCodePathName(String codePath) {
16975        if (codePath == null) {
16976            return null;
16977        }
16978        final File codeFile = new File(codePath);
16979        final String name = codeFile.getName();
16980        if (codeFile.isDirectory()) {
16981            return name;
16982        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16983            final int lastDot = name.lastIndexOf('.');
16984            return name.substring(0, lastDot);
16985        } else {
16986            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16987            return null;
16988        }
16989    }
16990
16991    static class PackageInstalledInfo {
16992        String name;
16993        int uid;
16994        // The set of users that originally had this package installed.
16995        int[] origUsers;
16996        // The set of users that now have this package installed.
16997        int[] newUsers;
16998        PackageParser.Package pkg;
16999        int returnCode;
17000        String returnMsg;
17001        PackageRemovedInfo removedInfo;
17002        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17003
17004        public void setError(int code, String msg) {
17005            setReturnCode(code);
17006            setReturnMessage(msg);
17007            Slog.w(TAG, msg);
17008        }
17009
17010        public void setError(String msg, PackageParserException e) {
17011            setReturnCode(e.error);
17012            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17013            Slog.w(TAG, msg, e);
17014        }
17015
17016        public void setError(String msg, PackageManagerException e) {
17017            returnCode = e.error;
17018            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17019            Slog.w(TAG, msg, e);
17020        }
17021
17022        public void setReturnCode(int returnCode) {
17023            this.returnCode = returnCode;
17024            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17025            for (int i = 0; i < childCount; i++) {
17026                addedChildPackages.valueAt(i).returnCode = returnCode;
17027            }
17028        }
17029
17030        private void setReturnMessage(String returnMsg) {
17031            this.returnMsg = returnMsg;
17032            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17033            for (int i = 0; i < childCount; i++) {
17034                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17035            }
17036        }
17037
17038        // In some error cases we want to convey more info back to the observer
17039        String origPackage;
17040        String origPermission;
17041    }
17042
17043    /*
17044     * Install a non-existing package.
17045     */
17046    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17047            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17048            PackageInstalledInfo res, int installReason) {
17049        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17050
17051        // Remember this for later, in case we need to rollback this install
17052        String pkgName = pkg.packageName;
17053
17054        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17055
17056        synchronized(mPackages) {
17057            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17058            if (renamedPackage != null) {
17059                // A package with the same name is already installed, though
17060                // it has been renamed to an older name.  The package we
17061                // are trying to install should be installed as an update to
17062                // the existing one, but that has not been requested, so bail.
17063                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17064                        + " without first uninstalling package running as "
17065                        + renamedPackage);
17066                return;
17067            }
17068            if (mPackages.containsKey(pkgName)) {
17069                // Don't allow installation over an existing package with the same name.
17070                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17071                        + " without first uninstalling.");
17072                return;
17073            }
17074        }
17075
17076        try {
17077            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17078                    System.currentTimeMillis(), user);
17079
17080            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17081
17082            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17083                prepareAppDataAfterInstallLIF(newPackage);
17084
17085            } else {
17086                // Remove package from internal structures, but keep around any
17087                // data that might have already existed
17088                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17089                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17090            }
17091        } catch (PackageManagerException e) {
17092            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17093        }
17094
17095        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17096    }
17097
17098    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17099        // Can't rotate keys during boot or if sharedUser.
17100        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17101                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17102            return false;
17103        }
17104        // app is using upgradeKeySets; make sure all are valid
17105        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17106        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17107        for (int i = 0; i < upgradeKeySets.length; i++) {
17108            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17109                Slog.wtf(TAG, "Package "
17110                         + (oldPs.name != null ? oldPs.name : "<null>")
17111                         + " contains upgrade-key-set reference to unknown key-set: "
17112                         + upgradeKeySets[i]
17113                         + " reverting to signatures check.");
17114                return false;
17115            }
17116        }
17117        return true;
17118    }
17119
17120    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17121        // Upgrade keysets are being used.  Determine if new package has a superset of the
17122        // required keys.
17123        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17124        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17125        for (int i = 0; i < upgradeKeySets.length; i++) {
17126            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17127            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17128                return true;
17129            }
17130        }
17131        return false;
17132    }
17133
17134    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17135        try (DigestInputStream digestStream =
17136                new DigestInputStream(new FileInputStream(file), digest)) {
17137            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17138        }
17139    }
17140
17141    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17142            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17143            int installReason) {
17144        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17145
17146        final PackageParser.Package oldPackage;
17147        final PackageSetting ps;
17148        final String pkgName = pkg.packageName;
17149        final int[] allUsers;
17150        final int[] installedUsers;
17151
17152        synchronized(mPackages) {
17153            oldPackage = mPackages.get(pkgName);
17154            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17155
17156            // don't allow upgrade to target a release SDK from a pre-release SDK
17157            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17158                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17159            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17160                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17161            if (oldTargetsPreRelease
17162                    && !newTargetsPreRelease
17163                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17164                Slog.w(TAG, "Can't install package targeting released sdk");
17165                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17166                return;
17167            }
17168
17169            ps = mSettings.mPackages.get(pkgName);
17170
17171            // verify signatures are valid
17172            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17173                if (!checkUpgradeKeySetLP(ps, pkg)) {
17174                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17175                            "New package not signed by keys specified by upgrade-keysets: "
17176                                    + pkgName);
17177                    return;
17178                }
17179            } else {
17180                // default to original signature matching
17181                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17182                        != PackageManager.SIGNATURE_MATCH) {
17183                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17184                            "New package has a different signature: " + pkgName);
17185                    return;
17186                }
17187            }
17188
17189            // don't allow a system upgrade unless the upgrade hash matches
17190            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17191                byte[] digestBytes = null;
17192                try {
17193                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17194                    updateDigest(digest, new File(pkg.baseCodePath));
17195                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17196                        for (String path : pkg.splitCodePaths) {
17197                            updateDigest(digest, new File(path));
17198                        }
17199                    }
17200                    digestBytes = digest.digest();
17201                } catch (NoSuchAlgorithmException | IOException e) {
17202                    res.setError(INSTALL_FAILED_INVALID_APK,
17203                            "Could not compute hash: " + pkgName);
17204                    return;
17205                }
17206                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17207                    res.setError(INSTALL_FAILED_INVALID_APK,
17208                            "New package fails restrict-update check: " + pkgName);
17209                    return;
17210                }
17211                // retain upgrade restriction
17212                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17213            }
17214
17215            // Check for shared user id changes
17216            String invalidPackageName =
17217                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17218            if (invalidPackageName != null) {
17219                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17220                        "Package " + invalidPackageName + " tried to change user "
17221                                + oldPackage.mSharedUserId);
17222                return;
17223            }
17224
17225            // In case of rollback, remember per-user/profile install state
17226            allUsers = sUserManager.getUserIds();
17227            installedUsers = ps.queryInstalledUsers(allUsers, true);
17228
17229            // don't allow an upgrade from full to ephemeral
17230            if (isInstantApp) {
17231                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17232                    for (int currentUser : allUsers) {
17233                        if (!ps.getInstantApp(currentUser)) {
17234                            // can't downgrade from full to instant
17235                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17236                                    + " for user: " + currentUser);
17237                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17238                            return;
17239                        }
17240                    }
17241                } else if (!ps.getInstantApp(user.getIdentifier())) {
17242                    // can't downgrade from full to instant
17243                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17244                            + " for user: " + user.getIdentifier());
17245                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17246                    return;
17247                }
17248            }
17249        }
17250
17251        // Update what is removed
17252        res.removedInfo = new PackageRemovedInfo(this);
17253        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17254        res.removedInfo.removedPackage = oldPackage.packageName;
17255        res.removedInfo.installerPackageName = ps.installerPackageName;
17256        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17257        res.removedInfo.isUpdate = true;
17258        res.removedInfo.origUsers = installedUsers;
17259        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17260        for (int i = 0; i < installedUsers.length; i++) {
17261            final int userId = installedUsers[i];
17262            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17263        }
17264
17265        final int childCount = (oldPackage.childPackages != null)
17266                ? oldPackage.childPackages.size() : 0;
17267        for (int i = 0; i < childCount; i++) {
17268            boolean childPackageUpdated = false;
17269            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17270            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17271            if (res.addedChildPackages != null) {
17272                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17273                if (childRes != null) {
17274                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17275                    childRes.removedInfo.removedPackage = childPkg.packageName;
17276                    if (childPs != null) {
17277                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17278                    }
17279                    childRes.removedInfo.isUpdate = true;
17280                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17281                    childPackageUpdated = true;
17282                }
17283            }
17284            if (!childPackageUpdated) {
17285                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17286                childRemovedRes.removedPackage = childPkg.packageName;
17287                if (childPs != null) {
17288                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17289                }
17290                childRemovedRes.isUpdate = false;
17291                childRemovedRes.dataRemoved = true;
17292                synchronized (mPackages) {
17293                    if (childPs != null) {
17294                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17295                    }
17296                }
17297                if (res.removedInfo.removedChildPackages == null) {
17298                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17299                }
17300                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17301            }
17302        }
17303
17304        boolean sysPkg = (isSystemApp(oldPackage));
17305        if (sysPkg) {
17306            // Set the system/privileged flags as needed
17307            final boolean privileged =
17308                    (oldPackage.applicationInfo.privateFlags
17309                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17310            final int systemPolicyFlags = policyFlags
17311                    | PackageParser.PARSE_IS_SYSTEM
17312                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17313
17314            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17315                    user, allUsers, installerPackageName, res, installReason);
17316        } else {
17317            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17318                    user, allUsers, installerPackageName, res, installReason);
17319        }
17320    }
17321
17322    @Override
17323    public List<String> getPreviousCodePaths(String packageName) {
17324        final int callingUid = Binder.getCallingUid();
17325        final List<String> result = new ArrayList<>();
17326        if (getInstantAppPackageName(callingUid) != null) {
17327            return result;
17328        }
17329        final PackageSetting ps = mSettings.mPackages.get(packageName);
17330        if (ps != null
17331                && ps.oldCodePaths != null
17332                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17333            result.addAll(ps.oldCodePaths);
17334        }
17335        return result;
17336    }
17337
17338    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17339            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17340            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17341            int installReason) {
17342        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17343                + deletedPackage);
17344
17345        String pkgName = deletedPackage.packageName;
17346        boolean deletedPkg = true;
17347        boolean addedPkg = false;
17348        boolean updatedSettings = false;
17349        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17350        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17351                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17352
17353        final long origUpdateTime = (pkg.mExtras != null)
17354                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17355
17356        // First delete the existing package while retaining the data directory
17357        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17358                res.removedInfo, true, pkg)) {
17359            // If the existing package wasn't successfully deleted
17360            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17361            deletedPkg = false;
17362        } else {
17363            // Successfully deleted the old package; proceed with replace.
17364
17365            // If deleted package lived in a container, give users a chance to
17366            // relinquish resources before killing.
17367            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17368                if (DEBUG_INSTALL) {
17369                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17370                }
17371                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17372                final ArrayList<String> pkgList = new ArrayList<String>(1);
17373                pkgList.add(deletedPackage.applicationInfo.packageName);
17374                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17375            }
17376
17377            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17378                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17379            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17380
17381            try {
17382                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17383                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17384                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17385                        installReason);
17386
17387                // Update the in-memory copy of the previous code paths.
17388                PackageSetting ps = mSettings.mPackages.get(pkgName);
17389                if (!killApp) {
17390                    if (ps.oldCodePaths == null) {
17391                        ps.oldCodePaths = new ArraySet<>();
17392                    }
17393                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17394                    if (deletedPackage.splitCodePaths != null) {
17395                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17396                    }
17397                } else {
17398                    ps.oldCodePaths = null;
17399                }
17400                if (ps.childPackageNames != null) {
17401                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17402                        final String childPkgName = ps.childPackageNames.get(i);
17403                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17404                        childPs.oldCodePaths = ps.oldCodePaths;
17405                    }
17406                }
17407                // set instant app status, but, only if it's explicitly specified
17408                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17409                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17410                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17411                prepareAppDataAfterInstallLIF(newPackage);
17412                addedPkg = true;
17413                mDexManager.notifyPackageUpdated(newPackage.packageName,
17414                        newPackage.baseCodePath, newPackage.splitCodePaths);
17415            } catch (PackageManagerException e) {
17416                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17417            }
17418        }
17419
17420        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17421            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17422
17423            // Revert all internal state mutations and added folders for the failed install
17424            if (addedPkg) {
17425                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17426                        res.removedInfo, true, null);
17427            }
17428
17429            // Restore the old package
17430            if (deletedPkg) {
17431                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17432                File restoreFile = new File(deletedPackage.codePath);
17433                // Parse old package
17434                boolean oldExternal = isExternal(deletedPackage);
17435                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17436                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17437                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17438                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17439                try {
17440                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17441                            null);
17442                } catch (PackageManagerException e) {
17443                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17444                            + e.getMessage());
17445                    return;
17446                }
17447
17448                synchronized (mPackages) {
17449                    // Ensure the installer package name up to date
17450                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17451
17452                    // Update permissions for restored package
17453                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17454
17455                    mSettings.writeLPr();
17456                }
17457
17458                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17459            }
17460        } else {
17461            synchronized (mPackages) {
17462                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17463                if (ps != null) {
17464                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17465                    if (res.removedInfo.removedChildPackages != null) {
17466                        final int childCount = res.removedInfo.removedChildPackages.size();
17467                        // Iterate in reverse as we may modify the collection
17468                        for (int i = childCount - 1; i >= 0; i--) {
17469                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17470                            if (res.addedChildPackages.containsKey(childPackageName)) {
17471                                res.removedInfo.removedChildPackages.removeAt(i);
17472                            } else {
17473                                PackageRemovedInfo childInfo = res.removedInfo
17474                                        .removedChildPackages.valueAt(i);
17475                                childInfo.removedForAllUsers = mPackages.get(
17476                                        childInfo.removedPackage) == null;
17477                            }
17478                        }
17479                    }
17480                }
17481            }
17482        }
17483    }
17484
17485    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17486            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17487            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17488            int installReason) {
17489        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17490                + ", old=" + deletedPackage);
17491
17492        final boolean disabledSystem;
17493
17494        // Remove existing system package
17495        removePackageLI(deletedPackage, true);
17496
17497        synchronized (mPackages) {
17498            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17499        }
17500        if (!disabledSystem) {
17501            // We didn't need to disable the .apk as a current system package,
17502            // which means we are replacing another update that is already
17503            // installed.  We need to make sure to delete the older one's .apk.
17504            res.removedInfo.args = createInstallArgsForExisting(0,
17505                    deletedPackage.applicationInfo.getCodePath(),
17506                    deletedPackage.applicationInfo.getResourcePath(),
17507                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17508        } else {
17509            res.removedInfo.args = null;
17510        }
17511
17512        // Successfully disabled the old package. Now proceed with re-installation
17513        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17514                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17515        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17516
17517        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17518        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17519                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17520
17521        PackageParser.Package newPackage = null;
17522        try {
17523            // Add the package to the internal data structures
17524            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17525
17526            // Set the update and install times
17527            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17528            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17529                    System.currentTimeMillis());
17530
17531            // Update the package dynamic state if succeeded
17532            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17533                // Now that the install succeeded make sure we remove data
17534                // directories for any child package the update removed.
17535                final int deletedChildCount = (deletedPackage.childPackages != null)
17536                        ? deletedPackage.childPackages.size() : 0;
17537                final int newChildCount = (newPackage.childPackages != null)
17538                        ? newPackage.childPackages.size() : 0;
17539                for (int i = 0; i < deletedChildCount; i++) {
17540                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17541                    boolean childPackageDeleted = true;
17542                    for (int j = 0; j < newChildCount; j++) {
17543                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17544                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17545                            childPackageDeleted = false;
17546                            break;
17547                        }
17548                    }
17549                    if (childPackageDeleted) {
17550                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17551                                deletedChildPkg.packageName);
17552                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17553                            PackageRemovedInfo removedChildRes = res.removedInfo
17554                                    .removedChildPackages.get(deletedChildPkg.packageName);
17555                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17556                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17557                        }
17558                    }
17559                }
17560
17561                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17562                        installReason);
17563                prepareAppDataAfterInstallLIF(newPackage);
17564
17565                mDexManager.notifyPackageUpdated(newPackage.packageName,
17566                            newPackage.baseCodePath, newPackage.splitCodePaths);
17567            }
17568        } catch (PackageManagerException e) {
17569            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17570            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17571        }
17572
17573        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17574            // Re installation failed. Restore old information
17575            // Remove new pkg information
17576            if (newPackage != null) {
17577                removeInstalledPackageLI(newPackage, true);
17578            }
17579            // Add back the old system package
17580            try {
17581                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17582            } catch (PackageManagerException e) {
17583                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17584            }
17585
17586            synchronized (mPackages) {
17587                if (disabledSystem) {
17588                    enableSystemPackageLPw(deletedPackage);
17589                }
17590
17591                // Ensure the installer package name up to date
17592                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17593
17594                // Update permissions for restored package
17595                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17596
17597                mSettings.writeLPr();
17598            }
17599
17600            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17601                    + " after failed upgrade");
17602        }
17603    }
17604
17605    /**
17606     * Checks whether the parent or any of the child packages have a change shared
17607     * user. For a package to be a valid update the shred users of the parent and
17608     * the children should match. We may later support changing child shared users.
17609     * @param oldPkg The updated package.
17610     * @param newPkg The update package.
17611     * @return The shared user that change between the versions.
17612     */
17613    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17614            PackageParser.Package newPkg) {
17615        // Check parent shared user
17616        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17617            return newPkg.packageName;
17618        }
17619        // Check child shared users
17620        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17621        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17622        for (int i = 0; i < newChildCount; i++) {
17623            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17624            // If this child was present, did it have the same shared user?
17625            for (int j = 0; j < oldChildCount; j++) {
17626                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17627                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17628                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17629                    return newChildPkg.packageName;
17630                }
17631            }
17632        }
17633        return null;
17634    }
17635
17636    private void removeNativeBinariesLI(PackageSetting ps) {
17637        // Remove the lib path for the parent package
17638        if (ps != null) {
17639            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17640            // Remove the lib path for the child packages
17641            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17642            for (int i = 0; i < childCount; i++) {
17643                PackageSetting childPs = null;
17644                synchronized (mPackages) {
17645                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17646                }
17647                if (childPs != null) {
17648                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17649                            .legacyNativeLibraryPathString);
17650                }
17651            }
17652        }
17653    }
17654
17655    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17656        // Enable the parent package
17657        mSettings.enableSystemPackageLPw(pkg.packageName);
17658        // Enable the child packages
17659        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17660        for (int i = 0; i < childCount; i++) {
17661            PackageParser.Package childPkg = pkg.childPackages.get(i);
17662            mSettings.enableSystemPackageLPw(childPkg.packageName);
17663        }
17664    }
17665
17666    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17667            PackageParser.Package newPkg) {
17668        // Disable the parent package (parent always replaced)
17669        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17670        // Disable the child packages
17671        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17672        for (int i = 0; i < childCount; i++) {
17673            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17674            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17675            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17676        }
17677        return disabled;
17678    }
17679
17680    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17681            String installerPackageName) {
17682        // Enable the parent package
17683        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17684        // Enable the child packages
17685        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17686        for (int i = 0; i < childCount; i++) {
17687            PackageParser.Package childPkg = pkg.childPackages.get(i);
17688            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17689        }
17690    }
17691
17692    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17693        // Collect all used permissions in the UID
17694        ArraySet<String> usedPermissions = new ArraySet<>();
17695        final int packageCount = su.packages.size();
17696        for (int i = 0; i < packageCount; i++) {
17697            PackageSetting ps = su.packages.valueAt(i);
17698            if (ps.pkg == null) {
17699                continue;
17700            }
17701            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17702            for (int j = 0; j < requestedPermCount; j++) {
17703                String permission = ps.pkg.requestedPermissions.get(j);
17704                BasePermission bp = mSettings.mPermissions.get(permission);
17705                if (bp != null) {
17706                    usedPermissions.add(permission);
17707                }
17708            }
17709        }
17710
17711        PermissionsState permissionsState = su.getPermissionsState();
17712        // Prune install permissions
17713        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17714        final int installPermCount = installPermStates.size();
17715        for (int i = installPermCount - 1; i >= 0;  i--) {
17716            PermissionState permissionState = installPermStates.get(i);
17717            if (!usedPermissions.contains(permissionState.getName())) {
17718                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17719                if (bp != null) {
17720                    permissionsState.revokeInstallPermission(bp);
17721                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17722                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17723                }
17724            }
17725        }
17726
17727        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17728
17729        // Prune runtime permissions
17730        for (int userId : allUserIds) {
17731            List<PermissionState> runtimePermStates = permissionsState
17732                    .getRuntimePermissionStates(userId);
17733            final int runtimePermCount = runtimePermStates.size();
17734            for (int i = runtimePermCount - 1; i >= 0; i--) {
17735                PermissionState permissionState = runtimePermStates.get(i);
17736                if (!usedPermissions.contains(permissionState.getName())) {
17737                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17738                    if (bp != null) {
17739                        permissionsState.revokeRuntimePermission(bp, userId);
17740                        permissionsState.updatePermissionFlags(bp, userId,
17741                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17742                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17743                                runtimePermissionChangedUserIds, userId);
17744                    }
17745                }
17746            }
17747        }
17748
17749        return runtimePermissionChangedUserIds;
17750    }
17751
17752    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17753            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17754        // Update the parent package setting
17755        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17756                res, user, installReason);
17757        // Update the child packages setting
17758        final int childCount = (newPackage.childPackages != null)
17759                ? newPackage.childPackages.size() : 0;
17760        for (int i = 0; i < childCount; i++) {
17761            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17762            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17763            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17764                    childRes.origUsers, childRes, user, installReason);
17765        }
17766    }
17767
17768    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17769            String installerPackageName, int[] allUsers, int[] installedForUsers,
17770            PackageInstalledInfo res, UserHandle user, int installReason) {
17771        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17772
17773        String pkgName = newPackage.packageName;
17774        synchronized (mPackages) {
17775            //write settings. the installStatus will be incomplete at this stage.
17776            //note that the new package setting would have already been
17777            //added to mPackages. It hasn't been persisted yet.
17778            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17779            // TODO: Remove this write? It's also written at the end of this method
17780            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17781            mSettings.writeLPr();
17782            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17783        }
17784
17785        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17786        synchronized (mPackages) {
17787            updatePermissionsLPw(newPackage.packageName, newPackage,
17788                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17789                            ? UPDATE_PERMISSIONS_ALL : 0));
17790            // For system-bundled packages, we assume that installing an upgraded version
17791            // of the package implies that the user actually wants to run that new code,
17792            // so we enable the package.
17793            PackageSetting ps = mSettings.mPackages.get(pkgName);
17794            final int userId = user.getIdentifier();
17795            if (ps != null) {
17796                if (isSystemApp(newPackage)) {
17797                    if (DEBUG_INSTALL) {
17798                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17799                    }
17800                    // Enable system package for requested users
17801                    if (res.origUsers != null) {
17802                        for (int origUserId : res.origUsers) {
17803                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17804                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17805                                        origUserId, installerPackageName);
17806                            }
17807                        }
17808                    }
17809                    // Also convey the prior install/uninstall state
17810                    if (allUsers != null && installedForUsers != null) {
17811                        for (int currentUserId : allUsers) {
17812                            final boolean installed = ArrayUtils.contains(
17813                                    installedForUsers, currentUserId);
17814                            if (DEBUG_INSTALL) {
17815                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17816                            }
17817                            ps.setInstalled(installed, currentUserId);
17818                        }
17819                        // these install state changes will be persisted in the
17820                        // upcoming call to mSettings.writeLPr().
17821                    }
17822                }
17823                // It's implied that when a user requests installation, they want the app to be
17824                // installed and enabled.
17825                if (userId != UserHandle.USER_ALL) {
17826                    ps.setInstalled(true, userId);
17827                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17828                }
17829
17830                // When replacing an existing package, preserve the original install reason for all
17831                // users that had the package installed before.
17832                final Set<Integer> previousUserIds = new ArraySet<>();
17833                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17834                    final int installReasonCount = res.removedInfo.installReasons.size();
17835                    for (int i = 0; i < installReasonCount; i++) {
17836                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17837                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17838                        ps.setInstallReason(previousInstallReason, previousUserId);
17839                        previousUserIds.add(previousUserId);
17840                    }
17841                }
17842
17843                // Set install reason for users that are having the package newly installed.
17844                if (userId == UserHandle.USER_ALL) {
17845                    for (int currentUserId : sUserManager.getUserIds()) {
17846                        if (!previousUserIds.contains(currentUserId)) {
17847                            ps.setInstallReason(installReason, currentUserId);
17848                        }
17849                    }
17850                } else if (!previousUserIds.contains(userId)) {
17851                    ps.setInstallReason(installReason, userId);
17852                }
17853                mSettings.writeKernelMappingLPr(ps);
17854            }
17855            res.name = pkgName;
17856            res.uid = newPackage.applicationInfo.uid;
17857            res.pkg = newPackage;
17858            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17859            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17860            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17861            //to update install status
17862            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17863            mSettings.writeLPr();
17864            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17865        }
17866
17867        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17868    }
17869
17870    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17871        try {
17872            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17873            installPackageLI(args, res);
17874        } finally {
17875            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17876        }
17877    }
17878
17879    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17880        final int installFlags = args.installFlags;
17881        final String installerPackageName = args.installerPackageName;
17882        final String volumeUuid = args.volumeUuid;
17883        final File tmpPackageFile = new File(args.getCodePath());
17884        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17885        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17886                || (args.volumeUuid != null));
17887        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17888        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17889        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17890        boolean replace = false;
17891        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17892        if (args.move != null) {
17893            // moving a complete application; perform an initial scan on the new install location
17894            scanFlags |= SCAN_INITIAL;
17895        }
17896        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17897            scanFlags |= SCAN_DONT_KILL_APP;
17898        }
17899        if (instantApp) {
17900            scanFlags |= SCAN_AS_INSTANT_APP;
17901        }
17902        if (fullApp) {
17903            scanFlags |= SCAN_AS_FULL_APP;
17904        }
17905
17906        // Result object to be returned
17907        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17908
17909        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17910
17911        // Sanity check
17912        if (instantApp && (forwardLocked || onExternal)) {
17913            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17914                    + " external=" + onExternal);
17915            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17916            return;
17917        }
17918
17919        // Retrieve PackageSettings and parse package
17920        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17921                | PackageParser.PARSE_ENFORCE_CODE
17922                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17923                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17924                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17925                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17926        PackageParser pp = new PackageParser();
17927        pp.setSeparateProcesses(mSeparateProcesses);
17928        pp.setDisplayMetrics(mMetrics);
17929        pp.setCallback(mPackageParserCallback);
17930
17931        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17932        final PackageParser.Package pkg;
17933        try {
17934            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17935        } catch (PackageParserException e) {
17936            res.setError("Failed parse during installPackageLI", e);
17937            return;
17938        } finally {
17939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17940        }
17941
17942        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17943        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17944            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17945            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17946                    "Instant app package must target O");
17947            return;
17948        }
17949        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17950            Slog.w(TAG, "Instant app package " + pkg.packageName
17951                    + " does not target targetSandboxVersion 2");
17952            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17953                    "Instant app package must use targetSanboxVersion 2");
17954            return;
17955        }
17956
17957        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17958            // Static shared libraries have synthetic package names
17959            renameStaticSharedLibraryPackage(pkg);
17960
17961            // No static shared libs on external storage
17962            if (onExternal) {
17963                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17964                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17965                        "Packages declaring static-shared libs cannot be updated");
17966                return;
17967            }
17968        }
17969
17970        // If we are installing a clustered package add results for the children
17971        if (pkg.childPackages != null) {
17972            synchronized (mPackages) {
17973                final int childCount = pkg.childPackages.size();
17974                for (int i = 0; i < childCount; i++) {
17975                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17976                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17977                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17978                    childRes.pkg = childPkg;
17979                    childRes.name = childPkg.packageName;
17980                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17981                    if (childPs != null) {
17982                        childRes.origUsers = childPs.queryInstalledUsers(
17983                                sUserManager.getUserIds(), true);
17984                    }
17985                    if ((mPackages.containsKey(childPkg.packageName))) {
17986                        childRes.removedInfo = new PackageRemovedInfo(this);
17987                        childRes.removedInfo.removedPackage = childPkg.packageName;
17988                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17989                    }
17990                    if (res.addedChildPackages == null) {
17991                        res.addedChildPackages = new ArrayMap<>();
17992                    }
17993                    res.addedChildPackages.put(childPkg.packageName, childRes);
17994                }
17995            }
17996        }
17997
17998        // If package doesn't declare API override, mark that we have an install
17999        // time CPU ABI override.
18000        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18001            pkg.cpuAbiOverride = args.abiOverride;
18002        }
18003
18004        String pkgName = res.name = pkg.packageName;
18005        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18006            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18007                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18008                return;
18009            }
18010        }
18011
18012        try {
18013            // either use what we've been given or parse directly from the APK
18014            if (args.certificates != null) {
18015                try {
18016                    PackageParser.populateCertificates(pkg, args.certificates);
18017                } catch (PackageParserException e) {
18018                    // there was something wrong with the certificates we were given;
18019                    // try to pull them from the APK
18020                    PackageParser.collectCertificates(pkg, parseFlags);
18021                }
18022            } else {
18023                PackageParser.collectCertificates(pkg, parseFlags);
18024            }
18025        } catch (PackageParserException e) {
18026            res.setError("Failed collect during installPackageLI", e);
18027            return;
18028        }
18029
18030        // Get rid of all references to package scan path via parser.
18031        pp = null;
18032        String oldCodePath = null;
18033        boolean systemApp = false;
18034        synchronized (mPackages) {
18035            // Check if installing already existing package
18036            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18037                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18038                if (pkg.mOriginalPackages != null
18039                        && pkg.mOriginalPackages.contains(oldName)
18040                        && mPackages.containsKey(oldName)) {
18041                    // This package is derived from an original package,
18042                    // and this device has been updating from that original
18043                    // name.  We must continue using the original name, so
18044                    // rename the new package here.
18045                    pkg.setPackageName(oldName);
18046                    pkgName = pkg.packageName;
18047                    replace = true;
18048                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18049                            + oldName + " pkgName=" + pkgName);
18050                } else if (mPackages.containsKey(pkgName)) {
18051                    // This package, under its official name, already exists
18052                    // on the device; we should replace it.
18053                    replace = true;
18054                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18055                }
18056
18057                // Child packages are installed through the parent package
18058                if (pkg.parentPackage != null) {
18059                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18060                            "Package " + pkg.packageName + " is child of package "
18061                                    + pkg.parentPackage.parentPackage + ". Child packages "
18062                                    + "can be updated only through the parent package.");
18063                    return;
18064                }
18065
18066                if (replace) {
18067                    // Prevent apps opting out from runtime permissions
18068                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18069                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18070                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18071                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18072                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18073                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18074                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18075                                        + " doesn't support runtime permissions but the old"
18076                                        + " target SDK " + oldTargetSdk + " does.");
18077                        return;
18078                    }
18079                    // Prevent apps from downgrading their targetSandbox.
18080                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18081                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18082                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18083                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18084                                "Package " + pkg.packageName + " new target sandbox "
18085                                + newTargetSandbox + " is incompatible with the previous value of"
18086                                + oldTargetSandbox + ".");
18087                        return;
18088                    }
18089
18090                    // Prevent installing of child packages
18091                    if (oldPackage.parentPackage != null) {
18092                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18093                                "Package " + pkg.packageName + " is child of package "
18094                                        + oldPackage.parentPackage + ". Child packages "
18095                                        + "can be updated only through the parent package.");
18096                        return;
18097                    }
18098                }
18099            }
18100
18101            PackageSetting ps = mSettings.mPackages.get(pkgName);
18102            if (ps != null) {
18103                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18104
18105                // Static shared libs have same package with different versions where
18106                // we internally use a synthetic package name to allow multiple versions
18107                // of the same package, therefore we need to compare signatures against
18108                // the package setting for the latest library version.
18109                PackageSetting signatureCheckPs = ps;
18110                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18111                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18112                    if (libraryEntry != null) {
18113                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18114                    }
18115                }
18116
18117                // Quick sanity check that we're signed correctly if updating;
18118                // we'll check this again later when scanning, but we want to
18119                // bail early here before tripping over redefined permissions.
18120                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18121                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18122                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18123                                + pkg.packageName + " upgrade keys do not match the "
18124                                + "previously installed version");
18125                        return;
18126                    }
18127                } else {
18128                    try {
18129                        verifySignaturesLP(signatureCheckPs, pkg);
18130                    } catch (PackageManagerException e) {
18131                        res.setError(e.error, e.getMessage());
18132                        return;
18133                    }
18134                }
18135
18136                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18137                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18138                    systemApp = (ps.pkg.applicationInfo.flags &
18139                            ApplicationInfo.FLAG_SYSTEM) != 0;
18140                }
18141                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18142            }
18143
18144            int N = pkg.permissions.size();
18145            for (int i = N-1; i >= 0; i--) {
18146                PackageParser.Permission perm = pkg.permissions.get(i);
18147                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18148
18149                // Don't allow anyone but the system to define ephemeral permissions.
18150                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18151                        && !systemApp) {
18152                    Slog.w(TAG, "Non-System package " + pkg.packageName
18153                            + " attempting to delcare ephemeral permission "
18154                            + perm.info.name + "; Removing ephemeral.");
18155                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18156                }
18157                // Check whether the newly-scanned package wants to define an already-defined perm
18158                if (bp != null) {
18159                    // If the defining package is signed with our cert, it's okay.  This
18160                    // also includes the "updating the same package" case, of course.
18161                    // "updating same package" could also involve key-rotation.
18162                    final boolean sigsOk;
18163                    if (bp.sourcePackage.equals(pkg.packageName)
18164                            && (bp.packageSetting instanceof PackageSetting)
18165                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18166                                    scanFlags))) {
18167                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18168                    } else {
18169                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18170                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18171                    }
18172                    if (!sigsOk) {
18173                        // If the owning package is the system itself, we log but allow
18174                        // install to proceed; we fail the install on all other permission
18175                        // redefinitions.
18176                        if (!bp.sourcePackage.equals("android")) {
18177                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18178                                    + pkg.packageName + " attempting to redeclare permission "
18179                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18180                            res.origPermission = perm.info.name;
18181                            res.origPackage = bp.sourcePackage;
18182                            return;
18183                        } else {
18184                            Slog.w(TAG, "Package " + pkg.packageName
18185                                    + " attempting to redeclare system permission "
18186                                    + perm.info.name + "; ignoring new declaration");
18187                            pkg.permissions.remove(i);
18188                        }
18189                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18190                        // Prevent apps to change protection level to dangerous from any other
18191                        // type as this would allow a privilege escalation where an app adds a
18192                        // normal/signature permission in other app's group and later redefines
18193                        // it as dangerous leading to the group auto-grant.
18194                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18195                                == PermissionInfo.PROTECTION_DANGEROUS) {
18196                            if (bp != null && !bp.isRuntime()) {
18197                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18198                                        + "non-runtime permission " + perm.info.name
18199                                        + " to runtime; keeping old protection level");
18200                                perm.info.protectionLevel = bp.protectionLevel;
18201                            }
18202                        }
18203                    }
18204                }
18205            }
18206        }
18207
18208        if (systemApp) {
18209            if (onExternal) {
18210                // Abort update; system app can't be replaced with app on sdcard
18211                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18212                        "Cannot install updates to system apps on sdcard");
18213                return;
18214            } else if (instantApp) {
18215                // Abort update; system app can't be replaced with an instant app
18216                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18217                        "Cannot update a system app with an instant app");
18218                return;
18219            }
18220        }
18221
18222        if (args.move != null) {
18223            // We did an in-place move, so dex is ready to roll
18224            scanFlags |= SCAN_NO_DEX;
18225            scanFlags |= SCAN_MOVE;
18226
18227            synchronized (mPackages) {
18228                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18229                if (ps == null) {
18230                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18231                            "Missing settings for moved package " + pkgName);
18232                }
18233
18234                // We moved the entire application as-is, so bring over the
18235                // previously derived ABI information.
18236                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18237                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18238            }
18239
18240        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18241            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18242            scanFlags |= SCAN_NO_DEX;
18243
18244            try {
18245                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18246                    args.abiOverride : pkg.cpuAbiOverride);
18247                final boolean extractNativeLibs = !pkg.isLibrary();
18248                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18249                        extractNativeLibs, mAppLib32InstallDir);
18250            } catch (PackageManagerException pme) {
18251                Slog.e(TAG, "Error deriving application ABI", pme);
18252                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18253                return;
18254            }
18255
18256            // Shared libraries for the package need to be updated.
18257            synchronized (mPackages) {
18258                try {
18259                    updateSharedLibrariesLPr(pkg, null);
18260                } catch (PackageManagerException e) {
18261                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18262                }
18263            }
18264
18265            // dexopt can take some time to complete, so, for instant apps, we skip this
18266            // step during installation. Instead, we'll take extra time the first time the
18267            // instant app starts. It's preferred to do it this way to provide continuous
18268            // progress to the user instead of mysteriously blocking somewhere in the
18269            // middle of running an instant app. The default behaviour can be overridden
18270            // via gservices.
18271            if (!instantApp || Global.getInt(
18272                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18273                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18274                // Do not run PackageDexOptimizer through the local performDexOpt
18275                // method because `pkg` may not be in `mPackages` yet.
18276                //
18277                // Also, don't fail application installs if the dexopt step fails.
18278                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18279                        REASON_INSTALL,
18280                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18281                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18282                        null /* instructionSets */,
18283                        getOrCreateCompilerPackageStats(pkg),
18284                        mDexManager.isUsedByOtherApps(pkg.packageName),
18285                        dexoptOptions);
18286                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18287            }
18288
18289            // Notify BackgroundDexOptService that the package has been changed.
18290            // If this is an update of a package which used to fail to compile,
18291            // BDOS will remove it from its blacklist.
18292            // TODO: Layering violation
18293            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18294        }
18295
18296        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18297            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18298            return;
18299        }
18300
18301        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18302
18303        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18304                "installPackageLI")) {
18305            if (replace) {
18306                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18307                    // Static libs have a synthetic package name containing the version
18308                    // and cannot be updated as an update would get a new package name,
18309                    // unless this is the exact same version code which is useful for
18310                    // development.
18311                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18312                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18313                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18314                                + "static-shared libs cannot be updated");
18315                        return;
18316                    }
18317                }
18318                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18319                        installerPackageName, res, args.installReason);
18320            } else {
18321                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18322                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18323            }
18324        }
18325
18326        synchronized (mPackages) {
18327            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18328            if (ps != null) {
18329                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18330                ps.setUpdateAvailable(false /*updateAvailable*/);
18331            }
18332
18333            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18334            for (int i = 0; i < childCount; i++) {
18335                PackageParser.Package childPkg = pkg.childPackages.get(i);
18336                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18337                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18338                if (childPs != null) {
18339                    childRes.newUsers = childPs.queryInstalledUsers(
18340                            sUserManager.getUserIds(), true);
18341                }
18342            }
18343
18344            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18345                updateSequenceNumberLP(ps, res.newUsers);
18346                updateInstantAppInstallerLocked(pkgName);
18347            }
18348        }
18349    }
18350
18351    private void startIntentFilterVerifications(int userId, boolean replacing,
18352            PackageParser.Package pkg) {
18353        if (mIntentFilterVerifierComponent == null) {
18354            Slog.w(TAG, "No IntentFilter verification will not be done as "
18355                    + "there is no IntentFilterVerifier available!");
18356            return;
18357        }
18358
18359        final int verifierUid = getPackageUid(
18360                mIntentFilterVerifierComponent.getPackageName(),
18361                MATCH_DEBUG_TRIAGED_MISSING,
18362                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18363
18364        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18365        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18366        mHandler.sendMessage(msg);
18367
18368        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18369        for (int i = 0; i < childCount; i++) {
18370            PackageParser.Package childPkg = pkg.childPackages.get(i);
18371            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18372            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18373            mHandler.sendMessage(msg);
18374        }
18375    }
18376
18377    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18378            PackageParser.Package pkg) {
18379        int size = pkg.activities.size();
18380        if (size == 0) {
18381            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18382                    "No activity, so no need to verify any IntentFilter!");
18383            return;
18384        }
18385
18386        final boolean hasDomainURLs = hasDomainURLs(pkg);
18387        if (!hasDomainURLs) {
18388            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18389                    "No domain URLs, so no need to verify any IntentFilter!");
18390            return;
18391        }
18392
18393        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18394                + " if any IntentFilter from the " + size
18395                + " Activities needs verification ...");
18396
18397        int count = 0;
18398        final String packageName = pkg.packageName;
18399
18400        synchronized (mPackages) {
18401            // If this is a new install and we see that we've already run verification for this
18402            // package, we have nothing to do: it means the state was restored from backup.
18403            if (!replacing) {
18404                IntentFilterVerificationInfo ivi =
18405                        mSettings.getIntentFilterVerificationLPr(packageName);
18406                if (ivi != null) {
18407                    if (DEBUG_DOMAIN_VERIFICATION) {
18408                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18409                                + ivi.getStatusString());
18410                    }
18411                    return;
18412                }
18413            }
18414
18415            // If any filters need to be verified, then all need to be.
18416            boolean needToVerify = false;
18417            for (PackageParser.Activity a : pkg.activities) {
18418                for (ActivityIntentInfo filter : a.intents) {
18419                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18420                        if (DEBUG_DOMAIN_VERIFICATION) {
18421                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18422                        }
18423                        needToVerify = true;
18424                        break;
18425                    }
18426                }
18427            }
18428
18429            if (needToVerify) {
18430                final int verificationId = mIntentFilterVerificationToken++;
18431                for (PackageParser.Activity a : pkg.activities) {
18432                    for (ActivityIntentInfo filter : a.intents) {
18433                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18434                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18435                                    "Verification needed for IntentFilter:" + filter.toString());
18436                            mIntentFilterVerifier.addOneIntentFilterVerification(
18437                                    verifierUid, userId, verificationId, filter, packageName);
18438                            count++;
18439                        }
18440                    }
18441                }
18442            }
18443        }
18444
18445        if (count > 0) {
18446            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18447                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18448                    +  " for userId:" + userId);
18449            mIntentFilterVerifier.startVerifications(userId);
18450        } else {
18451            if (DEBUG_DOMAIN_VERIFICATION) {
18452                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18453            }
18454        }
18455    }
18456
18457    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18458        final ComponentName cn  = filter.activity.getComponentName();
18459        final String packageName = cn.getPackageName();
18460
18461        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18462                packageName);
18463        if (ivi == null) {
18464            return true;
18465        }
18466        int status = ivi.getStatus();
18467        switch (status) {
18468            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18469            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18470                return true;
18471
18472            default:
18473                // Nothing to do
18474                return false;
18475        }
18476    }
18477
18478    private static boolean isMultiArch(ApplicationInfo info) {
18479        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18480    }
18481
18482    private static boolean isExternal(PackageParser.Package pkg) {
18483        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18484    }
18485
18486    private static boolean isExternal(PackageSetting ps) {
18487        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18488    }
18489
18490    private static boolean isSystemApp(PackageParser.Package pkg) {
18491        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18492    }
18493
18494    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18495        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18496    }
18497
18498    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18499        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18500    }
18501
18502    private static boolean isSystemApp(PackageSetting ps) {
18503        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18504    }
18505
18506    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18507        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18508    }
18509
18510    private int packageFlagsToInstallFlags(PackageSetting ps) {
18511        int installFlags = 0;
18512        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18513            // This existing package was an external ASEC install when we have
18514            // the external flag without a UUID
18515            installFlags |= PackageManager.INSTALL_EXTERNAL;
18516        }
18517        if (ps.isForwardLocked()) {
18518            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18519        }
18520        return installFlags;
18521    }
18522
18523    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18524        if (isExternal(pkg)) {
18525            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18526                return StorageManager.UUID_PRIMARY_PHYSICAL;
18527            } else {
18528                return pkg.volumeUuid;
18529            }
18530        } else {
18531            return StorageManager.UUID_PRIVATE_INTERNAL;
18532        }
18533    }
18534
18535    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18536        if (isExternal(pkg)) {
18537            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18538                return mSettings.getExternalVersion();
18539            } else {
18540                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18541            }
18542        } else {
18543            return mSettings.getInternalVersion();
18544        }
18545    }
18546
18547    private void deleteTempPackageFiles() {
18548        final FilenameFilter filter = new FilenameFilter() {
18549            public boolean accept(File dir, String name) {
18550                return name.startsWith("vmdl") && name.endsWith(".tmp");
18551            }
18552        };
18553        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18554            file.delete();
18555        }
18556    }
18557
18558    @Override
18559    public void deletePackageAsUser(String packageName, int versionCode,
18560            IPackageDeleteObserver observer, int userId, int flags) {
18561        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18562                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18563    }
18564
18565    @Override
18566    public void deletePackageVersioned(VersionedPackage versionedPackage,
18567            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18568        final int callingUid = Binder.getCallingUid();
18569        mContext.enforceCallingOrSelfPermission(
18570                android.Manifest.permission.DELETE_PACKAGES, null);
18571        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18572        Preconditions.checkNotNull(versionedPackage);
18573        Preconditions.checkNotNull(observer);
18574        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18575                PackageManager.VERSION_CODE_HIGHEST,
18576                Integer.MAX_VALUE, "versionCode must be >= -1");
18577
18578        final String packageName = versionedPackage.getPackageName();
18579        final int versionCode = versionedPackage.getVersionCode();
18580        final String internalPackageName;
18581        synchronized (mPackages) {
18582            // Normalize package name to handle renamed packages and static libs
18583            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18584                    versionedPackage.getVersionCode());
18585        }
18586
18587        final int uid = Binder.getCallingUid();
18588        if (!isOrphaned(internalPackageName)
18589                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18590            try {
18591                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18592                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18593                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18594                observer.onUserActionRequired(intent);
18595            } catch (RemoteException re) {
18596            }
18597            return;
18598        }
18599        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18600        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18601        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18602            mContext.enforceCallingOrSelfPermission(
18603                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18604                    "deletePackage for user " + userId);
18605        }
18606
18607        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18608            try {
18609                observer.onPackageDeleted(packageName,
18610                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18611            } catch (RemoteException re) {
18612            }
18613            return;
18614        }
18615
18616        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18617            try {
18618                observer.onPackageDeleted(packageName,
18619                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18620            } catch (RemoteException re) {
18621            }
18622            return;
18623        }
18624
18625        if (DEBUG_REMOVE) {
18626            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18627                    + " deleteAllUsers: " + deleteAllUsers + " version="
18628                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18629                    ? "VERSION_CODE_HIGHEST" : versionCode));
18630        }
18631        // Queue up an async operation since the package deletion may take a little while.
18632        mHandler.post(new Runnable() {
18633            public void run() {
18634                mHandler.removeCallbacks(this);
18635                int returnCode;
18636                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18637                boolean doDeletePackage = true;
18638                if (ps != null) {
18639                    final boolean targetIsInstantApp =
18640                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18641                    doDeletePackage = !targetIsInstantApp
18642                            || canViewInstantApps;
18643                }
18644                if (doDeletePackage) {
18645                    if (!deleteAllUsers) {
18646                        returnCode = deletePackageX(internalPackageName, versionCode,
18647                                userId, deleteFlags);
18648                    } else {
18649                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18650                                internalPackageName, users);
18651                        // If nobody is blocking uninstall, proceed with delete for all users
18652                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18653                            returnCode = deletePackageX(internalPackageName, versionCode,
18654                                    userId, deleteFlags);
18655                        } else {
18656                            // Otherwise uninstall individually for users with blockUninstalls=false
18657                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18658                            for (int userId : users) {
18659                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18660                                    returnCode = deletePackageX(internalPackageName, versionCode,
18661                                            userId, userFlags);
18662                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18663                                        Slog.w(TAG, "Package delete failed for user " + userId
18664                                                + ", returnCode " + returnCode);
18665                                    }
18666                                }
18667                            }
18668                            // The app has only been marked uninstalled for certain users.
18669                            // We still need to report that delete was blocked
18670                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18671                        }
18672                    }
18673                } else {
18674                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18675                }
18676                try {
18677                    observer.onPackageDeleted(packageName, returnCode, null);
18678                } catch (RemoteException e) {
18679                    Log.i(TAG, "Observer no longer exists.");
18680                } //end catch
18681            } //end run
18682        });
18683    }
18684
18685    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18686        if (pkg.staticSharedLibName != null) {
18687            return pkg.manifestPackageName;
18688        }
18689        return pkg.packageName;
18690    }
18691
18692    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18693        // Handle renamed packages
18694        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18695        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18696
18697        // Is this a static library?
18698        SparseArray<SharedLibraryEntry> versionedLib =
18699                mStaticLibsByDeclaringPackage.get(packageName);
18700        if (versionedLib == null || versionedLib.size() <= 0) {
18701            return packageName;
18702        }
18703
18704        // Figure out which lib versions the caller can see
18705        SparseIntArray versionsCallerCanSee = null;
18706        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18707        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18708                && callingAppId != Process.ROOT_UID) {
18709            versionsCallerCanSee = new SparseIntArray();
18710            String libName = versionedLib.valueAt(0).info.getName();
18711            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18712            if (uidPackages != null) {
18713                for (String uidPackage : uidPackages) {
18714                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18715                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18716                    if (libIdx >= 0) {
18717                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18718                        versionsCallerCanSee.append(libVersion, libVersion);
18719                    }
18720                }
18721            }
18722        }
18723
18724        // Caller can see nothing - done
18725        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18726            return packageName;
18727        }
18728
18729        // Find the version the caller can see and the app version code
18730        SharedLibraryEntry highestVersion = null;
18731        final int versionCount = versionedLib.size();
18732        for (int i = 0; i < versionCount; i++) {
18733            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18734            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18735                    libEntry.info.getVersion()) < 0) {
18736                continue;
18737            }
18738            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18739            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18740                if (libVersionCode == versionCode) {
18741                    return libEntry.apk;
18742                }
18743            } else if (highestVersion == null) {
18744                highestVersion = libEntry;
18745            } else if (libVersionCode  > highestVersion.info
18746                    .getDeclaringPackage().getVersionCode()) {
18747                highestVersion = libEntry;
18748            }
18749        }
18750
18751        if (highestVersion != null) {
18752            return highestVersion.apk;
18753        }
18754
18755        return packageName;
18756    }
18757
18758    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18759        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18760              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18761            return true;
18762        }
18763        final int callingUserId = UserHandle.getUserId(callingUid);
18764        // If the caller installed the pkgName, then allow it to silently uninstall.
18765        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18766            return true;
18767        }
18768
18769        // Allow package verifier to silently uninstall.
18770        if (mRequiredVerifierPackage != null &&
18771                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18772            return true;
18773        }
18774
18775        // Allow package uninstaller to silently uninstall.
18776        if (mRequiredUninstallerPackage != null &&
18777                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18778            return true;
18779        }
18780
18781        // Allow storage manager to silently uninstall.
18782        if (mStorageManagerPackage != null &&
18783                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18784            return true;
18785        }
18786
18787        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18788        // uninstall for device owner provisioning.
18789        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18790                == PERMISSION_GRANTED) {
18791            return true;
18792        }
18793
18794        return false;
18795    }
18796
18797    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18798        int[] result = EMPTY_INT_ARRAY;
18799        for (int userId : userIds) {
18800            if (getBlockUninstallForUser(packageName, userId)) {
18801                result = ArrayUtils.appendInt(result, userId);
18802            }
18803        }
18804        return result;
18805    }
18806
18807    @Override
18808    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18809        final int callingUid = Binder.getCallingUid();
18810        if (getInstantAppPackageName(callingUid) != null
18811                && !isCallerSameApp(packageName, callingUid)) {
18812            return false;
18813        }
18814        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18815    }
18816
18817    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18818        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18819                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18820        try {
18821            if (dpm != null) {
18822                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18823                        /* callingUserOnly =*/ false);
18824                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18825                        : deviceOwnerComponentName.getPackageName();
18826                // Does the package contains the device owner?
18827                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18828                // this check is probably not needed, since DO should be registered as a device
18829                // admin on some user too. (Original bug for this: b/17657954)
18830                if (packageName.equals(deviceOwnerPackageName)) {
18831                    return true;
18832                }
18833                // Does it contain a device admin for any user?
18834                int[] users;
18835                if (userId == UserHandle.USER_ALL) {
18836                    users = sUserManager.getUserIds();
18837                } else {
18838                    users = new int[]{userId};
18839                }
18840                for (int i = 0; i < users.length; ++i) {
18841                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18842                        return true;
18843                    }
18844                }
18845            }
18846        } catch (RemoteException e) {
18847        }
18848        return false;
18849    }
18850
18851    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18852        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18853    }
18854
18855    /**
18856     *  This method is an internal method that could be get invoked either
18857     *  to delete an installed package or to clean up a failed installation.
18858     *  After deleting an installed package, a broadcast is sent to notify any
18859     *  listeners that the package has been removed. For cleaning up a failed
18860     *  installation, the broadcast is not necessary since the package's
18861     *  installation wouldn't have sent the initial broadcast either
18862     *  The key steps in deleting a package are
18863     *  deleting the package information in internal structures like mPackages,
18864     *  deleting the packages base directories through installd
18865     *  updating mSettings to reflect current status
18866     *  persisting settings for later use
18867     *  sending a broadcast if necessary
18868     */
18869    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18870        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18871        final boolean res;
18872
18873        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18874                ? UserHandle.USER_ALL : userId;
18875
18876        if (isPackageDeviceAdmin(packageName, removeUser)) {
18877            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18878            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18879        }
18880
18881        PackageSetting uninstalledPs = null;
18882        PackageParser.Package pkg = null;
18883
18884        // for the uninstall-updates case and restricted profiles, remember the per-
18885        // user handle installed state
18886        int[] allUsers;
18887        synchronized (mPackages) {
18888            uninstalledPs = mSettings.mPackages.get(packageName);
18889            if (uninstalledPs == null) {
18890                Slog.w(TAG, "Not removing non-existent package " + packageName);
18891                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18892            }
18893
18894            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18895                    && uninstalledPs.versionCode != versionCode) {
18896                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18897                        + uninstalledPs.versionCode + " != " + versionCode);
18898                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18899            }
18900
18901            // Static shared libs can be declared by any package, so let us not
18902            // allow removing a package if it provides a lib others depend on.
18903            pkg = mPackages.get(packageName);
18904
18905            allUsers = sUserManager.getUserIds();
18906
18907            if (pkg != null && pkg.staticSharedLibName != null) {
18908                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18909                        pkg.staticSharedLibVersion);
18910                if (libEntry != null) {
18911                    for (int currUserId : allUsers) {
18912                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18913                            continue;
18914                        }
18915                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18916                                libEntry.info, 0, currUserId);
18917                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18918                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18919                                    + " hosting lib " + libEntry.info.getName() + " version "
18920                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18921                                    + " for user " + currUserId);
18922                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18923                        }
18924                    }
18925                }
18926            }
18927
18928            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18929        }
18930
18931        final int freezeUser;
18932        if (isUpdatedSystemApp(uninstalledPs)
18933                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18934            // We're downgrading a system app, which will apply to all users, so
18935            // freeze them all during the downgrade
18936            freezeUser = UserHandle.USER_ALL;
18937        } else {
18938            freezeUser = removeUser;
18939        }
18940
18941        synchronized (mInstallLock) {
18942            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18943            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18944                    deleteFlags, "deletePackageX")) {
18945                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18946                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18947            }
18948            synchronized (mPackages) {
18949                if (res) {
18950                    if (pkg != null) {
18951                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18952                    }
18953                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18954                    updateInstantAppInstallerLocked(packageName);
18955                }
18956            }
18957        }
18958
18959        if (res) {
18960            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18961            info.sendPackageRemovedBroadcasts(killApp);
18962            info.sendSystemPackageUpdatedBroadcasts();
18963            info.sendSystemPackageAppearedBroadcasts();
18964        }
18965        // Force a gc here.
18966        Runtime.getRuntime().gc();
18967        // Delete the resources here after sending the broadcast to let
18968        // other processes clean up before deleting resources.
18969        if (info.args != null) {
18970            synchronized (mInstallLock) {
18971                info.args.doPostDeleteLI(true);
18972            }
18973        }
18974
18975        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18976    }
18977
18978    static class PackageRemovedInfo {
18979        final PackageSender packageSender;
18980        String removedPackage;
18981        String installerPackageName;
18982        int uid = -1;
18983        int removedAppId = -1;
18984        int[] origUsers;
18985        int[] removedUsers = null;
18986        int[] broadcastUsers = null;
18987        SparseArray<Integer> installReasons;
18988        boolean isRemovedPackageSystemUpdate = false;
18989        boolean isUpdate;
18990        boolean dataRemoved;
18991        boolean removedForAllUsers;
18992        boolean isStaticSharedLib;
18993        // Clean up resources deleted packages.
18994        InstallArgs args = null;
18995        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18996        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18997
18998        PackageRemovedInfo(PackageSender packageSender) {
18999            this.packageSender = packageSender;
19000        }
19001
19002        void sendPackageRemovedBroadcasts(boolean killApp) {
19003            sendPackageRemovedBroadcastInternal(killApp);
19004            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19005            for (int i = 0; i < childCount; i++) {
19006                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19007                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19008            }
19009        }
19010
19011        void sendSystemPackageUpdatedBroadcasts() {
19012            if (isRemovedPackageSystemUpdate) {
19013                sendSystemPackageUpdatedBroadcastsInternal();
19014                final int childCount = (removedChildPackages != null)
19015                        ? removedChildPackages.size() : 0;
19016                for (int i = 0; i < childCount; i++) {
19017                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19018                    if (childInfo.isRemovedPackageSystemUpdate) {
19019                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19020                    }
19021                }
19022            }
19023        }
19024
19025        void sendSystemPackageAppearedBroadcasts() {
19026            final int packageCount = (appearedChildPackages != null)
19027                    ? appearedChildPackages.size() : 0;
19028            for (int i = 0; i < packageCount; i++) {
19029                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19030                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19031                    true, UserHandle.getAppId(installedInfo.uid),
19032                    installedInfo.newUsers);
19033            }
19034        }
19035
19036        private void sendSystemPackageUpdatedBroadcastsInternal() {
19037            Bundle extras = new Bundle(2);
19038            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19039            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19040            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19041                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19042            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19043                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19044            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19045                null, null, 0, removedPackage, null, null);
19046            if (installerPackageName != null) {
19047                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19048                        removedPackage, extras, 0 /*flags*/,
19049                        installerPackageName, null, null);
19050                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19051                        removedPackage, extras, 0 /*flags*/,
19052                        installerPackageName, null, null);
19053            }
19054        }
19055
19056        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19057            // Don't send static shared library removal broadcasts as these
19058            // libs are visible only the the apps that depend on them an one
19059            // cannot remove the library if it has a dependency.
19060            if (isStaticSharedLib) {
19061                return;
19062            }
19063            Bundle extras = new Bundle(2);
19064            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19065            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19066            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19067            if (isUpdate || isRemovedPackageSystemUpdate) {
19068                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19069            }
19070            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19071            if (removedPackage != null) {
19072                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19073                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19074                if (installerPackageName != null) {
19075                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19076                            removedPackage, extras, 0 /*flags*/,
19077                            installerPackageName, null, broadcastUsers);
19078                }
19079                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19080                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19081                        removedPackage, extras,
19082                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19083                        null, null, broadcastUsers);
19084                }
19085            }
19086            if (removedAppId >= 0) {
19087                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19088                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19089                    null, null, broadcastUsers);
19090            }
19091        }
19092
19093        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19094            removedUsers = userIds;
19095            if (removedUsers == null) {
19096                broadcastUsers = null;
19097                return;
19098            }
19099
19100            broadcastUsers = EMPTY_INT_ARRAY;
19101            for (int i = userIds.length - 1; i >= 0; --i) {
19102                final int userId = userIds[i];
19103                if (deletedPackageSetting.getInstantApp(userId)) {
19104                    continue;
19105                }
19106                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19107            }
19108        }
19109    }
19110
19111    /*
19112     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19113     * flag is not set, the data directory is removed as well.
19114     * make sure this flag is set for partially installed apps. If not its meaningless to
19115     * delete a partially installed application.
19116     */
19117    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19118            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19119        String packageName = ps.name;
19120        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19121        // Retrieve object to delete permissions for shared user later on
19122        final PackageParser.Package deletedPkg;
19123        final PackageSetting deletedPs;
19124        // reader
19125        synchronized (mPackages) {
19126            deletedPkg = mPackages.get(packageName);
19127            deletedPs = mSettings.mPackages.get(packageName);
19128            if (outInfo != null) {
19129                outInfo.removedPackage = packageName;
19130                outInfo.installerPackageName = ps.installerPackageName;
19131                outInfo.isStaticSharedLib = deletedPkg != null
19132                        && deletedPkg.staticSharedLibName != null;
19133                outInfo.populateUsers(deletedPs == null ? null
19134                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19135            }
19136        }
19137
19138        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19139
19140        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19141            final PackageParser.Package resolvedPkg;
19142            if (deletedPkg != null) {
19143                resolvedPkg = deletedPkg;
19144            } else {
19145                // We don't have a parsed package when it lives on an ejected
19146                // adopted storage device, so fake something together
19147                resolvedPkg = new PackageParser.Package(ps.name);
19148                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19149            }
19150            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19151                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19152            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19153            if (outInfo != null) {
19154                outInfo.dataRemoved = true;
19155            }
19156            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19157        }
19158
19159        int removedAppId = -1;
19160
19161        // writer
19162        synchronized (mPackages) {
19163            boolean installedStateChanged = false;
19164            if (deletedPs != null) {
19165                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19166                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19167                    clearDefaultBrowserIfNeeded(packageName);
19168                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19169                    removedAppId = mSettings.removePackageLPw(packageName);
19170                    if (outInfo != null) {
19171                        outInfo.removedAppId = removedAppId;
19172                    }
19173                    updatePermissionsLPw(deletedPs.name, null, 0);
19174                    if (deletedPs.sharedUser != null) {
19175                        // Remove permissions associated with package. Since runtime
19176                        // permissions are per user we have to kill the removed package
19177                        // or packages running under the shared user of the removed
19178                        // package if revoking the permissions requested only by the removed
19179                        // package is successful and this causes a change in gids.
19180                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19181                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19182                                    userId);
19183                            if (userIdToKill == UserHandle.USER_ALL
19184                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19185                                // If gids changed for this user, kill all affected packages.
19186                                mHandler.post(new Runnable() {
19187                                    @Override
19188                                    public void run() {
19189                                        // This has to happen with no lock held.
19190                                        killApplication(deletedPs.name, deletedPs.appId,
19191                                                KILL_APP_REASON_GIDS_CHANGED);
19192                                    }
19193                                });
19194                                break;
19195                            }
19196                        }
19197                    }
19198                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19199                }
19200                // make sure to preserve per-user disabled state if this removal was just
19201                // a downgrade of a system app to the factory package
19202                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19203                    if (DEBUG_REMOVE) {
19204                        Slog.d(TAG, "Propagating install state across downgrade");
19205                    }
19206                    for (int userId : allUserHandles) {
19207                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19208                        if (DEBUG_REMOVE) {
19209                            Slog.d(TAG, "    user " + userId + " => " + installed);
19210                        }
19211                        if (installed != ps.getInstalled(userId)) {
19212                            installedStateChanged = true;
19213                        }
19214                        ps.setInstalled(installed, userId);
19215                    }
19216                }
19217            }
19218            // can downgrade to reader
19219            if (writeSettings) {
19220                // Save settings now
19221                mSettings.writeLPr();
19222            }
19223            if (installedStateChanged) {
19224                mSettings.writeKernelMappingLPr(ps);
19225            }
19226        }
19227        if (removedAppId != -1) {
19228            // A user ID was deleted here. Go through all users and remove it
19229            // from KeyStore.
19230            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19231        }
19232    }
19233
19234    static boolean locationIsPrivileged(File path) {
19235        try {
19236            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19237                    .getCanonicalPath();
19238            return path.getCanonicalPath().startsWith(privilegedAppDir);
19239        } catch (IOException e) {
19240            Slog.e(TAG, "Unable to access code path " + path);
19241        }
19242        return false;
19243    }
19244
19245    /*
19246     * Tries to delete system package.
19247     */
19248    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19249            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19250            boolean writeSettings) {
19251        if (deletedPs.parentPackageName != null) {
19252            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19253            return false;
19254        }
19255
19256        final boolean applyUserRestrictions
19257                = (allUserHandles != null) && (outInfo.origUsers != null);
19258        final PackageSetting disabledPs;
19259        // Confirm if the system package has been updated
19260        // An updated system app can be deleted. This will also have to restore
19261        // the system pkg from system partition
19262        // reader
19263        synchronized (mPackages) {
19264            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19265        }
19266
19267        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19268                + " disabledPs=" + disabledPs);
19269
19270        if (disabledPs == null) {
19271            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19272            return false;
19273        } else if (DEBUG_REMOVE) {
19274            Slog.d(TAG, "Deleting system pkg from data partition");
19275        }
19276
19277        if (DEBUG_REMOVE) {
19278            if (applyUserRestrictions) {
19279                Slog.d(TAG, "Remembering install states:");
19280                for (int userId : allUserHandles) {
19281                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19282                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19283                }
19284            }
19285        }
19286
19287        // Delete the updated package
19288        outInfo.isRemovedPackageSystemUpdate = true;
19289        if (outInfo.removedChildPackages != null) {
19290            final int childCount = (deletedPs.childPackageNames != null)
19291                    ? deletedPs.childPackageNames.size() : 0;
19292            for (int i = 0; i < childCount; i++) {
19293                String childPackageName = deletedPs.childPackageNames.get(i);
19294                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19295                        .contains(childPackageName)) {
19296                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19297                            childPackageName);
19298                    if (childInfo != null) {
19299                        childInfo.isRemovedPackageSystemUpdate = true;
19300                    }
19301                }
19302            }
19303        }
19304
19305        if (disabledPs.versionCode < deletedPs.versionCode) {
19306            // Delete data for downgrades
19307            flags &= ~PackageManager.DELETE_KEEP_DATA;
19308        } else {
19309            // Preserve data by setting flag
19310            flags |= PackageManager.DELETE_KEEP_DATA;
19311        }
19312
19313        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19314                outInfo, writeSettings, disabledPs.pkg);
19315        if (!ret) {
19316            return false;
19317        }
19318
19319        // writer
19320        synchronized (mPackages) {
19321            // Reinstate the old system package
19322            enableSystemPackageLPw(disabledPs.pkg);
19323            // Remove any native libraries from the upgraded package.
19324            removeNativeBinariesLI(deletedPs);
19325        }
19326
19327        // Install the system package
19328        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19329        int parseFlags = mDefParseFlags
19330                | PackageParser.PARSE_MUST_BE_APK
19331                | PackageParser.PARSE_IS_SYSTEM
19332                | PackageParser.PARSE_IS_SYSTEM_DIR;
19333        if (locationIsPrivileged(disabledPs.codePath)) {
19334            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19335        }
19336
19337        final PackageParser.Package newPkg;
19338        try {
19339            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19340                0 /* currentTime */, null);
19341        } catch (PackageManagerException e) {
19342            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19343                    + e.getMessage());
19344            return false;
19345        }
19346
19347        try {
19348            // update shared libraries for the newly re-installed system package
19349            updateSharedLibrariesLPr(newPkg, null);
19350        } catch (PackageManagerException e) {
19351            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19352        }
19353
19354        prepareAppDataAfterInstallLIF(newPkg);
19355
19356        // writer
19357        synchronized (mPackages) {
19358            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19359
19360            // Propagate the permissions state as we do not want to drop on the floor
19361            // runtime permissions. The update permissions method below will take
19362            // care of removing obsolete permissions and grant install permissions.
19363            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19364            updatePermissionsLPw(newPkg.packageName, newPkg,
19365                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19366
19367            if (applyUserRestrictions) {
19368                boolean installedStateChanged = false;
19369                if (DEBUG_REMOVE) {
19370                    Slog.d(TAG, "Propagating install state across reinstall");
19371                }
19372                for (int userId : allUserHandles) {
19373                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19374                    if (DEBUG_REMOVE) {
19375                        Slog.d(TAG, "    user " + userId + " => " + installed);
19376                    }
19377                    if (installed != ps.getInstalled(userId)) {
19378                        installedStateChanged = true;
19379                    }
19380                    ps.setInstalled(installed, userId);
19381
19382                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19383                }
19384                // Regardless of writeSettings we need to ensure that this restriction
19385                // state propagation is persisted
19386                mSettings.writeAllUsersPackageRestrictionsLPr();
19387                if (installedStateChanged) {
19388                    mSettings.writeKernelMappingLPr(ps);
19389                }
19390            }
19391            // can downgrade to reader here
19392            if (writeSettings) {
19393                mSettings.writeLPr();
19394            }
19395        }
19396        return true;
19397    }
19398
19399    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19400            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19401            PackageRemovedInfo outInfo, boolean writeSettings,
19402            PackageParser.Package replacingPackage) {
19403        synchronized (mPackages) {
19404            if (outInfo != null) {
19405                outInfo.uid = ps.appId;
19406            }
19407
19408            if (outInfo != null && outInfo.removedChildPackages != null) {
19409                final int childCount = (ps.childPackageNames != null)
19410                        ? ps.childPackageNames.size() : 0;
19411                for (int i = 0; i < childCount; i++) {
19412                    String childPackageName = ps.childPackageNames.get(i);
19413                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19414                    if (childPs == null) {
19415                        return false;
19416                    }
19417                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19418                            childPackageName);
19419                    if (childInfo != null) {
19420                        childInfo.uid = childPs.appId;
19421                    }
19422                }
19423            }
19424        }
19425
19426        // Delete package data from internal structures and also remove data if flag is set
19427        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19428
19429        // Delete the child packages data
19430        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19431        for (int i = 0; i < childCount; i++) {
19432            PackageSetting childPs;
19433            synchronized (mPackages) {
19434                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19435            }
19436            if (childPs != null) {
19437                PackageRemovedInfo childOutInfo = (outInfo != null
19438                        && outInfo.removedChildPackages != null)
19439                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19440                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19441                        && (replacingPackage != null
19442                        && !replacingPackage.hasChildPackage(childPs.name))
19443                        ? flags & ~DELETE_KEEP_DATA : flags;
19444                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19445                        deleteFlags, writeSettings);
19446            }
19447        }
19448
19449        // Delete application code and resources only for parent packages
19450        if (ps.parentPackageName == null) {
19451            if (deleteCodeAndResources && (outInfo != null)) {
19452                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19453                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19454                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19455            }
19456        }
19457
19458        return true;
19459    }
19460
19461    @Override
19462    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19463            int userId) {
19464        mContext.enforceCallingOrSelfPermission(
19465                android.Manifest.permission.DELETE_PACKAGES, null);
19466        synchronized (mPackages) {
19467            // Cannot block uninstall of static shared libs as they are
19468            // considered a part of the using app (emulating static linking).
19469            // Also static libs are installed always on internal storage.
19470            PackageParser.Package pkg = mPackages.get(packageName);
19471            if (pkg != null && pkg.staticSharedLibName != null) {
19472                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19473                        + " providing static shared library: " + pkg.staticSharedLibName);
19474                return false;
19475            }
19476            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19477            mSettings.writePackageRestrictionsLPr(userId);
19478        }
19479        return true;
19480    }
19481
19482    @Override
19483    public boolean getBlockUninstallForUser(String packageName, int userId) {
19484        synchronized (mPackages) {
19485            final PackageSetting ps = mSettings.mPackages.get(packageName);
19486            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19487                return false;
19488            }
19489            return mSettings.getBlockUninstallLPr(userId, packageName);
19490        }
19491    }
19492
19493    @Override
19494    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19495        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19496        synchronized (mPackages) {
19497            PackageSetting ps = mSettings.mPackages.get(packageName);
19498            if (ps == null) {
19499                Log.w(TAG, "Package doesn't exist: " + packageName);
19500                return false;
19501            }
19502            if (systemUserApp) {
19503                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19504            } else {
19505                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19506            }
19507            mSettings.writeLPr();
19508        }
19509        return true;
19510    }
19511
19512    /*
19513     * This method handles package deletion in general
19514     */
19515    private boolean deletePackageLIF(String packageName, UserHandle user,
19516            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19517            PackageRemovedInfo outInfo, boolean writeSettings,
19518            PackageParser.Package replacingPackage) {
19519        if (packageName == null) {
19520            Slog.w(TAG, "Attempt to delete null packageName.");
19521            return false;
19522        }
19523
19524        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19525
19526        PackageSetting ps;
19527        synchronized (mPackages) {
19528            ps = mSettings.mPackages.get(packageName);
19529            if (ps == null) {
19530                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19531                return false;
19532            }
19533
19534            if (ps.parentPackageName != null && (!isSystemApp(ps)
19535                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19536                if (DEBUG_REMOVE) {
19537                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19538                            + ((user == null) ? UserHandle.USER_ALL : user));
19539                }
19540                final int removedUserId = (user != null) ? user.getIdentifier()
19541                        : UserHandle.USER_ALL;
19542                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19543                    return false;
19544                }
19545                markPackageUninstalledForUserLPw(ps, user);
19546                scheduleWritePackageRestrictionsLocked(user);
19547                return true;
19548            }
19549        }
19550
19551        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19552                && user.getIdentifier() != UserHandle.USER_ALL)) {
19553            // The caller is asking that the package only be deleted for a single
19554            // user.  To do this, we just mark its uninstalled state and delete
19555            // its data. If this is a system app, we only allow this to happen if
19556            // they have set the special DELETE_SYSTEM_APP which requests different
19557            // semantics than normal for uninstalling system apps.
19558            markPackageUninstalledForUserLPw(ps, user);
19559
19560            if (!isSystemApp(ps)) {
19561                // Do not uninstall the APK if an app should be cached
19562                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19563                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19564                    // Other user still have this package installed, so all
19565                    // we need to do is clear this user's data and save that
19566                    // it is uninstalled.
19567                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19568                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19569                        return false;
19570                    }
19571                    scheduleWritePackageRestrictionsLocked(user);
19572                    return true;
19573                } else {
19574                    // We need to set it back to 'installed' so the uninstall
19575                    // broadcasts will be sent correctly.
19576                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19577                    ps.setInstalled(true, user.getIdentifier());
19578                    mSettings.writeKernelMappingLPr(ps);
19579                }
19580            } else {
19581                // This is a system app, so we assume that the
19582                // other users still have this package installed, so all
19583                // we need to do is clear this user's data and save that
19584                // it is uninstalled.
19585                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19586                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19587                    return false;
19588                }
19589                scheduleWritePackageRestrictionsLocked(user);
19590                return true;
19591            }
19592        }
19593
19594        // If we are deleting a composite package for all users, keep track
19595        // of result for each child.
19596        if (ps.childPackageNames != null && outInfo != null) {
19597            synchronized (mPackages) {
19598                final int childCount = ps.childPackageNames.size();
19599                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19600                for (int i = 0; i < childCount; i++) {
19601                    String childPackageName = ps.childPackageNames.get(i);
19602                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19603                    childInfo.removedPackage = childPackageName;
19604                    childInfo.installerPackageName = ps.installerPackageName;
19605                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19606                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19607                    if (childPs != null) {
19608                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19609                    }
19610                }
19611            }
19612        }
19613
19614        boolean ret = false;
19615        if (isSystemApp(ps)) {
19616            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19617            // When an updated system application is deleted we delete the existing resources
19618            // as well and fall back to existing code in system partition
19619            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19620        } else {
19621            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19622            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19623                    outInfo, writeSettings, replacingPackage);
19624        }
19625
19626        // Take a note whether we deleted the package for all users
19627        if (outInfo != null) {
19628            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19629            if (outInfo.removedChildPackages != null) {
19630                synchronized (mPackages) {
19631                    final int childCount = outInfo.removedChildPackages.size();
19632                    for (int i = 0; i < childCount; i++) {
19633                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19634                        if (childInfo != null) {
19635                            childInfo.removedForAllUsers = mPackages.get(
19636                                    childInfo.removedPackage) == null;
19637                        }
19638                    }
19639                }
19640            }
19641            // If we uninstalled an update to a system app there may be some
19642            // child packages that appeared as they are declared in the system
19643            // app but were not declared in the update.
19644            if (isSystemApp(ps)) {
19645                synchronized (mPackages) {
19646                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19647                    final int childCount = (updatedPs.childPackageNames != null)
19648                            ? updatedPs.childPackageNames.size() : 0;
19649                    for (int i = 0; i < childCount; i++) {
19650                        String childPackageName = updatedPs.childPackageNames.get(i);
19651                        if (outInfo.removedChildPackages == null
19652                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19653                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19654                            if (childPs == null) {
19655                                continue;
19656                            }
19657                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19658                            installRes.name = childPackageName;
19659                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19660                            installRes.pkg = mPackages.get(childPackageName);
19661                            installRes.uid = childPs.pkg.applicationInfo.uid;
19662                            if (outInfo.appearedChildPackages == null) {
19663                                outInfo.appearedChildPackages = new ArrayMap<>();
19664                            }
19665                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19666                        }
19667                    }
19668                }
19669            }
19670        }
19671
19672        return ret;
19673    }
19674
19675    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19676        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19677                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19678        for (int nextUserId : userIds) {
19679            if (DEBUG_REMOVE) {
19680                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19681            }
19682            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19683                    false /*installed*/,
19684                    true /*stopped*/,
19685                    true /*notLaunched*/,
19686                    false /*hidden*/,
19687                    false /*suspended*/,
19688                    false /*instantApp*/,
19689                    null /*lastDisableAppCaller*/,
19690                    null /*enabledComponents*/,
19691                    null /*disabledComponents*/,
19692                    ps.readUserState(nextUserId).domainVerificationStatus,
19693                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19694        }
19695        mSettings.writeKernelMappingLPr(ps);
19696    }
19697
19698    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19699            PackageRemovedInfo outInfo) {
19700        final PackageParser.Package pkg;
19701        synchronized (mPackages) {
19702            pkg = mPackages.get(ps.name);
19703        }
19704
19705        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19706                : new int[] {userId};
19707        for (int nextUserId : userIds) {
19708            if (DEBUG_REMOVE) {
19709                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19710                        + nextUserId);
19711            }
19712
19713            destroyAppDataLIF(pkg, userId,
19714                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19715            destroyAppProfilesLIF(pkg, userId);
19716            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19717            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19718            schedulePackageCleaning(ps.name, nextUserId, false);
19719            synchronized (mPackages) {
19720                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19721                    scheduleWritePackageRestrictionsLocked(nextUserId);
19722                }
19723                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19724            }
19725        }
19726
19727        if (outInfo != null) {
19728            outInfo.removedPackage = ps.name;
19729            outInfo.installerPackageName = ps.installerPackageName;
19730            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19731            outInfo.removedAppId = ps.appId;
19732            outInfo.removedUsers = userIds;
19733            outInfo.broadcastUsers = userIds;
19734        }
19735
19736        return true;
19737    }
19738
19739    private final class ClearStorageConnection implements ServiceConnection {
19740        IMediaContainerService mContainerService;
19741
19742        @Override
19743        public void onServiceConnected(ComponentName name, IBinder service) {
19744            synchronized (this) {
19745                mContainerService = IMediaContainerService.Stub
19746                        .asInterface(Binder.allowBlocking(service));
19747                notifyAll();
19748            }
19749        }
19750
19751        @Override
19752        public void onServiceDisconnected(ComponentName name) {
19753        }
19754    }
19755
19756    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19757        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19758
19759        final boolean mounted;
19760        if (Environment.isExternalStorageEmulated()) {
19761            mounted = true;
19762        } else {
19763            final String status = Environment.getExternalStorageState();
19764
19765            mounted = status.equals(Environment.MEDIA_MOUNTED)
19766                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19767        }
19768
19769        if (!mounted) {
19770            return;
19771        }
19772
19773        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19774        int[] users;
19775        if (userId == UserHandle.USER_ALL) {
19776            users = sUserManager.getUserIds();
19777        } else {
19778            users = new int[] { userId };
19779        }
19780        final ClearStorageConnection conn = new ClearStorageConnection();
19781        if (mContext.bindServiceAsUser(
19782                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19783            try {
19784                for (int curUser : users) {
19785                    long timeout = SystemClock.uptimeMillis() + 5000;
19786                    synchronized (conn) {
19787                        long now;
19788                        while (conn.mContainerService == null &&
19789                                (now = SystemClock.uptimeMillis()) < timeout) {
19790                            try {
19791                                conn.wait(timeout - now);
19792                            } catch (InterruptedException e) {
19793                            }
19794                        }
19795                    }
19796                    if (conn.mContainerService == null) {
19797                        return;
19798                    }
19799
19800                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19801                    clearDirectory(conn.mContainerService,
19802                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19803                    if (allData) {
19804                        clearDirectory(conn.mContainerService,
19805                                userEnv.buildExternalStorageAppDataDirs(packageName));
19806                        clearDirectory(conn.mContainerService,
19807                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19808                    }
19809                }
19810            } finally {
19811                mContext.unbindService(conn);
19812            }
19813        }
19814    }
19815
19816    @Override
19817    public void clearApplicationProfileData(String packageName) {
19818        enforceSystemOrRoot("Only the system can clear all profile data");
19819
19820        final PackageParser.Package pkg;
19821        synchronized (mPackages) {
19822            pkg = mPackages.get(packageName);
19823        }
19824
19825        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19826            synchronized (mInstallLock) {
19827                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19828            }
19829        }
19830    }
19831
19832    @Override
19833    public void clearApplicationUserData(final String packageName,
19834            final IPackageDataObserver observer, final int userId) {
19835        mContext.enforceCallingOrSelfPermission(
19836                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19837
19838        final int callingUid = Binder.getCallingUid();
19839        enforceCrossUserPermission(callingUid, userId,
19840                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19841
19842        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19843        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19844            return;
19845        }
19846        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19847            throw new SecurityException("Cannot clear data for a protected package: "
19848                    + packageName);
19849        }
19850        // Queue up an async operation since the package deletion may take a little while.
19851        mHandler.post(new Runnable() {
19852            public void run() {
19853                mHandler.removeCallbacks(this);
19854                final boolean succeeded;
19855                try (PackageFreezer freezer = freezePackage(packageName,
19856                        "clearApplicationUserData")) {
19857                    synchronized (mInstallLock) {
19858                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19859                    }
19860                    clearExternalStorageDataSync(packageName, userId, true);
19861                    synchronized (mPackages) {
19862                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19863                                packageName, userId);
19864                    }
19865                }
19866                if (succeeded) {
19867                    // invoke DeviceStorageMonitor's update method to clear any notifications
19868                    DeviceStorageMonitorInternal dsm = LocalServices
19869                            .getService(DeviceStorageMonitorInternal.class);
19870                    if (dsm != null) {
19871                        dsm.checkMemory();
19872                    }
19873                }
19874                if(observer != null) {
19875                    try {
19876                        observer.onRemoveCompleted(packageName, succeeded);
19877                    } catch (RemoteException e) {
19878                        Log.i(TAG, "Observer no longer exists.");
19879                    }
19880                } //end if observer
19881            } //end run
19882        });
19883    }
19884
19885    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19886        if (packageName == null) {
19887            Slog.w(TAG, "Attempt to delete null packageName.");
19888            return false;
19889        }
19890
19891        // Try finding details about the requested package
19892        PackageParser.Package pkg;
19893        synchronized (mPackages) {
19894            pkg = mPackages.get(packageName);
19895            if (pkg == null) {
19896                final PackageSetting ps = mSettings.mPackages.get(packageName);
19897                if (ps != null) {
19898                    pkg = ps.pkg;
19899                }
19900            }
19901
19902            if (pkg == null) {
19903                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19904                return false;
19905            }
19906
19907            PackageSetting ps = (PackageSetting) pkg.mExtras;
19908            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19909        }
19910
19911        clearAppDataLIF(pkg, userId,
19912                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19913
19914        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19915        removeKeystoreDataIfNeeded(userId, appId);
19916
19917        UserManagerInternal umInternal = getUserManagerInternal();
19918        final int flags;
19919        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19920            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19921        } else if (umInternal.isUserRunning(userId)) {
19922            flags = StorageManager.FLAG_STORAGE_DE;
19923        } else {
19924            flags = 0;
19925        }
19926        prepareAppDataContentsLIF(pkg, userId, flags);
19927
19928        return true;
19929    }
19930
19931    /**
19932     * Reverts user permission state changes (permissions and flags) in
19933     * all packages for a given user.
19934     *
19935     * @param userId The device user for which to do a reset.
19936     */
19937    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19938        final int packageCount = mPackages.size();
19939        for (int i = 0; i < packageCount; i++) {
19940            PackageParser.Package pkg = mPackages.valueAt(i);
19941            PackageSetting ps = (PackageSetting) pkg.mExtras;
19942            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19943        }
19944    }
19945
19946    private void resetNetworkPolicies(int userId) {
19947        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19948    }
19949
19950    /**
19951     * Reverts user permission state changes (permissions and flags).
19952     *
19953     * @param ps The package for which to reset.
19954     * @param userId The device user for which to do a reset.
19955     */
19956    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19957            final PackageSetting ps, final int userId) {
19958        if (ps.pkg == null) {
19959            return;
19960        }
19961
19962        // These are flags that can change base on user actions.
19963        final int userSettableMask = FLAG_PERMISSION_USER_SET
19964                | FLAG_PERMISSION_USER_FIXED
19965                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19966                | FLAG_PERMISSION_REVIEW_REQUIRED;
19967
19968        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19969                | FLAG_PERMISSION_POLICY_FIXED;
19970
19971        boolean writeInstallPermissions = false;
19972        boolean writeRuntimePermissions = false;
19973
19974        final int permissionCount = ps.pkg.requestedPermissions.size();
19975        for (int i = 0; i < permissionCount; i++) {
19976            String permission = ps.pkg.requestedPermissions.get(i);
19977
19978            BasePermission bp = mSettings.mPermissions.get(permission);
19979            if (bp == null) {
19980                continue;
19981            }
19982
19983            // If shared user we just reset the state to which only this app contributed.
19984            if (ps.sharedUser != null) {
19985                boolean used = false;
19986                final int packageCount = ps.sharedUser.packages.size();
19987                for (int j = 0; j < packageCount; j++) {
19988                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19989                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19990                            && pkg.pkg.requestedPermissions.contains(permission)) {
19991                        used = true;
19992                        break;
19993                    }
19994                }
19995                if (used) {
19996                    continue;
19997                }
19998            }
19999
20000            PermissionsState permissionsState = ps.getPermissionsState();
20001
20002            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20003
20004            // Always clear the user settable flags.
20005            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20006                    bp.name) != null;
20007            // If permission review is enabled and this is a legacy app, mark the
20008            // permission as requiring a review as this is the initial state.
20009            int flags = 0;
20010            if (mPermissionReviewRequired
20011                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20012                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20013            }
20014            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20015                if (hasInstallState) {
20016                    writeInstallPermissions = true;
20017                } else {
20018                    writeRuntimePermissions = true;
20019                }
20020            }
20021
20022            // Below is only runtime permission handling.
20023            if (!bp.isRuntime()) {
20024                continue;
20025            }
20026
20027            // Never clobber system or policy.
20028            if ((oldFlags & policyOrSystemFlags) != 0) {
20029                continue;
20030            }
20031
20032            // If this permission was granted by default, make sure it is.
20033            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20034                if (permissionsState.grantRuntimePermission(bp, userId)
20035                        != PERMISSION_OPERATION_FAILURE) {
20036                    writeRuntimePermissions = true;
20037                }
20038            // If permission review is enabled the permissions for a legacy apps
20039            // are represented as constantly granted runtime ones, so don't revoke.
20040            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20041                // Otherwise, reset the permission.
20042                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20043                switch (revokeResult) {
20044                    case PERMISSION_OPERATION_SUCCESS:
20045                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20046                        writeRuntimePermissions = true;
20047                        final int appId = ps.appId;
20048                        mHandler.post(new Runnable() {
20049                            @Override
20050                            public void run() {
20051                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20052                            }
20053                        });
20054                    } break;
20055                }
20056            }
20057        }
20058
20059        // Synchronously write as we are taking permissions away.
20060        if (writeRuntimePermissions) {
20061            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20062        }
20063
20064        // Synchronously write as we are taking permissions away.
20065        if (writeInstallPermissions) {
20066            mSettings.writeLPr();
20067        }
20068    }
20069
20070    /**
20071     * Remove entries from the keystore daemon. Will only remove it if the
20072     * {@code appId} is valid.
20073     */
20074    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20075        if (appId < 0) {
20076            return;
20077        }
20078
20079        final KeyStore keyStore = KeyStore.getInstance();
20080        if (keyStore != null) {
20081            if (userId == UserHandle.USER_ALL) {
20082                for (final int individual : sUserManager.getUserIds()) {
20083                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20084                }
20085            } else {
20086                keyStore.clearUid(UserHandle.getUid(userId, appId));
20087            }
20088        } else {
20089            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20090        }
20091    }
20092
20093    @Override
20094    public void deleteApplicationCacheFiles(final String packageName,
20095            final IPackageDataObserver observer) {
20096        final int userId = UserHandle.getCallingUserId();
20097        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20098    }
20099
20100    @Override
20101    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20102            final IPackageDataObserver observer) {
20103        final int callingUid = Binder.getCallingUid();
20104        mContext.enforceCallingOrSelfPermission(
20105                android.Manifest.permission.DELETE_CACHE_FILES, null);
20106        enforceCrossUserPermission(callingUid, userId,
20107                /* requireFullPermission= */ true, /* checkShell= */ false,
20108                "delete application cache files");
20109        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20110                android.Manifest.permission.ACCESS_INSTANT_APPS);
20111
20112        final PackageParser.Package pkg;
20113        synchronized (mPackages) {
20114            pkg = mPackages.get(packageName);
20115        }
20116
20117        // Queue up an async operation since the package deletion may take a little while.
20118        mHandler.post(new Runnable() {
20119            public void run() {
20120                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20121                boolean doClearData = true;
20122                if (ps != null) {
20123                    final boolean targetIsInstantApp =
20124                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20125                    doClearData = !targetIsInstantApp
20126                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20127                }
20128                if (doClearData) {
20129                    synchronized (mInstallLock) {
20130                        final int flags = StorageManager.FLAG_STORAGE_DE
20131                                | StorageManager.FLAG_STORAGE_CE;
20132                        // We're only clearing cache files, so we don't care if the
20133                        // app is unfrozen and still able to run
20134                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20135                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20136                    }
20137                    clearExternalStorageDataSync(packageName, userId, false);
20138                }
20139                if (observer != null) {
20140                    try {
20141                        observer.onRemoveCompleted(packageName, true);
20142                    } catch (RemoteException e) {
20143                        Log.i(TAG, "Observer no longer exists.");
20144                    }
20145                }
20146            }
20147        });
20148    }
20149
20150    @Override
20151    public void getPackageSizeInfo(final String packageName, int userHandle,
20152            final IPackageStatsObserver observer) {
20153        throw new UnsupportedOperationException(
20154                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20155    }
20156
20157    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20158        final PackageSetting ps;
20159        synchronized (mPackages) {
20160            ps = mSettings.mPackages.get(packageName);
20161            if (ps == null) {
20162                Slog.w(TAG, "Failed to find settings for " + packageName);
20163                return false;
20164            }
20165        }
20166
20167        final String[] packageNames = { packageName };
20168        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20169        final String[] codePaths = { ps.codePathString };
20170
20171        try {
20172            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20173                    ps.appId, ceDataInodes, codePaths, stats);
20174
20175            // For now, ignore code size of packages on system partition
20176            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20177                stats.codeSize = 0;
20178            }
20179
20180            // External clients expect these to be tracked separately
20181            stats.dataSize -= stats.cacheSize;
20182
20183        } catch (InstallerException e) {
20184            Slog.w(TAG, String.valueOf(e));
20185            return false;
20186        }
20187
20188        return true;
20189    }
20190
20191    private int getUidTargetSdkVersionLockedLPr(int uid) {
20192        Object obj = mSettings.getUserIdLPr(uid);
20193        if (obj instanceof SharedUserSetting) {
20194            final SharedUserSetting sus = (SharedUserSetting) obj;
20195            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20196            final Iterator<PackageSetting> it = sus.packages.iterator();
20197            while (it.hasNext()) {
20198                final PackageSetting ps = it.next();
20199                if (ps.pkg != null) {
20200                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20201                    if (v < vers) vers = v;
20202                }
20203            }
20204            return vers;
20205        } else if (obj instanceof PackageSetting) {
20206            final PackageSetting ps = (PackageSetting) obj;
20207            if (ps.pkg != null) {
20208                return ps.pkg.applicationInfo.targetSdkVersion;
20209            }
20210        }
20211        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20212    }
20213
20214    @Override
20215    public void addPreferredActivity(IntentFilter filter, int match,
20216            ComponentName[] set, ComponentName activity, int userId) {
20217        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20218                "Adding preferred");
20219    }
20220
20221    private void addPreferredActivityInternal(IntentFilter filter, int match,
20222            ComponentName[] set, ComponentName activity, boolean always, int userId,
20223            String opname) {
20224        // writer
20225        int callingUid = Binder.getCallingUid();
20226        enforceCrossUserPermission(callingUid, userId,
20227                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20228        if (filter.countActions() == 0) {
20229            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20230            return;
20231        }
20232        synchronized (mPackages) {
20233            if (mContext.checkCallingOrSelfPermission(
20234                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20235                    != PackageManager.PERMISSION_GRANTED) {
20236                if (getUidTargetSdkVersionLockedLPr(callingUid)
20237                        < Build.VERSION_CODES.FROYO) {
20238                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20239                            + callingUid);
20240                    return;
20241                }
20242                mContext.enforceCallingOrSelfPermission(
20243                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20244            }
20245
20246            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20247            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20248                    + userId + ":");
20249            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20250            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20251            scheduleWritePackageRestrictionsLocked(userId);
20252            postPreferredActivityChangedBroadcast(userId);
20253        }
20254    }
20255
20256    private void postPreferredActivityChangedBroadcast(int userId) {
20257        mHandler.post(() -> {
20258            final IActivityManager am = ActivityManager.getService();
20259            if (am == null) {
20260                return;
20261            }
20262
20263            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20264            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20265            try {
20266                am.broadcastIntent(null, intent, null, null,
20267                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20268                        null, false, false, userId);
20269            } catch (RemoteException e) {
20270            }
20271        });
20272    }
20273
20274    @Override
20275    public void replacePreferredActivity(IntentFilter filter, int match,
20276            ComponentName[] set, ComponentName activity, int userId) {
20277        if (filter.countActions() != 1) {
20278            throw new IllegalArgumentException(
20279                    "replacePreferredActivity expects filter to have only 1 action.");
20280        }
20281        if (filter.countDataAuthorities() != 0
20282                || filter.countDataPaths() != 0
20283                || filter.countDataSchemes() > 1
20284                || filter.countDataTypes() != 0) {
20285            throw new IllegalArgumentException(
20286                    "replacePreferredActivity expects filter to have no data authorities, " +
20287                    "paths, or types; and at most one scheme.");
20288        }
20289
20290        final int callingUid = Binder.getCallingUid();
20291        enforceCrossUserPermission(callingUid, userId,
20292                true /* requireFullPermission */, false /* checkShell */,
20293                "replace preferred activity");
20294        synchronized (mPackages) {
20295            if (mContext.checkCallingOrSelfPermission(
20296                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20297                    != PackageManager.PERMISSION_GRANTED) {
20298                if (getUidTargetSdkVersionLockedLPr(callingUid)
20299                        < Build.VERSION_CODES.FROYO) {
20300                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20301                            + Binder.getCallingUid());
20302                    return;
20303                }
20304                mContext.enforceCallingOrSelfPermission(
20305                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20306            }
20307
20308            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20309            if (pir != null) {
20310                // Get all of the existing entries that exactly match this filter.
20311                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20312                if (existing != null && existing.size() == 1) {
20313                    PreferredActivity cur = existing.get(0);
20314                    if (DEBUG_PREFERRED) {
20315                        Slog.i(TAG, "Checking replace of preferred:");
20316                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20317                        if (!cur.mPref.mAlways) {
20318                            Slog.i(TAG, "  -- CUR; not mAlways!");
20319                        } else {
20320                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20321                            Slog.i(TAG, "  -- CUR: mSet="
20322                                    + Arrays.toString(cur.mPref.mSetComponents));
20323                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20324                            Slog.i(TAG, "  -- NEW: mMatch="
20325                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20326                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20327                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20328                        }
20329                    }
20330                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20331                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20332                            && cur.mPref.sameSet(set)) {
20333                        // Setting the preferred activity to what it happens to be already
20334                        if (DEBUG_PREFERRED) {
20335                            Slog.i(TAG, "Replacing with same preferred activity "
20336                                    + cur.mPref.mShortComponent + " for user "
20337                                    + userId + ":");
20338                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20339                        }
20340                        return;
20341                    }
20342                }
20343
20344                if (existing != null) {
20345                    if (DEBUG_PREFERRED) {
20346                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20347                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20348                    }
20349                    for (int i = 0; i < existing.size(); i++) {
20350                        PreferredActivity pa = existing.get(i);
20351                        if (DEBUG_PREFERRED) {
20352                            Slog.i(TAG, "Removing existing preferred activity "
20353                                    + pa.mPref.mComponent + ":");
20354                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20355                        }
20356                        pir.removeFilter(pa);
20357                    }
20358                }
20359            }
20360            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20361                    "Replacing preferred");
20362        }
20363    }
20364
20365    @Override
20366    public void clearPackagePreferredActivities(String packageName) {
20367        final int callingUid = Binder.getCallingUid();
20368        if (getInstantAppPackageName(callingUid) != null) {
20369            return;
20370        }
20371        // writer
20372        synchronized (mPackages) {
20373            PackageParser.Package pkg = mPackages.get(packageName);
20374            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20375                if (mContext.checkCallingOrSelfPermission(
20376                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20377                        != PackageManager.PERMISSION_GRANTED) {
20378                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20379                            < Build.VERSION_CODES.FROYO) {
20380                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20381                                + callingUid);
20382                        return;
20383                    }
20384                    mContext.enforceCallingOrSelfPermission(
20385                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20386                }
20387            }
20388            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20389            if (ps != null
20390                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20391                return;
20392            }
20393            int user = UserHandle.getCallingUserId();
20394            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20395                scheduleWritePackageRestrictionsLocked(user);
20396            }
20397        }
20398    }
20399
20400    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20401    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20402        ArrayList<PreferredActivity> removed = null;
20403        boolean changed = false;
20404        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20405            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20406            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20407            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20408                continue;
20409            }
20410            Iterator<PreferredActivity> it = pir.filterIterator();
20411            while (it.hasNext()) {
20412                PreferredActivity pa = it.next();
20413                // Mark entry for removal only if it matches the package name
20414                // and the entry is of type "always".
20415                if (packageName == null ||
20416                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20417                                && pa.mPref.mAlways)) {
20418                    if (removed == null) {
20419                        removed = new ArrayList<PreferredActivity>();
20420                    }
20421                    removed.add(pa);
20422                }
20423            }
20424            if (removed != null) {
20425                for (int j=0; j<removed.size(); j++) {
20426                    PreferredActivity pa = removed.get(j);
20427                    pir.removeFilter(pa);
20428                }
20429                changed = true;
20430            }
20431        }
20432        if (changed) {
20433            postPreferredActivityChangedBroadcast(userId);
20434        }
20435        return changed;
20436    }
20437
20438    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20439    private void clearIntentFilterVerificationsLPw(int userId) {
20440        final int packageCount = mPackages.size();
20441        for (int i = 0; i < packageCount; i++) {
20442            PackageParser.Package pkg = mPackages.valueAt(i);
20443            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20444        }
20445    }
20446
20447    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20448    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20449        if (userId == UserHandle.USER_ALL) {
20450            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20451                    sUserManager.getUserIds())) {
20452                for (int oneUserId : sUserManager.getUserIds()) {
20453                    scheduleWritePackageRestrictionsLocked(oneUserId);
20454                }
20455            }
20456        } else {
20457            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20458                scheduleWritePackageRestrictionsLocked(userId);
20459            }
20460        }
20461    }
20462
20463    /** Clears state for all users, and touches intent filter verification policy */
20464    void clearDefaultBrowserIfNeeded(String packageName) {
20465        for (int oneUserId : sUserManager.getUserIds()) {
20466            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20467        }
20468    }
20469
20470    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20471        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20472        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20473            if (packageName.equals(defaultBrowserPackageName)) {
20474                setDefaultBrowserPackageName(null, userId);
20475            }
20476        }
20477    }
20478
20479    @Override
20480    public void resetApplicationPreferences(int userId) {
20481        mContext.enforceCallingOrSelfPermission(
20482                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20483        final long identity = Binder.clearCallingIdentity();
20484        // writer
20485        try {
20486            synchronized (mPackages) {
20487                clearPackagePreferredActivitiesLPw(null, userId);
20488                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20489                // TODO: We have to reset the default SMS and Phone. This requires
20490                // significant refactoring to keep all default apps in the package
20491                // manager (cleaner but more work) or have the services provide
20492                // callbacks to the package manager to request a default app reset.
20493                applyFactoryDefaultBrowserLPw(userId);
20494                clearIntentFilterVerificationsLPw(userId);
20495                primeDomainVerificationsLPw(userId);
20496                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20497                scheduleWritePackageRestrictionsLocked(userId);
20498            }
20499            resetNetworkPolicies(userId);
20500        } finally {
20501            Binder.restoreCallingIdentity(identity);
20502        }
20503    }
20504
20505    @Override
20506    public int getPreferredActivities(List<IntentFilter> outFilters,
20507            List<ComponentName> outActivities, String packageName) {
20508        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20509            return 0;
20510        }
20511        int num = 0;
20512        final int userId = UserHandle.getCallingUserId();
20513        // reader
20514        synchronized (mPackages) {
20515            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20516            if (pir != null) {
20517                final Iterator<PreferredActivity> it = pir.filterIterator();
20518                while (it.hasNext()) {
20519                    final PreferredActivity pa = it.next();
20520                    if (packageName == null
20521                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20522                                    && pa.mPref.mAlways)) {
20523                        if (outFilters != null) {
20524                            outFilters.add(new IntentFilter(pa));
20525                        }
20526                        if (outActivities != null) {
20527                            outActivities.add(pa.mPref.mComponent);
20528                        }
20529                    }
20530                }
20531            }
20532        }
20533
20534        return num;
20535    }
20536
20537    @Override
20538    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20539            int userId) {
20540        int callingUid = Binder.getCallingUid();
20541        if (callingUid != Process.SYSTEM_UID) {
20542            throw new SecurityException(
20543                    "addPersistentPreferredActivity can only be run by the system");
20544        }
20545        if (filter.countActions() == 0) {
20546            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20547            return;
20548        }
20549        synchronized (mPackages) {
20550            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20551                    ":");
20552            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20553            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20554                    new PersistentPreferredActivity(filter, activity));
20555            scheduleWritePackageRestrictionsLocked(userId);
20556            postPreferredActivityChangedBroadcast(userId);
20557        }
20558    }
20559
20560    @Override
20561    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20562        int callingUid = Binder.getCallingUid();
20563        if (callingUid != Process.SYSTEM_UID) {
20564            throw new SecurityException(
20565                    "clearPackagePersistentPreferredActivities can only be run by the system");
20566        }
20567        ArrayList<PersistentPreferredActivity> removed = null;
20568        boolean changed = false;
20569        synchronized (mPackages) {
20570            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20571                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20572                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20573                        .valueAt(i);
20574                if (userId != thisUserId) {
20575                    continue;
20576                }
20577                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20578                while (it.hasNext()) {
20579                    PersistentPreferredActivity ppa = it.next();
20580                    // Mark entry for removal only if it matches the package name.
20581                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20582                        if (removed == null) {
20583                            removed = new ArrayList<PersistentPreferredActivity>();
20584                        }
20585                        removed.add(ppa);
20586                    }
20587                }
20588                if (removed != null) {
20589                    for (int j=0; j<removed.size(); j++) {
20590                        PersistentPreferredActivity ppa = removed.get(j);
20591                        ppir.removeFilter(ppa);
20592                    }
20593                    changed = true;
20594                }
20595            }
20596
20597            if (changed) {
20598                scheduleWritePackageRestrictionsLocked(userId);
20599                postPreferredActivityChangedBroadcast(userId);
20600            }
20601        }
20602    }
20603
20604    /**
20605     * Common machinery for picking apart a restored XML blob and passing
20606     * it to a caller-supplied functor to be applied to the running system.
20607     */
20608    private void restoreFromXml(XmlPullParser parser, int userId,
20609            String expectedStartTag, BlobXmlRestorer functor)
20610            throws IOException, XmlPullParserException {
20611        int type;
20612        while ((type = parser.next()) != XmlPullParser.START_TAG
20613                && type != XmlPullParser.END_DOCUMENT) {
20614        }
20615        if (type != XmlPullParser.START_TAG) {
20616            // oops didn't find a start tag?!
20617            if (DEBUG_BACKUP) {
20618                Slog.e(TAG, "Didn't find start tag during restore");
20619            }
20620            return;
20621        }
20622Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20623        // this is supposed to be TAG_PREFERRED_BACKUP
20624        if (!expectedStartTag.equals(parser.getName())) {
20625            if (DEBUG_BACKUP) {
20626                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20627            }
20628            return;
20629        }
20630
20631        // skip interfering stuff, then we're aligned with the backing implementation
20632        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20633Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20634        functor.apply(parser, userId);
20635    }
20636
20637    private interface BlobXmlRestorer {
20638        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20639    }
20640
20641    /**
20642     * Non-Binder method, support for the backup/restore mechanism: write the
20643     * full set of preferred activities in its canonical XML format.  Returns the
20644     * XML output as a byte array, or null if there is none.
20645     */
20646    @Override
20647    public byte[] getPreferredActivityBackup(int userId) {
20648        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20649            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20650        }
20651
20652        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20653        try {
20654            final XmlSerializer serializer = new FastXmlSerializer();
20655            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20656            serializer.startDocument(null, true);
20657            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20658
20659            synchronized (mPackages) {
20660                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20661            }
20662
20663            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20664            serializer.endDocument();
20665            serializer.flush();
20666        } catch (Exception e) {
20667            if (DEBUG_BACKUP) {
20668                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20669            }
20670            return null;
20671        }
20672
20673        return dataStream.toByteArray();
20674    }
20675
20676    @Override
20677    public void restorePreferredActivities(byte[] backup, int userId) {
20678        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20679            throw new SecurityException("Only the system may call restorePreferredActivities()");
20680        }
20681
20682        try {
20683            final XmlPullParser parser = Xml.newPullParser();
20684            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20685            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20686                    new BlobXmlRestorer() {
20687                        @Override
20688                        public void apply(XmlPullParser parser, int userId)
20689                                throws XmlPullParserException, IOException {
20690                            synchronized (mPackages) {
20691                                mSettings.readPreferredActivitiesLPw(parser, userId);
20692                            }
20693                        }
20694                    } );
20695        } catch (Exception e) {
20696            if (DEBUG_BACKUP) {
20697                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20698            }
20699        }
20700    }
20701
20702    /**
20703     * Non-Binder method, support for the backup/restore mechanism: write the
20704     * default browser (etc) settings in its canonical XML format.  Returns the default
20705     * browser XML representation as a byte array, or null if there is none.
20706     */
20707    @Override
20708    public byte[] getDefaultAppsBackup(int userId) {
20709        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20710            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20711        }
20712
20713        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20714        try {
20715            final XmlSerializer serializer = new FastXmlSerializer();
20716            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20717            serializer.startDocument(null, true);
20718            serializer.startTag(null, TAG_DEFAULT_APPS);
20719
20720            synchronized (mPackages) {
20721                mSettings.writeDefaultAppsLPr(serializer, userId);
20722            }
20723
20724            serializer.endTag(null, TAG_DEFAULT_APPS);
20725            serializer.endDocument();
20726            serializer.flush();
20727        } catch (Exception e) {
20728            if (DEBUG_BACKUP) {
20729                Slog.e(TAG, "Unable to write default apps for backup", e);
20730            }
20731            return null;
20732        }
20733
20734        return dataStream.toByteArray();
20735    }
20736
20737    @Override
20738    public void restoreDefaultApps(byte[] backup, int userId) {
20739        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20740            throw new SecurityException("Only the system may call restoreDefaultApps()");
20741        }
20742
20743        try {
20744            final XmlPullParser parser = Xml.newPullParser();
20745            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20746            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20747                    new BlobXmlRestorer() {
20748                        @Override
20749                        public void apply(XmlPullParser parser, int userId)
20750                                throws XmlPullParserException, IOException {
20751                            synchronized (mPackages) {
20752                                mSettings.readDefaultAppsLPw(parser, userId);
20753                            }
20754                        }
20755                    } );
20756        } catch (Exception e) {
20757            if (DEBUG_BACKUP) {
20758                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20759            }
20760        }
20761    }
20762
20763    @Override
20764    public byte[] getIntentFilterVerificationBackup(int userId) {
20765        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20766            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20767        }
20768
20769        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20770        try {
20771            final XmlSerializer serializer = new FastXmlSerializer();
20772            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20773            serializer.startDocument(null, true);
20774            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20775
20776            synchronized (mPackages) {
20777                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20778            }
20779
20780            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20781            serializer.endDocument();
20782            serializer.flush();
20783        } catch (Exception e) {
20784            if (DEBUG_BACKUP) {
20785                Slog.e(TAG, "Unable to write default apps for backup", e);
20786            }
20787            return null;
20788        }
20789
20790        return dataStream.toByteArray();
20791    }
20792
20793    @Override
20794    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20795        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20796            throw new SecurityException("Only the system may call restorePreferredActivities()");
20797        }
20798
20799        try {
20800            final XmlPullParser parser = Xml.newPullParser();
20801            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20802            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20803                    new BlobXmlRestorer() {
20804                        @Override
20805                        public void apply(XmlPullParser parser, int userId)
20806                                throws XmlPullParserException, IOException {
20807                            synchronized (mPackages) {
20808                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20809                                mSettings.writeLPr();
20810                            }
20811                        }
20812                    } );
20813        } catch (Exception e) {
20814            if (DEBUG_BACKUP) {
20815                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20816            }
20817        }
20818    }
20819
20820    @Override
20821    public byte[] getPermissionGrantBackup(int userId) {
20822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20823            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20824        }
20825
20826        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20827        try {
20828            final XmlSerializer serializer = new FastXmlSerializer();
20829            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20830            serializer.startDocument(null, true);
20831            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20832
20833            synchronized (mPackages) {
20834                serializeRuntimePermissionGrantsLPr(serializer, userId);
20835            }
20836
20837            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20838            serializer.endDocument();
20839            serializer.flush();
20840        } catch (Exception e) {
20841            if (DEBUG_BACKUP) {
20842                Slog.e(TAG, "Unable to write default apps for backup", e);
20843            }
20844            return null;
20845        }
20846
20847        return dataStream.toByteArray();
20848    }
20849
20850    @Override
20851    public void restorePermissionGrants(byte[] backup, int userId) {
20852        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20853            throw new SecurityException("Only the system may call restorePermissionGrants()");
20854        }
20855
20856        try {
20857            final XmlPullParser parser = Xml.newPullParser();
20858            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20859            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20860                    new BlobXmlRestorer() {
20861                        @Override
20862                        public void apply(XmlPullParser parser, int userId)
20863                                throws XmlPullParserException, IOException {
20864                            synchronized (mPackages) {
20865                                processRestoredPermissionGrantsLPr(parser, userId);
20866                            }
20867                        }
20868                    } );
20869        } catch (Exception e) {
20870            if (DEBUG_BACKUP) {
20871                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20872            }
20873        }
20874    }
20875
20876    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20877            throws IOException {
20878        serializer.startTag(null, TAG_ALL_GRANTS);
20879
20880        final int N = mSettings.mPackages.size();
20881        for (int i = 0; i < N; i++) {
20882            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20883            boolean pkgGrantsKnown = false;
20884
20885            PermissionsState packagePerms = ps.getPermissionsState();
20886
20887            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20888                final int grantFlags = state.getFlags();
20889                // only look at grants that are not system/policy fixed
20890                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20891                    final boolean isGranted = state.isGranted();
20892                    // And only back up the user-twiddled state bits
20893                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20894                        final String packageName = mSettings.mPackages.keyAt(i);
20895                        if (!pkgGrantsKnown) {
20896                            serializer.startTag(null, TAG_GRANT);
20897                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20898                            pkgGrantsKnown = true;
20899                        }
20900
20901                        final boolean userSet =
20902                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20903                        final boolean userFixed =
20904                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20905                        final boolean revoke =
20906                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20907
20908                        serializer.startTag(null, TAG_PERMISSION);
20909                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20910                        if (isGranted) {
20911                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20912                        }
20913                        if (userSet) {
20914                            serializer.attribute(null, ATTR_USER_SET, "true");
20915                        }
20916                        if (userFixed) {
20917                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20918                        }
20919                        if (revoke) {
20920                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20921                        }
20922                        serializer.endTag(null, TAG_PERMISSION);
20923                    }
20924                }
20925            }
20926
20927            if (pkgGrantsKnown) {
20928                serializer.endTag(null, TAG_GRANT);
20929            }
20930        }
20931
20932        serializer.endTag(null, TAG_ALL_GRANTS);
20933    }
20934
20935    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20936            throws XmlPullParserException, IOException {
20937        String pkgName = null;
20938        int outerDepth = parser.getDepth();
20939        int type;
20940        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20941                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20942            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20943                continue;
20944            }
20945
20946            final String tagName = parser.getName();
20947            if (tagName.equals(TAG_GRANT)) {
20948                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20949                if (DEBUG_BACKUP) {
20950                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20951                }
20952            } else if (tagName.equals(TAG_PERMISSION)) {
20953
20954                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20955                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20956
20957                int newFlagSet = 0;
20958                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20959                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20960                }
20961                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20962                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20963                }
20964                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20965                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20966                }
20967                if (DEBUG_BACKUP) {
20968                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20969                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20970                }
20971                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20972                if (ps != null) {
20973                    // Already installed so we apply the grant immediately
20974                    if (DEBUG_BACKUP) {
20975                        Slog.v(TAG, "        + already installed; applying");
20976                    }
20977                    PermissionsState perms = ps.getPermissionsState();
20978                    BasePermission bp = mSettings.mPermissions.get(permName);
20979                    if (bp != null) {
20980                        if (isGranted) {
20981                            perms.grantRuntimePermission(bp, userId);
20982                        }
20983                        if (newFlagSet != 0) {
20984                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20985                        }
20986                    }
20987                } else {
20988                    // Need to wait for post-restore install to apply the grant
20989                    if (DEBUG_BACKUP) {
20990                        Slog.v(TAG, "        - not yet installed; saving for later");
20991                    }
20992                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20993                            isGranted, newFlagSet, userId);
20994                }
20995            } else {
20996                PackageManagerService.reportSettingsProblem(Log.WARN,
20997                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20998                XmlUtils.skipCurrentTag(parser);
20999            }
21000        }
21001
21002        scheduleWriteSettingsLocked();
21003        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21004    }
21005
21006    @Override
21007    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21008            int sourceUserId, int targetUserId, int flags) {
21009        mContext.enforceCallingOrSelfPermission(
21010                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21011        int callingUid = Binder.getCallingUid();
21012        enforceOwnerRights(ownerPackage, callingUid);
21013        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21014        if (intentFilter.countActions() == 0) {
21015            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21016            return;
21017        }
21018        synchronized (mPackages) {
21019            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21020                    ownerPackage, targetUserId, flags);
21021            CrossProfileIntentResolver resolver =
21022                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21023            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21024            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21025            if (existing != null) {
21026                int size = existing.size();
21027                for (int i = 0; i < size; i++) {
21028                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21029                        return;
21030                    }
21031                }
21032            }
21033            resolver.addFilter(newFilter);
21034            scheduleWritePackageRestrictionsLocked(sourceUserId);
21035        }
21036    }
21037
21038    @Override
21039    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21040        mContext.enforceCallingOrSelfPermission(
21041                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21042        final int callingUid = Binder.getCallingUid();
21043        enforceOwnerRights(ownerPackage, callingUid);
21044        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21045        synchronized (mPackages) {
21046            CrossProfileIntentResolver resolver =
21047                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21048            ArraySet<CrossProfileIntentFilter> set =
21049                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21050            for (CrossProfileIntentFilter filter : set) {
21051                if (filter.getOwnerPackage().equals(ownerPackage)) {
21052                    resolver.removeFilter(filter);
21053                }
21054            }
21055            scheduleWritePackageRestrictionsLocked(sourceUserId);
21056        }
21057    }
21058
21059    // Enforcing that callingUid is owning pkg on userId
21060    private void enforceOwnerRights(String pkg, int callingUid) {
21061        // The system owns everything.
21062        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21063            return;
21064        }
21065        final int callingUserId = UserHandle.getUserId(callingUid);
21066        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21067        if (pi == null) {
21068            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21069                    + callingUserId);
21070        }
21071        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21072            throw new SecurityException("Calling uid " + callingUid
21073                    + " does not own package " + pkg);
21074        }
21075    }
21076
21077    @Override
21078    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21079        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21080            return null;
21081        }
21082        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21083    }
21084
21085    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21086        UserManagerService ums = UserManagerService.getInstance();
21087        if (ums != null) {
21088            final UserInfo parent = ums.getProfileParent(userId);
21089            final int launcherUid = (parent != null) ? parent.id : userId;
21090            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21091            if (launcherComponent != null) {
21092                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21093                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21094                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21095                        .setPackage(launcherComponent.getPackageName());
21096                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21097            }
21098        }
21099    }
21100
21101    /**
21102     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21103     * then reports the most likely home activity or null if there are more than one.
21104     */
21105    private ComponentName getDefaultHomeActivity(int userId) {
21106        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21107        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21108        if (cn != null) {
21109            return cn;
21110        }
21111
21112        // Find the launcher with the highest priority and return that component if there are no
21113        // other home activity with the same priority.
21114        int lastPriority = Integer.MIN_VALUE;
21115        ComponentName lastComponent = null;
21116        final int size = allHomeCandidates.size();
21117        for (int i = 0; i < size; i++) {
21118            final ResolveInfo ri = allHomeCandidates.get(i);
21119            if (ri.priority > lastPriority) {
21120                lastComponent = ri.activityInfo.getComponentName();
21121                lastPriority = ri.priority;
21122            } else if (ri.priority == lastPriority) {
21123                // Two components found with same priority.
21124                lastComponent = null;
21125            }
21126        }
21127        return lastComponent;
21128    }
21129
21130    private Intent getHomeIntent() {
21131        Intent intent = new Intent(Intent.ACTION_MAIN);
21132        intent.addCategory(Intent.CATEGORY_HOME);
21133        intent.addCategory(Intent.CATEGORY_DEFAULT);
21134        return intent;
21135    }
21136
21137    private IntentFilter getHomeFilter() {
21138        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21139        filter.addCategory(Intent.CATEGORY_HOME);
21140        filter.addCategory(Intent.CATEGORY_DEFAULT);
21141        return filter;
21142    }
21143
21144    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21145            int userId) {
21146        Intent intent  = getHomeIntent();
21147        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21148                PackageManager.GET_META_DATA, userId);
21149        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21150                true, false, false, userId);
21151
21152        allHomeCandidates.clear();
21153        if (list != null) {
21154            for (ResolveInfo ri : list) {
21155                allHomeCandidates.add(ri);
21156            }
21157        }
21158        return (preferred == null || preferred.activityInfo == null)
21159                ? null
21160                : new ComponentName(preferred.activityInfo.packageName,
21161                        preferred.activityInfo.name);
21162    }
21163
21164    @Override
21165    public void setHomeActivity(ComponentName comp, int userId) {
21166        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21167            return;
21168        }
21169        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21170        getHomeActivitiesAsUser(homeActivities, userId);
21171
21172        boolean found = false;
21173
21174        final int size = homeActivities.size();
21175        final ComponentName[] set = new ComponentName[size];
21176        for (int i = 0; i < size; i++) {
21177            final ResolveInfo candidate = homeActivities.get(i);
21178            final ActivityInfo info = candidate.activityInfo;
21179            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21180            set[i] = activityName;
21181            if (!found && activityName.equals(comp)) {
21182                found = true;
21183            }
21184        }
21185        if (!found) {
21186            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21187                    + userId);
21188        }
21189        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21190                set, comp, userId);
21191    }
21192
21193    private @Nullable String getSetupWizardPackageName() {
21194        final Intent intent = new Intent(Intent.ACTION_MAIN);
21195        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21196
21197        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21198                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21199                        | MATCH_DISABLED_COMPONENTS,
21200                UserHandle.myUserId());
21201        if (matches.size() == 1) {
21202            return matches.get(0).getComponentInfo().packageName;
21203        } else {
21204            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21205                    + ": matches=" + matches);
21206            return null;
21207        }
21208    }
21209
21210    private @Nullable String getStorageManagerPackageName() {
21211        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21212
21213        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21214                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21215                        | MATCH_DISABLED_COMPONENTS,
21216                UserHandle.myUserId());
21217        if (matches.size() == 1) {
21218            return matches.get(0).getComponentInfo().packageName;
21219        } else {
21220            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21221                    + matches.size() + ": matches=" + matches);
21222            return null;
21223        }
21224    }
21225
21226    @Override
21227    public void setApplicationEnabledSetting(String appPackageName,
21228            int newState, int flags, int userId, String callingPackage) {
21229        if (!sUserManager.exists(userId)) return;
21230        if (callingPackage == null) {
21231            callingPackage = Integer.toString(Binder.getCallingUid());
21232        }
21233        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21234    }
21235
21236    @Override
21237    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21238        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21239        synchronized (mPackages) {
21240            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21241            if (pkgSetting != null) {
21242                pkgSetting.setUpdateAvailable(updateAvailable);
21243            }
21244        }
21245    }
21246
21247    @Override
21248    public void setComponentEnabledSetting(ComponentName componentName,
21249            int newState, int flags, int userId) {
21250        if (!sUserManager.exists(userId)) return;
21251        setEnabledSetting(componentName.getPackageName(),
21252                componentName.getClassName(), newState, flags, userId, null);
21253    }
21254
21255    private void setEnabledSetting(final String packageName, String className, int newState,
21256            final int flags, int userId, String callingPackage) {
21257        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21258              || newState == COMPONENT_ENABLED_STATE_ENABLED
21259              || newState == COMPONENT_ENABLED_STATE_DISABLED
21260              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21261              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21262            throw new IllegalArgumentException("Invalid new component state: "
21263                    + newState);
21264        }
21265        PackageSetting pkgSetting;
21266        final int callingUid = Binder.getCallingUid();
21267        final int permission;
21268        if (callingUid == Process.SYSTEM_UID) {
21269            permission = PackageManager.PERMISSION_GRANTED;
21270        } else {
21271            permission = mContext.checkCallingOrSelfPermission(
21272                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21273        }
21274        enforceCrossUserPermission(callingUid, userId,
21275                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21276        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21277        boolean sendNow = false;
21278        boolean isApp = (className == null);
21279        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21280        String componentName = isApp ? packageName : className;
21281        int packageUid = -1;
21282        ArrayList<String> components;
21283
21284        // reader
21285        synchronized (mPackages) {
21286            pkgSetting = mSettings.mPackages.get(packageName);
21287            if (pkgSetting == null) {
21288                if (!isCallerInstantApp) {
21289                    if (className == null) {
21290                        throw new IllegalArgumentException("Unknown package: " + packageName);
21291                    }
21292                    throw new IllegalArgumentException(
21293                            "Unknown component: " + packageName + "/" + className);
21294                } else {
21295                    // throw SecurityException to prevent leaking package information
21296                    throw new SecurityException(
21297                            "Attempt to change component state; "
21298                            + "pid=" + Binder.getCallingPid()
21299                            + ", uid=" + callingUid
21300                            + (className == null
21301                                    ? ", package=" + packageName
21302                                    : ", component=" + packageName + "/" + className));
21303                }
21304            }
21305        }
21306
21307        // Limit who can change which apps
21308        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21309            // Don't allow apps that don't have permission to modify other apps
21310            if (!allowedByPermission
21311                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21312                throw new SecurityException(
21313                        "Attempt to change component state; "
21314                        + "pid=" + Binder.getCallingPid()
21315                        + ", uid=" + callingUid
21316                        + (className == null
21317                                ? ", package=" + packageName
21318                                : ", component=" + packageName + "/" + className));
21319            }
21320            // Don't allow changing protected packages.
21321            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21322                throw new SecurityException("Cannot disable a protected package: " + packageName);
21323            }
21324        }
21325
21326        synchronized (mPackages) {
21327            if (callingUid == Process.SHELL_UID
21328                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21329                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21330                // unless it is a test package.
21331                int oldState = pkgSetting.getEnabled(userId);
21332                if (className == null
21333                    &&
21334                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21335                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21336                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21337                    &&
21338                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21339                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21340                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21341                    // ok
21342                } else {
21343                    throw new SecurityException(
21344                            "Shell cannot change component state for " + packageName + "/"
21345                            + className + " to " + newState);
21346                }
21347            }
21348            if (className == null) {
21349                // We're dealing with an application/package level state change
21350                if (pkgSetting.getEnabled(userId) == newState) {
21351                    // Nothing to do
21352                    return;
21353                }
21354                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21355                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21356                    // Don't care about who enables an app.
21357                    callingPackage = null;
21358                }
21359                pkgSetting.setEnabled(newState, userId, callingPackage);
21360                // pkgSetting.pkg.mSetEnabled = newState;
21361            } else {
21362                // We're dealing with a component level state change
21363                // First, verify that this is a valid class name.
21364                PackageParser.Package pkg = pkgSetting.pkg;
21365                if (pkg == null || !pkg.hasComponentClassName(className)) {
21366                    if (pkg != null &&
21367                            pkg.applicationInfo.targetSdkVersion >=
21368                                    Build.VERSION_CODES.JELLY_BEAN) {
21369                        throw new IllegalArgumentException("Component class " + className
21370                                + " does not exist in " + packageName);
21371                    } else {
21372                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21373                                + className + " does not exist in " + packageName);
21374                    }
21375                }
21376                switch (newState) {
21377                case COMPONENT_ENABLED_STATE_ENABLED:
21378                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21379                        return;
21380                    }
21381                    break;
21382                case COMPONENT_ENABLED_STATE_DISABLED:
21383                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21384                        return;
21385                    }
21386                    break;
21387                case COMPONENT_ENABLED_STATE_DEFAULT:
21388                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21389                        return;
21390                    }
21391                    break;
21392                default:
21393                    Slog.e(TAG, "Invalid new component state: " + newState);
21394                    return;
21395                }
21396            }
21397            scheduleWritePackageRestrictionsLocked(userId);
21398            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21399            final long callingId = Binder.clearCallingIdentity();
21400            try {
21401                updateInstantAppInstallerLocked(packageName);
21402            } finally {
21403                Binder.restoreCallingIdentity(callingId);
21404            }
21405            components = mPendingBroadcasts.get(userId, packageName);
21406            final boolean newPackage = components == null;
21407            if (newPackage) {
21408                components = new ArrayList<String>();
21409            }
21410            if (!components.contains(componentName)) {
21411                components.add(componentName);
21412            }
21413            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21414                sendNow = true;
21415                // Purge entry from pending broadcast list if another one exists already
21416                // since we are sending one right away.
21417                mPendingBroadcasts.remove(userId, packageName);
21418            } else {
21419                if (newPackage) {
21420                    mPendingBroadcasts.put(userId, packageName, components);
21421                }
21422                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21423                    // Schedule a message
21424                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21425                }
21426            }
21427        }
21428
21429        long callingId = Binder.clearCallingIdentity();
21430        try {
21431            if (sendNow) {
21432                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21433                sendPackageChangedBroadcast(packageName,
21434                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21435            }
21436        } finally {
21437            Binder.restoreCallingIdentity(callingId);
21438        }
21439    }
21440
21441    @Override
21442    public void flushPackageRestrictionsAsUser(int userId) {
21443        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21444            return;
21445        }
21446        if (!sUserManager.exists(userId)) {
21447            return;
21448        }
21449        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21450                false /* checkShell */, "flushPackageRestrictions");
21451        synchronized (mPackages) {
21452            mSettings.writePackageRestrictionsLPr(userId);
21453            mDirtyUsers.remove(userId);
21454            if (mDirtyUsers.isEmpty()) {
21455                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21456            }
21457        }
21458    }
21459
21460    private void sendPackageChangedBroadcast(String packageName,
21461            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21462        if (DEBUG_INSTALL)
21463            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21464                    + componentNames);
21465        Bundle extras = new Bundle(4);
21466        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21467        String nameList[] = new String[componentNames.size()];
21468        componentNames.toArray(nameList);
21469        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21470        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21471        extras.putInt(Intent.EXTRA_UID, packageUid);
21472        // If this is not reporting a change of the overall package, then only send it
21473        // to registered receivers.  We don't want to launch a swath of apps for every
21474        // little component state change.
21475        final int flags = !componentNames.contains(packageName)
21476                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21477        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21478                new int[] {UserHandle.getUserId(packageUid)});
21479    }
21480
21481    @Override
21482    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21483        if (!sUserManager.exists(userId)) return;
21484        final int callingUid = Binder.getCallingUid();
21485        if (getInstantAppPackageName(callingUid) != null) {
21486            return;
21487        }
21488        final int permission = mContext.checkCallingOrSelfPermission(
21489                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21490        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21491        enforceCrossUserPermission(callingUid, userId,
21492                true /* requireFullPermission */, true /* checkShell */, "stop package");
21493        // writer
21494        synchronized (mPackages) {
21495            final PackageSetting ps = mSettings.mPackages.get(packageName);
21496            if (!filterAppAccessLPr(ps, callingUid, userId)
21497                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21498                            allowedByPermission, callingUid, userId)) {
21499                scheduleWritePackageRestrictionsLocked(userId);
21500            }
21501        }
21502    }
21503
21504    @Override
21505    public String getInstallerPackageName(String packageName) {
21506        final int callingUid = Binder.getCallingUid();
21507        if (getInstantAppPackageName(callingUid) != null) {
21508            return null;
21509        }
21510        // reader
21511        synchronized (mPackages) {
21512            final PackageSetting ps = mSettings.mPackages.get(packageName);
21513            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21514                return null;
21515            }
21516            return mSettings.getInstallerPackageNameLPr(packageName);
21517        }
21518    }
21519
21520    public boolean isOrphaned(String packageName) {
21521        // reader
21522        synchronized (mPackages) {
21523            return mSettings.isOrphaned(packageName);
21524        }
21525    }
21526
21527    @Override
21528    public int getApplicationEnabledSetting(String packageName, int userId) {
21529        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21530        int callingUid = Binder.getCallingUid();
21531        enforceCrossUserPermission(callingUid, userId,
21532                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21533        // reader
21534        synchronized (mPackages) {
21535            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21536                return COMPONENT_ENABLED_STATE_DISABLED;
21537            }
21538            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21539        }
21540    }
21541
21542    @Override
21543    public int getComponentEnabledSetting(ComponentName component, int userId) {
21544        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21545        int callingUid = Binder.getCallingUid();
21546        enforceCrossUserPermission(callingUid, userId,
21547                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21548        synchronized (mPackages) {
21549            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21550                    component, TYPE_UNKNOWN, userId)) {
21551                return COMPONENT_ENABLED_STATE_DISABLED;
21552            }
21553            return mSettings.getComponentEnabledSettingLPr(component, userId);
21554        }
21555    }
21556
21557    @Override
21558    public void enterSafeMode() {
21559        enforceSystemOrRoot("Only the system can request entering safe mode");
21560
21561        if (!mSystemReady) {
21562            mSafeMode = true;
21563        }
21564    }
21565
21566    @Override
21567    public void systemReady() {
21568        enforceSystemOrRoot("Only the system can claim the system is ready");
21569
21570        mSystemReady = true;
21571        final ContentResolver resolver = mContext.getContentResolver();
21572        ContentObserver co = new ContentObserver(mHandler) {
21573            @Override
21574            public void onChange(boolean selfChange) {
21575                mEphemeralAppsDisabled =
21576                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21577                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21578            }
21579        };
21580        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21581                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21582                false, co, UserHandle.USER_SYSTEM);
21583        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21584                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21585        co.onChange(true);
21586
21587        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21588        // disabled after already being started.
21589        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21590                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21591
21592        // Read the compatibilty setting when the system is ready.
21593        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21594                mContext.getContentResolver(),
21595                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21596        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21597        if (DEBUG_SETTINGS) {
21598            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21599        }
21600
21601        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21602
21603        synchronized (mPackages) {
21604            // Verify that all of the preferred activity components actually
21605            // exist.  It is possible for applications to be updated and at
21606            // that point remove a previously declared activity component that
21607            // had been set as a preferred activity.  We try to clean this up
21608            // the next time we encounter that preferred activity, but it is
21609            // possible for the user flow to never be able to return to that
21610            // situation so here we do a sanity check to make sure we haven't
21611            // left any junk around.
21612            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21613            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21614                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21615                removed.clear();
21616                for (PreferredActivity pa : pir.filterSet()) {
21617                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21618                        removed.add(pa);
21619                    }
21620                }
21621                if (removed.size() > 0) {
21622                    for (int r=0; r<removed.size(); r++) {
21623                        PreferredActivity pa = removed.get(r);
21624                        Slog.w(TAG, "Removing dangling preferred activity: "
21625                                + pa.mPref.mComponent);
21626                        pir.removeFilter(pa);
21627                    }
21628                    mSettings.writePackageRestrictionsLPr(
21629                            mSettings.mPreferredActivities.keyAt(i));
21630                }
21631            }
21632
21633            for (int userId : UserManagerService.getInstance().getUserIds()) {
21634                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21635                    grantPermissionsUserIds = ArrayUtils.appendInt(
21636                            grantPermissionsUserIds, userId);
21637                }
21638            }
21639        }
21640        sUserManager.systemReady();
21641
21642        // If we upgraded grant all default permissions before kicking off.
21643        for (int userId : grantPermissionsUserIds) {
21644            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21645        }
21646
21647        // If we did not grant default permissions, we preload from this the
21648        // default permission exceptions lazily to ensure we don't hit the
21649        // disk on a new user creation.
21650        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21651            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21652        }
21653
21654        // Kick off any messages waiting for system ready
21655        if (mPostSystemReadyMessages != null) {
21656            for (Message msg : mPostSystemReadyMessages) {
21657                msg.sendToTarget();
21658            }
21659            mPostSystemReadyMessages = null;
21660        }
21661
21662        // Watch for external volumes that come and go over time
21663        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21664        storage.registerListener(mStorageListener);
21665
21666        mInstallerService.systemReady();
21667        mPackageDexOptimizer.systemReady();
21668
21669        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21670                StorageManagerInternal.class);
21671        StorageManagerInternal.addExternalStoragePolicy(
21672                new StorageManagerInternal.ExternalStorageMountPolicy() {
21673            @Override
21674            public int getMountMode(int uid, String packageName) {
21675                if (Process.isIsolated(uid)) {
21676                    return Zygote.MOUNT_EXTERNAL_NONE;
21677                }
21678                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21679                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21680                }
21681                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21682                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21683                }
21684                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21685                    return Zygote.MOUNT_EXTERNAL_READ;
21686                }
21687                return Zygote.MOUNT_EXTERNAL_WRITE;
21688            }
21689
21690            @Override
21691            public boolean hasExternalStorage(int uid, String packageName) {
21692                return true;
21693            }
21694        });
21695
21696        // Now that we're mostly running, clean up stale users and apps
21697        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21698        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21699
21700        if (mPrivappPermissionsViolations != null) {
21701            Slog.wtf(TAG,"Signature|privileged permissions not in "
21702                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21703            mPrivappPermissionsViolations = null;
21704        }
21705    }
21706
21707    public void waitForAppDataPrepared() {
21708        if (mPrepareAppDataFuture == null) {
21709            return;
21710        }
21711        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21712        mPrepareAppDataFuture = null;
21713    }
21714
21715    @Override
21716    public boolean isSafeMode() {
21717        // allow instant applications
21718        return mSafeMode;
21719    }
21720
21721    @Override
21722    public boolean hasSystemUidErrors() {
21723        // allow instant applications
21724        return mHasSystemUidErrors;
21725    }
21726
21727    static String arrayToString(int[] array) {
21728        StringBuffer buf = new StringBuffer(128);
21729        buf.append('[');
21730        if (array != null) {
21731            for (int i=0; i<array.length; i++) {
21732                if (i > 0) buf.append(", ");
21733                buf.append(array[i]);
21734            }
21735        }
21736        buf.append(']');
21737        return buf.toString();
21738    }
21739
21740    static class DumpState {
21741        public static final int DUMP_LIBS = 1 << 0;
21742        public static final int DUMP_FEATURES = 1 << 1;
21743        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21744        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21745        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21746        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21747        public static final int DUMP_PERMISSIONS = 1 << 6;
21748        public static final int DUMP_PACKAGES = 1 << 7;
21749        public static final int DUMP_SHARED_USERS = 1 << 8;
21750        public static final int DUMP_MESSAGES = 1 << 9;
21751        public static final int DUMP_PROVIDERS = 1 << 10;
21752        public static final int DUMP_VERIFIERS = 1 << 11;
21753        public static final int DUMP_PREFERRED = 1 << 12;
21754        public static final int DUMP_PREFERRED_XML = 1 << 13;
21755        public static final int DUMP_KEYSETS = 1 << 14;
21756        public static final int DUMP_VERSION = 1 << 15;
21757        public static final int DUMP_INSTALLS = 1 << 16;
21758        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21759        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21760        public static final int DUMP_FROZEN = 1 << 19;
21761        public static final int DUMP_DEXOPT = 1 << 20;
21762        public static final int DUMP_COMPILER_STATS = 1 << 21;
21763        public static final int DUMP_CHANGES = 1 << 22;
21764
21765        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21766
21767        private int mTypes;
21768
21769        private int mOptions;
21770
21771        private boolean mTitlePrinted;
21772
21773        private SharedUserSetting mSharedUser;
21774
21775        public boolean isDumping(int type) {
21776            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21777                return true;
21778            }
21779
21780            return (mTypes & type) != 0;
21781        }
21782
21783        public void setDump(int type) {
21784            mTypes |= type;
21785        }
21786
21787        public boolean isOptionEnabled(int option) {
21788            return (mOptions & option) != 0;
21789        }
21790
21791        public void setOptionEnabled(int option) {
21792            mOptions |= option;
21793        }
21794
21795        public boolean onTitlePrinted() {
21796            final boolean printed = mTitlePrinted;
21797            mTitlePrinted = true;
21798            return printed;
21799        }
21800
21801        public boolean getTitlePrinted() {
21802            return mTitlePrinted;
21803        }
21804
21805        public void setTitlePrinted(boolean enabled) {
21806            mTitlePrinted = enabled;
21807        }
21808
21809        public SharedUserSetting getSharedUser() {
21810            return mSharedUser;
21811        }
21812
21813        public void setSharedUser(SharedUserSetting user) {
21814            mSharedUser = user;
21815        }
21816    }
21817
21818    @Override
21819    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21820            FileDescriptor err, String[] args, ShellCallback callback,
21821            ResultReceiver resultReceiver) {
21822        (new PackageManagerShellCommand(this)).exec(
21823                this, in, out, err, args, callback, resultReceiver);
21824    }
21825
21826    @Override
21827    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21828        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21829
21830        DumpState dumpState = new DumpState();
21831        boolean fullPreferred = false;
21832        boolean checkin = false;
21833
21834        String packageName = null;
21835        ArraySet<String> permissionNames = null;
21836
21837        int opti = 0;
21838        while (opti < args.length) {
21839            String opt = args[opti];
21840            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21841                break;
21842            }
21843            opti++;
21844
21845            if ("-a".equals(opt)) {
21846                // Right now we only know how to print all.
21847            } else if ("-h".equals(opt)) {
21848                pw.println("Package manager dump options:");
21849                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21850                pw.println("    --checkin: dump for a checkin");
21851                pw.println("    -f: print details of intent filters");
21852                pw.println("    -h: print this help");
21853                pw.println("  cmd may be one of:");
21854                pw.println("    l[ibraries]: list known shared libraries");
21855                pw.println("    f[eatures]: list device features");
21856                pw.println("    k[eysets]: print known keysets");
21857                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21858                pw.println("    perm[issions]: dump permissions");
21859                pw.println("    permission [name ...]: dump declaration and use of given permission");
21860                pw.println("    pref[erred]: print preferred package settings");
21861                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21862                pw.println("    prov[iders]: dump content providers");
21863                pw.println("    p[ackages]: dump installed packages");
21864                pw.println("    s[hared-users]: dump shared user IDs");
21865                pw.println("    m[essages]: print collected runtime messages");
21866                pw.println("    v[erifiers]: print package verifier info");
21867                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21868                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21869                pw.println("    version: print database version info");
21870                pw.println("    write: write current settings now");
21871                pw.println("    installs: details about install sessions");
21872                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21873                pw.println("    dexopt: dump dexopt state");
21874                pw.println("    compiler-stats: dump compiler statistics");
21875                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21876                pw.println("    <package.name>: info about given package");
21877                return;
21878            } else if ("--checkin".equals(opt)) {
21879                checkin = true;
21880            } else if ("-f".equals(opt)) {
21881                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21882            } else if ("--proto".equals(opt)) {
21883                dumpProto(fd);
21884                return;
21885            } else {
21886                pw.println("Unknown argument: " + opt + "; use -h for help");
21887            }
21888        }
21889
21890        // Is the caller requesting to dump a particular piece of data?
21891        if (opti < args.length) {
21892            String cmd = args[opti];
21893            opti++;
21894            // Is this a package name?
21895            if ("android".equals(cmd) || cmd.contains(".")) {
21896                packageName = cmd;
21897                // When dumping a single package, we always dump all of its
21898                // filter information since the amount of data will be reasonable.
21899                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21900            } else if ("check-permission".equals(cmd)) {
21901                if (opti >= args.length) {
21902                    pw.println("Error: check-permission missing permission argument");
21903                    return;
21904                }
21905                String perm = args[opti];
21906                opti++;
21907                if (opti >= args.length) {
21908                    pw.println("Error: check-permission missing package argument");
21909                    return;
21910                }
21911
21912                String pkg = args[opti];
21913                opti++;
21914                int user = UserHandle.getUserId(Binder.getCallingUid());
21915                if (opti < args.length) {
21916                    try {
21917                        user = Integer.parseInt(args[opti]);
21918                    } catch (NumberFormatException e) {
21919                        pw.println("Error: check-permission user argument is not a number: "
21920                                + args[opti]);
21921                        return;
21922                    }
21923                }
21924
21925                // Normalize package name to handle renamed packages and static libs
21926                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21927
21928                pw.println(checkPermission(perm, pkg, user));
21929                return;
21930            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21931                dumpState.setDump(DumpState.DUMP_LIBS);
21932            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21933                dumpState.setDump(DumpState.DUMP_FEATURES);
21934            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21935                if (opti >= args.length) {
21936                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21937                            | DumpState.DUMP_SERVICE_RESOLVERS
21938                            | DumpState.DUMP_RECEIVER_RESOLVERS
21939                            | DumpState.DUMP_CONTENT_RESOLVERS);
21940                } else {
21941                    while (opti < args.length) {
21942                        String name = args[opti];
21943                        if ("a".equals(name) || "activity".equals(name)) {
21944                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21945                        } else if ("s".equals(name) || "service".equals(name)) {
21946                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21947                        } else if ("r".equals(name) || "receiver".equals(name)) {
21948                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21949                        } else if ("c".equals(name) || "content".equals(name)) {
21950                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21951                        } else {
21952                            pw.println("Error: unknown resolver table type: " + name);
21953                            return;
21954                        }
21955                        opti++;
21956                    }
21957                }
21958            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21959                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21960            } else if ("permission".equals(cmd)) {
21961                if (opti >= args.length) {
21962                    pw.println("Error: permission requires permission name");
21963                    return;
21964                }
21965                permissionNames = new ArraySet<>();
21966                while (opti < args.length) {
21967                    permissionNames.add(args[opti]);
21968                    opti++;
21969                }
21970                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21971                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21972            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21973                dumpState.setDump(DumpState.DUMP_PREFERRED);
21974            } else if ("preferred-xml".equals(cmd)) {
21975                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21976                if (opti < args.length && "--full".equals(args[opti])) {
21977                    fullPreferred = true;
21978                    opti++;
21979                }
21980            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21981                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21982            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21983                dumpState.setDump(DumpState.DUMP_PACKAGES);
21984            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21985                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21986            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21987                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21988            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21989                dumpState.setDump(DumpState.DUMP_MESSAGES);
21990            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21991                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21992            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21993                    || "intent-filter-verifiers".equals(cmd)) {
21994                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21995            } else if ("version".equals(cmd)) {
21996                dumpState.setDump(DumpState.DUMP_VERSION);
21997            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21998                dumpState.setDump(DumpState.DUMP_KEYSETS);
21999            } else if ("installs".equals(cmd)) {
22000                dumpState.setDump(DumpState.DUMP_INSTALLS);
22001            } else if ("frozen".equals(cmd)) {
22002                dumpState.setDump(DumpState.DUMP_FROZEN);
22003            } else if ("dexopt".equals(cmd)) {
22004                dumpState.setDump(DumpState.DUMP_DEXOPT);
22005            } else if ("compiler-stats".equals(cmd)) {
22006                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22007            } else if ("changes".equals(cmd)) {
22008                dumpState.setDump(DumpState.DUMP_CHANGES);
22009            } else if ("write".equals(cmd)) {
22010                synchronized (mPackages) {
22011                    mSettings.writeLPr();
22012                    pw.println("Settings written.");
22013                    return;
22014                }
22015            }
22016        }
22017
22018        if (checkin) {
22019            pw.println("vers,1");
22020        }
22021
22022        // reader
22023        synchronized (mPackages) {
22024            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22025                if (!checkin) {
22026                    if (dumpState.onTitlePrinted())
22027                        pw.println();
22028                    pw.println("Database versions:");
22029                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22030                }
22031            }
22032
22033            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22034                if (!checkin) {
22035                    if (dumpState.onTitlePrinted())
22036                        pw.println();
22037                    pw.println("Verifiers:");
22038                    pw.print("  Required: ");
22039                    pw.print(mRequiredVerifierPackage);
22040                    pw.print(" (uid=");
22041                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22042                            UserHandle.USER_SYSTEM));
22043                    pw.println(")");
22044                } else if (mRequiredVerifierPackage != null) {
22045                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22046                    pw.print(",");
22047                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22048                            UserHandle.USER_SYSTEM));
22049                }
22050            }
22051
22052            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22053                    packageName == null) {
22054                if (mIntentFilterVerifierComponent != null) {
22055                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22056                    if (!checkin) {
22057                        if (dumpState.onTitlePrinted())
22058                            pw.println();
22059                        pw.println("Intent Filter Verifier:");
22060                        pw.print("  Using: ");
22061                        pw.print(verifierPackageName);
22062                        pw.print(" (uid=");
22063                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22064                                UserHandle.USER_SYSTEM));
22065                        pw.println(")");
22066                    } else if (verifierPackageName != null) {
22067                        pw.print("ifv,"); pw.print(verifierPackageName);
22068                        pw.print(",");
22069                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22070                                UserHandle.USER_SYSTEM));
22071                    }
22072                } else {
22073                    pw.println();
22074                    pw.println("No Intent Filter Verifier available!");
22075                }
22076            }
22077
22078            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22079                boolean printedHeader = false;
22080                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22081                while (it.hasNext()) {
22082                    String libName = it.next();
22083                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22084                    if (versionedLib == null) {
22085                        continue;
22086                    }
22087                    final int versionCount = versionedLib.size();
22088                    for (int i = 0; i < versionCount; i++) {
22089                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22090                        if (!checkin) {
22091                            if (!printedHeader) {
22092                                if (dumpState.onTitlePrinted())
22093                                    pw.println();
22094                                pw.println("Libraries:");
22095                                printedHeader = true;
22096                            }
22097                            pw.print("  ");
22098                        } else {
22099                            pw.print("lib,");
22100                        }
22101                        pw.print(libEntry.info.getName());
22102                        if (libEntry.info.isStatic()) {
22103                            pw.print(" version=" + libEntry.info.getVersion());
22104                        }
22105                        if (!checkin) {
22106                            pw.print(" -> ");
22107                        }
22108                        if (libEntry.path != null) {
22109                            pw.print(" (jar) ");
22110                            pw.print(libEntry.path);
22111                        } else {
22112                            pw.print(" (apk) ");
22113                            pw.print(libEntry.apk);
22114                        }
22115                        pw.println();
22116                    }
22117                }
22118            }
22119
22120            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22121                if (dumpState.onTitlePrinted())
22122                    pw.println();
22123                if (!checkin) {
22124                    pw.println("Features:");
22125                }
22126
22127                synchronized (mAvailableFeatures) {
22128                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22129                        if (checkin) {
22130                            pw.print("feat,");
22131                            pw.print(feat.name);
22132                            pw.print(",");
22133                            pw.println(feat.version);
22134                        } else {
22135                            pw.print("  ");
22136                            pw.print(feat.name);
22137                            if (feat.version > 0) {
22138                                pw.print(" version=");
22139                                pw.print(feat.version);
22140                            }
22141                            pw.println();
22142                        }
22143                    }
22144                }
22145            }
22146
22147            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22148                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22149                        : "Activity Resolver Table:", "  ", packageName,
22150                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22151                    dumpState.setTitlePrinted(true);
22152                }
22153            }
22154            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22155                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22156                        : "Receiver Resolver Table:", "  ", packageName,
22157                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22158                    dumpState.setTitlePrinted(true);
22159                }
22160            }
22161            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22162                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22163                        : "Service Resolver Table:", "  ", packageName,
22164                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22165                    dumpState.setTitlePrinted(true);
22166                }
22167            }
22168            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22169                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22170                        : "Provider Resolver Table:", "  ", packageName,
22171                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22172                    dumpState.setTitlePrinted(true);
22173                }
22174            }
22175
22176            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22177                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22178                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22179                    int user = mSettings.mPreferredActivities.keyAt(i);
22180                    if (pir.dump(pw,
22181                            dumpState.getTitlePrinted()
22182                                ? "\nPreferred Activities User " + user + ":"
22183                                : "Preferred Activities User " + user + ":", "  ",
22184                            packageName, true, false)) {
22185                        dumpState.setTitlePrinted(true);
22186                    }
22187                }
22188            }
22189
22190            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22191                pw.flush();
22192                FileOutputStream fout = new FileOutputStream(fd);
22193                BufferedOutputStream str = new BufferedOutputStream(fout);
22194                XmlSerializer serializer = new FastXmlSerializer();
22195                try {
22196                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22197                    serializer.startDocument(null, true);
22198                    serializer.setFeature(
22199                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22200                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22201                    serializer.endDocument();
22202                    serializer.flush();
22203                } catch (IllegalArgumentException e) {
22204                    pw.println("Failed writing: " + e);
22205                } catch (IllegalStateException e) {
22206                    pw.println("Failed writing: " + e);
22207                } catch (IOException e) {
22208                    pw.println("Failed writing: " + e);
22209                }
22210            }
22211
22212            if (!checkin
22213                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22214                    && packageName == null) {
22215                pw.println();
22216                int count = mSettings.mPackages.size();
22217                if (count == 0) {
22218                    pw.println("No applications!");
22219                    pw.println();
22220                } else {
22221                    final String prefix = "  ";
22222                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22223                    if (allPackageSettings.size() == 0) {
22224                        pw.println("No domain preferred apps!");
22225                        pw.println();
22226                    } else {
22227                        pw.println("App verification status:");
22228                        pw.println();
22229                        count = 0;
22230                        for (PackageSetting ps : allPackageSettings) {
22231                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22232                            if (ivi == null || ivi.getPackageName() == null) continue;
22233                            pw.println(prefix + "Package: " + ivi.getPackageName());
22234                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22235                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22236                            pw.println();
22237                            count++;
22238                        }
22239                        if (count == 0) {
22240                            pw.println(prefix + "No app verification established.");
22241                            pw.println();
22242                        }
22243                        for (int userId : sUserManager.getUserIds()) {
22244                            pw.println("App linkages for user " + userId + ":");
22245                            pw.println();
22246                            count = 0;
22247                            for (PackageSetting ps : allPackageSettings) {
22248                                final long status = ps.getDomainVerificationStatusForUser(userId);
22249                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22250                                        && !DEBUG_DOMAIN_VERIFICATION) {
22251                                    continue;
22252                                }
22253                                pw.println(prefix + "Package: " + ps.name);
22254                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22255                                String statusStr = IntentFilterVerificationInfo.
22256                                        getStatusStringFromValue(status);
22257                                pw.println(prefix + "Status:  " + statusStr);
22258                                pw.println();
22259                                count++;
22260                            }
22261                            if (count == 0) {
22262                                pw.println(prefix + "No configured app linkages.");
22263                                pw.println();
22264                            }
22265                        }
22266                    }
22267                }
22268            }
22269
22270            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22271                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22272                if (packageName == null && permissionNames == null) {
22273                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22274                        if (iperm == 0) {
22275                            if (dumpState.onTitlePrinted())
22276                                pw.println();
22277                            pw.println("AppOp Permissions:");
22278                        }
22279                        pw.print("  AppOp Permission ");
22280                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22281                        pw.println(":");
22282                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22283                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22284                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22285                        }
22286                    }
22287                }
22288            }
22289
22290            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22291                boolean printedSomething = false;
22292                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22293                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22294                        continue;
22295                    }
22296                    if (!printedSomething) {
22297                        if (dumpState.onTitlePrinted())
22298                            pw.println();
22299                        pw.println("Registered ContentProviders:");
22300                        printedSomething = true;
22301                    }
22302                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22303                    pw.print("    "); pw.println(p.toString());
22304                }
22305                printedSomething = false;
22306                for (Map.Entry<String, PackageParser.Provider> entry :
22307                        mProvidersByAuthority.entrySet()) {
22308                    PackageParser.Provider p = entry.getValue();
22309                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22310                        continue;
22311                    }
22312                    if (!printedSomething) {
22313                        if (dumpState.onTitlePrinted())
22314                            pw.println();
22315                        pw.println("ContentProvider Authorities:");
22316                        printedSomething = true;
22317                    }
22318                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22319                    pw.print("    "); pw.println(p.toString());
22320                    if (p.info != null && p.info.applicationInfo != null) {
22321                        final String appInfo = p.info.applicationInfo.toString();
22322                        pw.print("      applicationInfo="); pw.println(appInfo);
22323                    }
22324                }
22325            }
22326
22327            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22328                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22329            }
22330
22331            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22332                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22333            }
22334
22335            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22336                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22337            }
22338
22339            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22340                if (dumpState.onTitlePrinted()) pw.println();
22341                pw.println("Package Changes:");
22342                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22343                final int K = mChangedPackages.size();
22344                for (int i = 0; i < K; i++) {
22345                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22346                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22347                    final int N = changes.size();
22348                    if (N == 0) {
22349                        pw.print("    "); pw.println("No packages changed");
22350                    } else {
22351                        for (int j = 0; j < N; j++) {
22352                            final String pkgName = changes.valueAt(j);
22353                            final int sequenceNumber = changes.keyAt(j);
22354                            pw.print("    ");
22355                            pw.print("seq=");
22356                            pw.print(sequenceNumber);
22357                            pw.print(", package=");
22358                            pw.println(pkgName);
22359                        }
22360                    }
22361                }
22362            }
22363
22364            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22365                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22366            }
22367
22368            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22369                // XXX should handle packageName != null by dumping only install data that
22370                // the given package is involved with.
22371                if (dumpState.onTitlePrinted()) pw.println();
22372
22373                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22374                ipw.println();
22375                ipw.println("Frozen packages:");
22376                ipw.increaseIndent();
22377                if (mFrozenPackages.size() == 0) {
22378                    ipw.println("(none)");
22379                } else {
22380                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22381                        ipw.println(mFrozenPackages.valueAt(i));
22382                    }
22383                }
22384                ipw.decreaseIndent();
22385            }
22386
22387            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22388                if (dumpState.onTitlePrinted()) pw.println();
22389                dumpDexoptStateLPr(pw, packageName);
22390            }
22391
22392            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22393                if (dumpState.onTitlePrinted()) pw.println();
22394                dumpCompilerStatsLPr(pw, packageName);
22395            }
22396
22397            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22398                if (dumpState.onTitlePrinted()) pw.println();
22399                mSettings.dumpReadMessagesLPr(pw, dumpState);
22400
22401                pw.println();
22402                pw.println("Package warning messages:");
22403                BufferedReader in = null;
22404                String line = null;
22405                try {
22406                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22407                    while ((line = in.readLine()) != null) {
22408                        if (line.contains("ignored: updated version")) continue;
22409                        pw.println(line);
22410                    }
22411                } catch (IOException ignored) {
22412                } finally {
22413                    IoUtils.closeQuietly(in);
22414                }
22415            }
22416
22417            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22418                BufferedReader in = null;
22419                String line = null;
22420                try {
22421                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22422                    while ((line = in.readLine()) != null) {
22423                        if (line.contains("ignored: updated version")) continue;
22424                        pw.print("msg,");
22425                        pw.println(line);
22426                    }
22427                } catch (IOException ignored) {
22428                } finally {
22429                    IoUtils.closeQuietly(in);
22430                }
22431            }
22432        }
22433
22434        // PackageInstaller should be called outside of mPackages lock
22435        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22436            // XXX should handle packageName != null by dumping only install data that
22437            // the given package is involved with.
22438            if (dumpState.onTitlePrinted()) pw.println();
22439            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22440        }
22441    }
22442
22443    private void dumpProto(FileDescriptor fd) {
22444        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22445
22446        synchronized (mPackages) {
22447            final long requiredVerifierPackageToken =
22448                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22449            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22450            proto.write(
22451                    PackageServiceDumpProto.PackageShortProto.UID,
22452                    getPackageUid(
22453                            mRequiredVerifierPackage,
22454                            MATCH_DEBUG_TRIAGED_MISSING,
22455                            UserHandle.USER_SYSTEM));
22456            proto.end(requiredVerifierPackageToken);
22457
22458            if (mIntentFilterVerifierComponent != null) {
22459                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22460                final long verifierPackageToken =
22461                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22462                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22463                proto.write(
22464                        PackageServiceDumpProto.PackageShortProto.UID,
22465                        getPackageUid(
22466                                verifierPackageName,
22467                                MATCH_DEBUG_TRIAGED_MISSING,
22468                                UserHandle.USER_SYSTEM));
22469                proto.end(verifierPackageToken);
22470            }
22471
22472            dumpSharedLibrariesProto(proto);
22473            dumpFeaturesProto(proto);
22474            mSettings.dumpPackagesProto(proto);
22475            mSettings.dumpSharedUsersProto(proto);
22476            dumpMessagesProto(proto);
22477        }
22478        proto.flush();
22479    }
22480
22481    private void dumpMessagesProto(ProtoOutputStream proto) {
22482        BufferedReader in = null;
22483        String line = null;
22484        try {
22485            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22486            while ((line = in.readLine()) != null) {
22487                if (line.contains("ignored: updated version")) continue;
22488                proto.write(PackageServiceDumpProto.MESSAGES, line);
22489            }
22490        } catch (IOException ignored) {
22491        } finally {
22492            IoUtils.closeQuietly(in);
22493        }
22494    }
22495
22496    private void dumpFeaturesProto(ProtoOutputStream proto) {
22497        synchronized (mAvailableFeatures) {
22498            final int count = mAvailableFeatures.size();
22499            for (int i = 0; i < count; i++) {
22500                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22501                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22502                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22503                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22504                proto.end(featureToken);
22505            }
22506        }
22507    }
22508
22509    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22510        final int count = mSharedLibraries.size();
22511        for (int i = 0; i < count; i++) {
22512            final String libName = mSharedLibraries.keyAt(i);
22513            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22514            if (versionedLib == null) {
22515                continue;
22516            }
22517            final int versionCount = versionedLib.size();
22518            for (int j = 0; j < versionCount; j++) {
22519                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22520                final long sharedLibraryToken =
22521                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22522                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22523                final boolean isJar = (libEntry.path != null);
22524                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22525                if (isJar) {
22526                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22527                } else {
22528                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22529                }
22530                proto.end(sharedLibraryToken);
22531            }
22532        }
22533    }
22534
22535    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22536        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22537        ipw.println();
22538        ipw.println("Dexopt state:");
22539        ipw.increaseIndent();
22540        Collection<PackageParser.Package> packages = null;
22541        if (packageName != null) {
22542            PackageParser.Package targetPackage = mPackages.get(packageName);
22543            if (targetPackage != null) {
22544                packages = Collections.singletonList(targetPackage);
22545            } else {
22546                ipw.println("Unable to find package: " + packageName);
22547                return;
22548            }
22549        } else {
22550            packages = mPackages.values();
22551        }
22552
22553        for (PackageParser.Package pkg : packages) {
22554            ipw.println("[" + pkg.packageName + "]");
22555            ipw.increaseIndent();
22556            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22557            ipw.decreaseIndent();
22558        }
22559    }
22560
22561    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22562        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22563        ipw.println();
22564        ipw.println("Compiler stats:");
22565        ipw.increaseIndent();
22566        Collection<PackageParser.Package> packages = null;
22567        if (packageName != null) {
22568            PackageParser.Package targetPackage = mPackages.get(packageName);
22569            if (targetPackage != null) {
22570                packages = Collections.singletonList(targetPackage);
22571            } else {
22572                ipw.println("Unable to find package: " + packageName);
22573                return;
22574            }
22575        } else {
22576            packages = mPackages.values();
22577        }
22578
22579        for (PackageParser.Package pkg : packages) {
22580            ipw.println("[" + pkg.packageName + "]");
22581            ipw.increaseIndent();
22582
22583            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22584            if (stats == null) {
22585                ipw.println("(No recorded stats)");
22586            } else {
22587                stats.dump(ipw);
22588            }
22589            ipw.decreaseIndent();
22590        }
22591    }
22592
22593    private String dumpDomainString(String packageName) {
22594        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22595                .getList();
22596        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22597
22598        ArraySet<String> result = new ArraySet<>();
22599        if (iviList.size() > 0) {
22600            for (IntentFilterVerificationInfo ivi : iviList) {
22601                for (String host : ivi.getDomains()) {
22602                    result.add(host);
22603                }
22604            }
22605        }
22606        if (filters != null && filters.size() > 0) {
22607            for (IntentFilter filter : filters) {
22608                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22609                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22610                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22611                    result.addAll(filter.getHostsList());
22612                }
22613            }
22614        }
22615
22616        StringBuilder sb = new StringBuilder(result.size() * 16);
22617        for (String domain : result) {
22618            if (sb.length() > 0) sb.append(" ");
22619            sb.append(domain);
22620        }
22621        return sb.toString();
22622    }
22623
22624    // ------- apps on sdcard specific code -------
22625    static final boolean DEBUG_SD_INSTALL = false;
22626
22627    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22628
22629    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22630
22631    private boolean mMediaMounted = false;
22632
22633    static String getEncryptKey() {
22634        try {
22635            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22636                    SD_ENCRYPTION_KEYSTORE_NAME);
22637            if (sdEncKey == null) {
22638                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22639                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22640                if (sdEncKey == null) {
22641                    Slog.e(TAG, "Failed to create encryption keys");
22642                    return null;
22643                }
22644            }
22645            return sdEncKey;
22646        } catch (NoSuchAlgorithmException nsae) {
22647            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22648            return null;
22649        } catch (IOException ioe) {
22650            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22651            return null;
22652        }
22653    }
22654
22655    /*
22656     * Update media status on PackageManager.
22657     */
22658    @Override
22659    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22660        enforceSystemOrRoot("Media status can only be updated by the system");
22661        // reader; this apparently protects mMediaMounted, but should probably
22662        // be a different lock in that case.
22663        synchronized (mPackages) {
22664            Log.i(TAG, "Updating external media status from "
22665                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22666                    + (mediaStatus ? "mounted" : "unmounted"));
22667            if (DEBUG_SD_INSTALL)
22668                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22669                        + ", mMediaMounted=" + mMediaMounted);
22670            if (mediaStatus == mMediaMounted) {
22671                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22672                        : 0, -1);
22673                mHandler.sendMessage(msg);
22674                return;
22675            }
22676            mMediaMounted = mediaStatus;
22677        }
22678        // Queue up an async operation since the package installation may take a
22679        // little while.
22680        mHandler.post(new Runnable() {
22681            public void run() {
22682                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22683            }
22684        });
22685    }
22686
22687    /**
22688     * Called by StorageManagerService when the initial ASECs to scan are available.
22689     * Should block until all the ASEC containers are finished being scanned.
22690     */
22691    public void scanAvailableAsecs() {
22692        updateExternalMediaStatusInner(true, false, false);
22693    }
22694
22695    /*
22696     * Collect information of applications on external media, map them against
22697     * existing containers and update information based on current mount status.
22698     * Please note that we always have to report status if reportStatus has been
22699     * set to true especially when unloading packages.
22700     */
22701    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22702            boolean externalStorage) {
22703        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22704        int[] uidArr = EmptyArray.INT;
22705
22706        final String[] list = PackageHelper.getSecureContainerList();
22707        if (ArrayUtils.isEmpty(list)) {
22708            Log.i(TAG, "No secure containers found");
22709        } else {
22710            // Process list of secure containers and categorize them
22711            // as active or stale based on their package internal state.
22712
22713            // reader
22714            synchronized (mPackages) {
22715                for (String cid : list) {
22716                    // Leave stages untouched for now; installer service owns them
22717                    if (PackageInstallerService.isStageName(cid)) continue;
22718
22719                    if (DEBUG_SD_INSTALL)
22720                        Log.i(TAG, "Processing container " + cid);
22721                    String pkgName = getAsecPackageName(cid);
22722                    if (pkgName == null) {
22723                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22724                        continue;
22725                    }
22726                    if (DEBUG_SD_INSTALL)
22727                        Log.i(TAG, "Looking for pkg : " + pkgName);
22728
22729                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22730                    if (ps == null) {
22731                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22732                        continue;
22733                    }
22734
22735                    /*
22736                     * Skip packages that are not external if we're unmounting
22737                     * external storage.
22738                     */
22739                    if (externalStorage && !isMounted && !isExternal(ps)) {
22740                        continue;
22741                    }
22742
22743                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22744                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22745                    // The package status is changed only if the code path
22746                    // matches between settings and the container id.
22747                    if (ps.codePathString != null
22748                            && ps.codePathString.startsWith(args.getCodePath())) {
22749                        if (DEBUG_SD_INSTALL) {
22750                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22751                                    + " at code path: " + ps.codePathString);
22752                        }
22753
22754                        // We do have a valid package installed on sdcard
22755                        processCids.put(args, ps.codePathString);
22756                        final int uid = ps.appId;
22757                        if (uid != -1) {
22758                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22759                        }
22760                    } else {
22761                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22762                                + ps.codePathString);
22763                    }
22764                }
22765            }
22766
22767            Arrays.sort(uidArr);
22768        }
22769
22770        // Process packages with valid entries.
22771        if (isMounted) {
22772            if (DEBUG_SD_INSTALL)
22773                Log.i(TAG, "Loading packages");
22774            loadMediaPackages(processCids, uidArr, externalStorage);
22775            startCleaningPackages();
22776            mInstallerService.onSecureContainersAvailable();
22777        } else {
22778            if (DEBUG_SD_INSTALL)
22779                Log.i(TAG, "Unloading packages");
22780            unloadMediaPackages(processCids, uidArr, reportStatus);
22781        }
22782    }
22783
22784    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22785            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22786        final int size = infos.size();
22787        final String[] packageNames = new String[size];
22788        final int[] packageUids = new int[size];
22789        for (int i = 0; i < size; i++) {
22790            final ApplicationInfo info = infos.get(i);
22791            packageNames[i] = info.packageName;
22792            packageUids[i] = info.uid;
22793        }
22794        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22795                finishedReceiver);
22796    }
22797
22798    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22799            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22800        sendResourcesChangedBroadcast(mediaStatus, replacing,
22801                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22802    }
22803
22804    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22805            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22806        int size = pkgList.length;
22807        if (size > 0) {
22808            // Send broadcasts here
22809            Bundle extras = new Bundle();
22810            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22811            if (uidArr != null) {
22812                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22813            }
22814            if (replacing) {
22815                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22816            }
22817            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22818                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22819            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22820        }
22821    }
22822
22823   /*
22824     * Look at potentially valid container ids from processCids If package
22825     * information doesn't match the one on record or package scanning fails,
22826     * the cid is added to list of removeCids. We currently don't delete stale
22827     * containers.
22828     */
22829    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22830            boolean externalStorage) {
22831        ArrayList<String> pkgList = new ArrayList<String>();
22832        Set<AsecInstallArgs> keys = processCids.keySet();
22833
22834        for (AsecInstallArgs args : keys) {
22835            String codePath = processCids.get(args);
22836            if (DEBUG_SD_INSTALL)
22837                Log.i(TAG, "Loading container : " + args.cid);
22838            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22839            try {
22840                // Make sure there are no container errors first.
22841                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22842                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22843                            + " when installing from sdcard");
22844                    continue;
22845                }
22846                // Check code path here.
22847                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22848                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22849                            + " does not match one in settings " + codePath);
22850                    continue;
22851                }
22852                // Parse package
22853                int parseFlags = mDefParseFlags;
22854                if (args.isExternalAsec()) {
22855                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22856                }
22857                if (args.isFwdLocked()) {
22858                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22859                }
22860
22861                synchronized (mInstallLock) {
22862                    PackageParser.Package pkg = null;
22863                    try {
22864                        // Sadly we don't know the package name yet to freeze it
22865                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22866                                SCAN_IGNORE_FROZEN, 0, null);
22867                    } catch (PackageManagerException e) {
22868                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22869                    }
22870                    // Scan the package
22871                    if (pkg != null) {
22872                        /*
22873                         * TODO why is the lock being held? doPostInstall is
22874                         * called in other places without the lock. This needs
22875                         * to be straightened out.
22876                         */
22877                        // writer
22878                        synchronized (mPackages) {
22879                            retCode = PackageManager.INSTALL_SUCCEEDED;
22880                            pkgList.add(pkg.packageName);
22881                            // Post process args
22882                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22883                                    pkg.applicationInfo.uid);
22884                        }
22885                    } else {
22886                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22887                    }
22888                }
22889
22890            } finally {
22891                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22892                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22893                }
22894            }
22895        }
22896        // writer
22897        synchronized (mPackages) {
22898            // If the platform SDK has changed since the last time we booted,
22899            // we need to re-grant app permission to catch any new ones that
22900            // appear. This is really a hack, and means that apps can in some
22901            // cases get permissions that the user didn't initially explicitly
22902            // allow... it would be nice to have some better way to handle
22903            // this situation.
22904            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22905                    : mSettings.getInternalVersion();
22906            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22907                    : StorageManager.UUID_PRIVATE_INTERNAL;
22908
22909            int updateFlags = UPDATE_PERMISSIONS_ALL;
22910            if (ver.sdkVersion != mSdkVersion) {
22911                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22912                        + mSdkVersion + "; regranting permissions for external");
22913                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22914            }
22915            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22916
22917            // Yay, everything is now upgraded
22918            ver.forceCurrent();
22919
22920            // can downgrade to reader
22921            // Persist settings
22922            mSettings.writeLPr();
22923        }
22924        // Send a broadcast to let everyone know we are done processing
22925        if (pkgList.size() > 0) {
22926            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22927        }
22928    }
22929
22930   /*
22931     * Utility method to unload a list of specified containers
22932     */
22933    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22934        // Just unmount all valid containers.
22935        for (AsecInstallArgs arg : cidArgs) {
22936            synchronized (mInstallLock) {
22937                arg.doPostDeleteLI(false);
22938           }
22939       }
22940   }
22941
22942    /*
22943     * Unload packages mounted on external media. This involves deleting package
22944     * data from internal structures, sending broadcasts about disabled packages,
22945     * gc'ing to free up references, unmounting all secure containers
22946     * corresponding to packages on external media, and posting a
22947     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22948     * that we always have to post this message if status has been requested no
22949     * matter what.
22950     */
22951    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22952            final boolean reportStatus) {
22953        if (DEBUG_SD_INSTALL)
22954            Log.i(TAG, "unloading media packages");
22955        ArrayList<String> pkgList = new ArrayList<String>();
22956        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22957        final Set<AsecInstallArgs> keys = processCids.keySet();
22958        for (AsecInstallArgs args : keys) {
22959            String pkgName = args.getPackageName();
22960            if (DEBUG_SD_INSTALL)
22961                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22962            // Delete package internally
22963            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22964            synchronized (mInstallLock) {
22965                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22966                final boolean res;
22967                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22968                        "unloadMediaPackages")) {
22969                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22970                            null);
22971                }
22972                if (res) {
22973                    pkgList.add(pkgName);
22974                } else {
22975                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22976                    failedList.add(args);
22977                }
22978            }
22979        }
22980
22981        // reader
22982        synchronized (mPackages) {
22983            // We didn't update the settings after removing each package;
22984            // write them now for all packages.
22985            mSettings.writeLPr();
22986        }
22987
22988        // We have to absolutely send UPDATED_MEDIA_STATUS only
22989        // after confirming that all the receivers processed the ordered
22990        // broadcast when packages get disabled, force a gc to clean things up.
22991        // and unload all the containers.
22992        if (pkgList.size() > 0) {
22993            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22994                    new IIntentReceiver.Stub() {
22995                public void performReceive(Intent intent, int resultCode, String data,
22996                        Bundle extras, boolean ordered, boolean sticky,
22997                        int sendingUser) throws RemoteException {
22998                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22999                            reportStatus ? 1 : 0, 1, keys);
23000                    mHandler.sendMessage(msg);
23001                }
23002            });
23003        } else {
23004            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23005                    keys);
23006            mHandler.sendMessage(msg);
23007        }
23008    }
23009
23010    private void loadPrivatePackages(final VolumeInfo vol) {
23011        mHandler.post(new Runnable() {
23012            @Override
23013            public void run() {
23014                loadPrivatePackagesInner(vol);
23015            }
23016        });
23017    }
23018
23019    private void loadPrivatePackagesInner(VolumeInfo vol) {
23020        final String volumeUuid = vol.fsUuid;
23021        if (TextUtils.isEmpty(volumeUuid)) {
23022            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23023            return;
23024        }
23025
23026        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23027        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23028        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23029
23030        final VersionInfo ver;
23031        final List<PackageSetting> packages;
23032        synchronized (mPackages) {
23033            ver = mSettings.findOrCreateVersion(volumeUuid);
23034            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23035        }
23036
23037        for (PackageSetting ps : packages) {
23038            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23039            synchronized (mInstallLock) {
23040                final PackageParser.Package pkg;
23041                try {
23042                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23043                    loaded.add(pkg.applicationInfo);
23044
23045                } catch (PackageManagerException e) {
23046                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23047                }
23048
23049                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23050                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23051                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23052                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23053                }
23054            }
23055        }
23056
23057        // Reconcile app data for all started/unlocked users
23058        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23059        final UserManager um = mContext.getSystemService(UserManager.class);
23060        UserManagerInternal umInternal = getUserManagerInternal();
23061        for (UserInfo user : um.getUsers()) {
23062            final int flags;
23063            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23064                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23065            } else if (umInternal.isUserRunning(user.id)) {
23066                flags = StorageManager.FLAG_STORAGE_DE;
23067            } else {
23068                continue;
23069            }
23070
23071            try {
23072                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23073                synchronized (mInstallLock) {
23074                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23075                }
23076            } catch (IllegalStateException e) {
23077                // Device was probably ejected, and we'll process that event momentarily
23078                Slog.w(TAG, "Failed to prepare storage: " + e);
23079            }
23080        }
23081
23082        synchronized (mPackages) {
23083            int updateFlags = UPDATE_PERMISSIONS_ALL;
23084            if (ver.sdkVersion != mSdkVersion) {
23085                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23086                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23087                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23088            }
23089            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23090
23091            // Yay, everything is now upgraded
23092            ver.forceCurrent();
23093
23094            mSettings.writeLPr();
23095        }
23096
23097        for (PackageFreezer freezer : freezers) {
23098            freezer.close();
23099        }
23100
23101        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23102        sendResourcesChangedBroadcast(true, false, loaded, null);
23103    }
23104
23105    private void unloadPrivatePackages(final VolumeInfo vol) {
23106        mHandler.post(new Runnable() {
23107            @Override
23108            public void run() {
23109                unloadPrivatePackagesInner(vol);
23110            }
23111        });
23112    }
23113
23114    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23115        final String volumeUuid = vol.fsUuid;
23116        if (TextUtils.isEmpty(volumeUuid)) {
23117            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23118            return;
23119        }
23120
23121        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23122        synchronized (mInstallLock) {
23123        synchronized (mPackages) {
23124            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23125            for (PackageSetting ps : packages) {
23126                if (ps.pkg == null) continue;
23127
23128                final ApplicationInfo info = ps.pkg.applicationInfo;
23129                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23130                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23131
23132                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23133                        "unloadPrivatePackagesInner")) {
23134                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23135                            false, null)) {
23136                        unloaded.add(info);
23137                    } else {
23138                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23139                    }
23140                }
23141
23142                // Try very hard to release any references to this package
23143                // so we don't risk the system server being killed due to
23144                // open FDs
23145                AttributeCache.instance().removePackage(ps.name);
23146            }
23147
23148            mSettings.writeLPr();
23149        }
23150        }
23151
23152        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23153        sendResourcesChangedBroadcast(false, false, unloaded, null);
23154
23155        // Try very hard to release any references to this path so we don't risk
23156        // the system server being killed due to open FDs
23157        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23158
23159        for (int i = 0; i < 3; i++) {
23160            System.gc();
23161            System.runFinalization();
23162        }
23163    }
23164
23165    private void assertPackageKnown(String volumeUuid, String packageName)
23166            throws PackageManagerException {
23167        synchronized (mPackages) {
23168            // Normalize package name to handle renamed packages
23169            packageName = normalizePackageNameLPr(packageName);
23170
23171            final PackageSetting ps = mSettings.mPackages.get(packageName);
23172            if (ps == null) {
23173                throw new PackageManagerException("Package " + packageName + " is unknown");
23174            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23175                throw new PackageManagerException(
23176                        "Package " + packageName + " found on unknown volume " + volumeUuid
23177                                + "; expected volume " + ps.volumeUuid);
23178            }
23179        }
23180    }
23181
23182    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23183            throws PackageManagerException {
23184        synchronized (mPackages) {
23185            // Normalize package name to handle renamed packages
23186            packageName = normalizePackageNameLPr(packageName);
23187
23188            final PackageSetting ps = mSettings.mPackages.get(packageName);
23189            if (ps == null) {
23190                throw new PackageManagerException("Package " + packageName + " is unknown");
23191            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23192                throw new PackageManagerException(
23193                        "Package " + packageName + " found on unknown volume " + volumeUuid
23194                                + "; expected volume " + ps.volumeUuid);
23195            } else if (!ps.getInstalled(userId)) {
23196                throw new PackageManagerException(
23197                        "Package " + packageName + " not installed for user " + userId);
23198            }
23199        }
23200    }
23201
23202    private List<String> collectAbsoluteCodePaths() {
23203        synchronized (mPackages) {
23204            List<String> codePaths = new ArrayList<>();
23205            final int packageCount = mSettings.mPackages.size();
23206            for (int i = 0; i < packageCount; i++) {
23207                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23208                codePaths.add(ps.codePath.getAbsolutePath());
23209            }
23210            return codePaths;
23211        }
23212    }
23213
23214    /**
23215     * Examine all apps present on given mounted volume, and destroy apps that
23216     * aren't expected, either due to uninstallation or reinstallation on
23217     * another volume.
23218     */
23219    private void reconcileApps(String volumeUuid) {
23220        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23221        List<File> filesToDelete = null;
23222
23223        final File[] files = FileUtils.listFilesOrEmpty(
23224                Environment.getDataAppDirectory(volumeUuid));
23225        for (File file : files) {
23226            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23227                    && !PackageInstallerService.isStageName(file.getName());
23228            if (!isPackage) {
23229                // Ignore entries which are not packages
23230                continue;
23231            }
23232
23233            String absolutePath = file.getAbsolutePath();
23234
23235            boolean pathValid = false;
23236            final int absoluteCodePathCount = absoluteCodePaths.size();
23237            for (int i = 0; i < absoluteCodePathCount; i++) {
23238                String absoluteCodePath = absoluteCodePaths.get(i);
23239                if (absolutePath.startsWith(absoluteCodePath)) {
23240                    pathValid = true;
23241                    break;
23242                }
23243            }
23244
23245            if (!pathValid) {
23246                if (filesToDelete == null) {
23247                    filesToDelete = new ArrayList<>();
23248                }
23249                filesToDelete.add(file);
23250            }
23251        }
23252
23253        if (filesToDelete != null) {
23254            final int fileToDeleteCount = filesToDelete.size();
23255            for (int i = 0; i < fileToDeleteCount; i++) {
23256                File fileToDelete = filesToDelete.get(i);
23257                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23258                synchronized (mInstallLock) {
23259                    removeCodePathLI(fileToDelete);
23260                }
23261            }
23262        }
23263    }
23264
23265    /**
23266     * Reconcile all app data for the given user.
23267     * <p>
23268     * Verifies that directories exist and that ownership and labeling is
23269     * correct for all installed apps on all mounted volumes.
23270     */
23271    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23273        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23274            final String volumeUuid = vol.getFsUuid();
23275            synchronized (mInstallLock) {
23276                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23277            }
23278        }
23279    }
23280
23281    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23282            boolean migrateAppData) {
23283        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23284    }
23285
23286    /**
23287     * Reconcile all app data on given mounted volume.
23288     * <p>
23289     * Destroys app data that isn't expected, either due to uninstallation or
23290     * reinstallation on another volume.
23291     * <p>
23292     * Verifies that directories exist and that ownership and labeling is
23293     * correct for all installed apps.
23294     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23295     */
23296    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23297            boolean migrateAppData, boolean onlyCoreApps) {
23298        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23299                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23300        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23301
23302        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23303        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23304
23305        // First look for stale data that doesn't belong, and check if things
23306        // have changed since we did our last restorecon
23307        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23308            if (StorageManager.isFileEncryptedNativeOrEmulated()
23309                    && !StorageManager.isUserKeyUnlocked(userId)) {
23310                throw new RuntimeException(
23311                        "Yikes, someone asked us to reconcile CE storage while " + userId
23312                                + " was still locked; this would have caused massive data loss!");
23313            }
23314
23315            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23316            for (File file : files) {
23317                final String packageName = file.getName();
23318                try {
23319                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23320                } catch (PackageManagerException e) {
23321                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23322                    try {
23323                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23324                                StorageManager.FLAG_STORAGE_CE, 0);
23325                    } catch (InstallerException e2) {
23326                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23327                    }
23328                }
23329            }
23330        }
23331        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23332            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23333            for (File file : files) {
23334                final String packageName = file.getName();
23335                try {
23336                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23337                } catch (PackageManagerException e) {
23338                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23339                    try {
23340                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23341                                StorageManager.FLAG_STORAGE_DE, 0);
23342                    } catch (InstallerException e2) {
23343                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23344                    }
23345                }
23346            }
23347        }
23348
23349        // Ensure that data directories are ready to roll for all packages
23350        // installed for this volume and user
23351        final List<PackageSetting> packages;
23352        synchronized (mPackages) {
23353            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23354        }
23355        int preparedCount = 0;
23356        for (PackageSetting ps : packages) {
23357            final String packageName = ps.name;
23358            if (ps.pkg == null) {
23359                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23360                // TODO: might be due to legacy ASEC apps; we should circle back
23361                // and reconcile again once they're scanned
23362                continue;
23363            }
23364            // Skip non-core apps if requested
23365            if (onlyCoreApps && !ps.pkg.coreApp) {
23366                result.add(packageName);
23367                continue;
23368            }
23369
23370            if (ps.getInstalled(userId)) {
23371                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23372                preparedCount++;
23373            }
23374        }
23375
23376        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23377        return result;
23378    }
23379
23380    /**
23381     * Prepare app data for the given app just after it was installed or
23382     * upgraded. This method carefully only touches users that it's installed
23383     * for, and it forces a restorecon to handle any seinfo changes.
23384     * <p>
23385     * Verifies that directories exist and that ownership and labeling is
23386     * correct for all installed apps. If there is an ownership mismatch, it
23387     * will try recovering system apps by wiping data; third-party app data is
23388     * left intact.
23389     * <p>
23390     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23391     */
23392    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23393        final PackageSetting ps;
23394        synchronized (mPackages) {
23395            ps = mSettings.mPackages.get(pkg.packageName);
23396            mSettings.writeKernelMappingLPr(ps);
23397        }
23398
23399        final UserManager um = mContext.getSystemService(UserManager.class);
23400        UserManagerInternal umInternal = getUserManagerInternal();
23401        for (UserInfo user : um.getUsers()) {
23402            final int flags;
23403            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23404                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23405            } else if (umInternal.isUserRunning(user.id)) {
23406                flags = StorageManager.FLAG_STORAGE_DE;
23407            } else {
23408                continue;
23409            }
23410
23411            if (ps.getInstalled(user.id)) {
23412                // TODO: when user data is locked, mark that we're still dirty
23413                prepareAppDataLIF(pkg, user.id, flags);
23414            }
23415        }
23416    }
23417
23418    /**
23419     * Prepare app data for the given app.
23420     * <p>
23421     * Verifies that directories exist and that ownership and labeling is
23422     * correct for all installed apps. If there is an ownership mismatch, this
23423     * will try recovering system apps by wiping data; third-party app data is
23424     * left intact.
23425     */
23426    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23427        if (pkg == null) {
23428            Slog.wtf(TAG, "Package was null!", new Throwable());
23429            return;
23430        }
23431        prepareAppDataLeafLIF(pkg, userId, flags);
23432        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23433        for (int i = 0; i < childCount; i++) {
23434            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23435        }
23436    }
23437
23438    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23439            boolean maybeMigrateAppData) {
23440        prepareAppDataLIF(pkg, userId, flags);
23441
23442        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23443            // We may have just shuffled around app data directories, so
23444            // prepare them one more time
23445            prepareAppDataLIF(pkg, userId, flags);
23446        }
23447    }
23448
23449    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23450        if (DEBUG_APP_DATA) {
23451            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23452                    + Integer.toHexString(flags));
23453        }
23454
23455        final String volumeUuid = pkg.volumeUuid;
23456        final String packageName = pkg.packageName;
23457        final ApplicationInfo app = pkg.applicationInfo;
23458        final int appId = UserHandle.getAppId(app.uid);
23459
23460        Preconditions.checkNotNull(app.seInfo);
23461
23462        long ceDataInode = -1;
23463        try {
23464            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23465                    appId, app.seInfo, app.targetSdkVersion);
23466        } catch (InstallerException e) {
23467            if (app.isSystemApp()) {
23468                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23469                        + ", but trying to recover: " + e);
23470                destroyAppDataLeafLIF(pkg, userId, flags);
23471                try {
23472                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23473                            appId, app.seInfo, app.targetSdkVersion);
23474                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23475                } catch (InstallerException e2) {
23476                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23477                }
23478            } else {
23479                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23480            }
23481        }
23482
23483        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23484            // TODO: mark this structure as dirty so we persist it!
23485            synchronized (mPackages) {
23486                final PackageSetting ps = mSettings.mPackages.get(packageName);
23487                if (ps != null) {
23488                    ps.setCeDataInode(ceDataInode, userId);
23489                }
23490            }
23491        }
23492
23493        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23494    }
23495
23496    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23497        if (pkg == null) {
23498            Slog.wtf(TAG, "Package was null!", new Throwable());
23499            return;
23500        }
23501        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23502        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23503        for (int i = 0; i < childCount; i++) {
23504            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23505        }
23506    }
23507
23508    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23509        final String volumeUuid = pkg.volumeUuid;
23510        final String packageName = pkg.packageName;
23511        final ApplicationInfo app = pkg.applicationInfo;
23512
23513        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23514            // Create a native library symlink only if we have native libraries
23515            // and if the native libraries are 32 bit libraries. We do not provide
23516            // this symlink for 64 bit libraries.
23517            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23518                final String nativeLibPath = app.nativeLibraryDir;
23519                try {
23520                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23521                            nativeLibPath, userId);
23522                } catch (InstallerException e) {
23523                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23524                }
23525            }
23526        }
23527    }
23528
23529    /**
23530     * For system apps on non-FBE devices, this method migrates any existing
23531     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23532     * requested by the app.
23533     */
23534    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23535        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23536                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23537            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23538                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23539            try {
23540                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23541                        storageTarget);
23542            } catch (InstallerException e) {
23543                logCriticalInfo(Log.WARN,
23544                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23545            }
23546            return true;
23547        } else {
23548            return false;
23549        }
23550    }
23551
23552    public PackageFreezer freezePackage(String packageName, String killReason) {
23553        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23554    }
23555
23556    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23557        return new PackageFreezer(packageName, userId, killReason);
23558    }
23559
23560    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23561            String killReason) {
23562        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23563    }
23564
23565    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23566            String killReason) {
23567        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23568            return new PackageFreezer();
23569        } else {
23570            return freezePackage(packageName, userId, killReason);
23571        }
23572    }
23573
23574    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23575            String killReason) {
23576        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23577    }
23578
23579    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23580            String killReason) {
23581        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23582            return new PackageFreezer();
23583        } else {
23584            return freezePackage(packageName, userId, killReason);
23585        }
23586    }
23587
23588    /**
23589     * Class that freezes and kills the given package upon creation, and
23590     * unfreezes it upon closing. This is typically used when doing surgery on
23591     * app code/data to prevent the app from running while you're working.
23592     */
23593    private class PackageFreezer implements AutoCloseable {
23594        private final String mPackageName;
23595        private final PackageFreezer[] mChildren;
23596
23597        private final boolean mWeFroze;
23598
23599        private final AtomicBoolean mClosed = new AtomicBoolean();
23600        private final CloseGuard mCloseGuard = CloseGuard.get();
23601
23602        /**
23603         * Create and return a stub freezer that doesn't actually do anything,
23604         * typically used when someone requested
23605         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23606         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23607         */
23608        public PackageFreezer() {
23609            mPackageName = null;
23610            mChildren = null;
23611            mWeFroze = false;
23612            mCloseGuard.open("close");
23613        }
23614
23615        public PackageFreezer(String packageName, int userId, String killReason) {
23616            synchronized (mPackages) {
23617                mPackageName = packageName;
23618                mWeFroze = mFrozenPackages.add(mPackageName);
23619
23620                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23621                if (ps != null) {
23622                    killApplication(ps.name, ps.appId, userId, killReason);
23623                }
23624
23625                final PackageParser.Package p = mPackages.get(packageName);
23626                if (p != null && p.childPackages != null) {
23627                    final int N = p.childPackages.size();
23628                    mChildren = new PackageFreezer[N];
23629                    for (int i = 0; i < N; i++) {
23630                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23631                                userId, killReason);
23632                    }
23633                } else {
23634                    mChildren = null;
23635                }
23636            }
23637            mCloseGuard.open("close");
23638        }
23639
23640        @Override
23641        protected void finalize() throws Throwable {
23642            try {
23643                if (mCloseGuard != null) {
23644                    mCloseGuard.warnIfOpen();
23645                }
23646
23647                close();
23648            } finally {
23649                super.finalize();
23650            }
23651        }
23652
23653        @Override
23654        public void close() {
23655            mCloseGuard.close();
23656            if (mClosed.compareAndSet(false, true)) {
23657                synchronized (mPackages) {
23658                    if (mWeFroze) {
23659                        mFrozenPackages.remove(mPackageName);
23660                    }
23661
23662                    if (mChildren != null) {
23663                        for (PackageFreezer freezer : mChildren) {
23664                            freezer.close();
23665                        }
23666                    }
23667                }
23668            }
23669        }
23670    }
23671
23672    /**
23673     * Verify that given package is currently frozen.
23674     */
23675    private void checkPackageFrozen(String packageName) {
23676        synchronized (mPackages) {
23677            if (!mFrozenPackages.contains(packageName)) {
23678                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23679            }
23680        }
23681    }
23682
23683    @Override
23684    public int movePackage(final String packageName, final String volumeUuid) {
23685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23686
23687        final int callingUid = Binder.getCallingUid();
23688        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23689        final int moveId = mNextMoveId.getAndIncrement();
23690        mHandler.post(new Runnable() {
23691            @Override
23692            public void run() {
23693                try {
23694                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23695                } catch (PackageManagerException e) {
23696                    Slog.w(TAG, "Failed to move " + packageName, e);
23697                    mMoveCallbacks.notifyStatusChanged(moveId,
23698                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23699                }
23700            }
23701        });
23702        return moveId;
23703    }
23704
23705    private void movePackageInternal(final String packageName, final String volumeUuid,
23706            final int moveId, final int callingUid, UserHandle user)
23707                    throws PackageManagerException {
23708        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23709        final PackageManager pm = mContext.getPackageManager();
23710
23711        final boolean currentAsec;
23712        final String currentVolumeUuid;
23713        final File codeFile;
23714        final String installerPackageName;
23715        final String packageAbiOverride;
23716        final int appId;
23717        final String seinfo;
23718        final String label;
23719        final int targetSdkVersion;
23720        final PackageFreezer freezer;
23721        final int[] installedUserIds;
23722
23723        // reader
23724        synchronized (mPackages) {
23725            final PackageParser.Package pkg = mPackages.get(packageName);
23726            final PackageSetting ps = mSettings.mPackages.get(packageName);
23727            if (pkg == null
23728                    || ps == null
23729                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23730                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23731            }
23732            if (pkg.applicationInfo.isSystemApp()) {
23733                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23734                        "Cannot move system application");
23735            }
23736
23737            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23738            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23739                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23740            if (isInternalStorage && !allow3rdPartyOnInternal) {
23741                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23742                        "3rd party apps are not allowed on internal storage");
23743            }
23744
23745            if (pkg.applicationInfo.isExternalAsec()) {
23746                currentAsec = true;
23747                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23748            } else if (pkg.applicationInfo.isForwardLocked()) {
23749                currentAsec = true;
23750                currentVolumeUuid = "forward_locked";
23751            } else {
23752                currentAsec = false;
23753                currentVolumeUuid = ps.volumeUuid;
23754
23755                final File probe = new File(pkg.codePath);
23756                final File probeOat = new File(probe, "oat");
23757                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23758                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23759                            "Move only supported for modern cluster style installs");
23760                }
23761            }
23762
23763            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23764                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23765                        "Package already moved to " + volumeUuid);
23766            }
23767            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23768                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23769                        "Device admin cannot be moved");
23770            }
23771
23772            if (mFrozenPackages.contains(packageName)) {
23773                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23774                        "Failed to move already frozen package");
23775            }
23776
23777            codeFile = new File(pkg.codePath);
23778            installerPackageName = ps.installerPackageName;
23779            packageAbiOverride = ps.cpuAbiOverrideString;
23780            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23781            seinfo = pkg.applicationInfo.seInfo;
23782            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23783            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23784            freezer = freezePackage(packageName, "movePackageInternal");
23785            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23786        }
23787
23788        final Bundle extras = new Bundle();
23789        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23790        extras.putString(Intent.EXTRA_TITLE, label);
23791        mMoveCallbacks.notifyCreated(moveId, extras);
23792
23793        int installFlags;
23794        final boolean moveCompleteApp;
23795        final File measurePath;
23796
23797        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23798            installFlags = INSTALL_INTERNAL;
23799            moveCompleteApp = !currentAsec;
23800            measurePath = Environment.getDataAppDirectory(volumeUuid);
23801        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23802            installFlags = INSTALL_EXTERNAL;
23803            moveCompleteApp = false;
23804            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23805        } else {
23806            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23807            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23808                    || !volume.isMountedWritable()) {
23809                freezer.close();
23810                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23811                        "Move location not mounted private volume");
23812            }
23813
23814            Preconditions.checkState(!currentAsec);
23815
23816            installFlags = INSTALL_INTERNAL;
23817            moveCompleteApp = true;
23818            measurePath = Environment.getDataAppDirectory(volumeUuid);
23819        }
23820
23821        final PackageStats stats = new PackageStats(null, -1);
23822        synchronized (mInstaller) {
23823            for (int userId : installedUserIds) {
23824                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23825                    freezer.close();
23826                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23827                            "Failed to measure package size");
23828                }
23829            }
23830        }
23831
23832        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23833                + stats.dataSize);
23834
23835        final long startFreeBytes = measurePath.getUsableSpace();
23836        final long sizeBytes;
23837        if (moveCompleteApp) {
23838            sizeBytes = stats.codeSize + stats.dataSize;
23839        } else {
23840            sizeBytes = stats.codeSize;
23841        }
23842
23843        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23844            freezer.close();
23845            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23846                    "Not enough free space to move");
23847        }
23848
23849        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23850
23851        final CountDownLatch installedLatch = new CountDownLatch(1);
23852        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23853            @Override
23854            public void onUserActionRequired(Intent intent) throws RemoteException {
23855                throw new IllegalStateException();
23856            }
23857
23858            @Override
23859            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23860                    Bundle extras) throws RemoteException {
23861                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23862                        + PackageManager.installStatusToString(returnCode, msg));
23863
23864                installedLatch.countDown();
23865                freezer.close();
23866
23867                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23868                switch (status) {
23869                    case PackageInstaller.STATUS_SUCCESS:
23870                        mMoveCallbacks.notifyStatusChanged(moveId,
23871                                PackageManager.MOVE_SUCCEEDED);
23872                        break;
23873                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23874                        mMoveCallbacks.notifyStatusChanged(moveId,
23875                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23876                        break;
23877                    default:
23878                        mMoveCallbacks.notifyStatusChanged(moveId,
23879                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23880                        break;
23881                }
23882            }
23883        };
23884
23885        final MoveInfo move;
23886        if (moveCompleteApp) {
23887            // Kick off a thread to report progress estimates
23888            new Thread() {
23889                @Override
23890                public void run() {
23891                    while (true) {
23892                        try {
23893                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23894                                break;
23895                            }
23896                        } catch (InterruptedException ignored) {
23897                        }
23898
23899                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23900                        final int progress = 10 + (int) MathUtils.constrain(
23901                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23902                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23903                    }
23904                }
23905            }.start();
23906
23907            final String dataAppName = codeFile.getName();
23908            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23909                    dataAppName, appId, seinfo, targetSdkVersion);
23910        } else {
23911            move = null;
23912        }
23913
23914        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23915
23916        final Message msg = mHandler.obtainMessage(INIT_COPY);
23917        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23918        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23919                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23920                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23921                PackageManager.INSTALL_REASON_UNKNOWN);
23922        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23923        msg.obj = params;
23924
23925        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23926                System.identityHashCode(msg.obj));
23927        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23928                System.identityHashCode(msg.obj));
23929
23930        mHandler.sendMessage(msg);
23931    }
23932
23933    @Override
23934    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23935        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23936
23937        final int realMoveId = mNextMoveId.getAndIncrement();
23938        final Bundle extras = new Bundle();
23939        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23940        mMoveCallbacks.notifyCreated(realMoveId, extras);
23941
23942        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23943            @Override
23944            public void onCreated(int moveId, Bundle extras) {
23945                // Ignored
23946            }
23947
23948            @Override
23949            public void onStatusChanged(int moveId, int status, long estMillis) {
23950                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23951            }
23952        };
23953
23954        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23955        storage.setPrimaryStorageUuid(volumeUuid, callback);
23956        return realMoveId;
23957    }
23958
23959    @Override
23960    public int getMoveStatus(int moveId) {
23961        mContext.enforceCallingOrSelfPermission(
23962                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23963        return mMoveCallbacks.mLastStatus.get(moveId);
23964    }
23965
23966    @Override
23967    public void registerMoveCallback(IPackageMoveObserver callback) {
23968        mContext.enforceCallingOrSelfPermission(
23969                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23970        mMoveCallbacks.register(callback);
23971    }
23972
23973    @Override
23974    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23975        mContext.enforceCallingOrSelfPermission(
23976                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23977        mMoveCallbacks.unregister(callback);
23978    }
23979
23980    @Override
23981    public boolean setInstallLocation(int loc) {
23982        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23983                null);
23984        if (getInstallLocation() == loc) {
23985            return true;
23986        }
23987        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23988                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23989            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23990                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23991            return true;
23992        }
23993        return false;
23994   }
23995
23996    @Override
23997    public int getInstallLocation() {
23998        // allow instant app access
23999        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24000                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24001                PackageHelper.APP_INSTALL_AUTO);
24002    }
24003
24004    /** Called by UserManagerService */
24005    void cleanUpUser(UserManagerService userManager, int userHandle) {
24006        synchronized (mPackages) {
24007            mDirtyUsers.remove(userHandle);
24008            mUserNeedsBadging.delete(userHandle);
24009            mSettings.removeUserLPw(userHandle);
24010            mPendingBroadcasts.remove(userHandle);
24011            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24012            removeUnusedPackagesLPw(userManager, userHandle);
24013        }
24014    }
24015
24016    /**
24017     * We're removing userHandle and would like to remove any downloaded packages
24018     * that are no longer in use by any other user.
24019     * @param userHandle the user being removed
24020     */
24021    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24022        final boolean DEBUG_CLEAN_APKS = false;
24023        int [] users = userManager.getUserIds();
24024        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24025        while (psit.hasNext()) {
24026            PackageSetting ps = psit.next();
24027            if (ps.pkg == null) {
24028                continue;
24029            }
24030            final String packageName = ps.pkg.packageName;
24031            // Skip over if system app
24032            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24033                continue;
24034            }
24035            if (DEBUG_CLEAN_APKS) {
24036                Slog.i(TAG, "Checking package " + packageName);
24037            }
24038            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24039            if (keep) {
24040                if (DEBUG_CLEAN_APKS) {
24041                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24042                }
24043            } else {
24044                for (int i = 0; i < users.length; i++) {
24045                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24046                        keep = true;
24047                        if (DEBUG_CLEAN_APKS) {
24048                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24049                                    + users[i]);
24050                        }
24051                        break;
24052                    }
24053                }
24054            }
24055            if (!keep) {
24056                if (DEBUG_CLEAN_APKS) {
24057                    Slog.i(TAG, "  Removing package " + packageName);
24058                }
24059                mHandler.post(new Runnable() {
24060                    public void run() {
24061                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24062                                userHandle, 0);
24063                    } //end run
24064                });
24065            }
24066        }
24067    }
24068
24069    /** Called by UserManagerService */
24070    void createNewUser(int userId, String[] disallowedPackages) {
24071        synchronized (mInstallLock) {
24072            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24073        }
24074        synchronized (mPackages) {
24075            scheduleWritePackageRestrictionsLocked(userId);
24076            scheduleWritePackageListLocked(userId);
24077            applyFactoryDefaultBrowserLPw(userId);
24078            primeDomainVerificationsLPw(userId);
24079        }
24080    }
24081
24082    void onNewUserCreated(final int userId) {
24083        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24084        // If permission review for legacy apps is required, we represent
24085        // dagerous permissions for such apps as always granted runtime
24086        // permissions to keep per user flag state whether review is needed.
24087        // Hence, if a new user is added we have to propagate dangerous
24088        // permission grants for these legacy apps.
24089        if (mPermissionReviewRequired) {
24090            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24091                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24092        }
24093    }
24094
24095    @Override
24096    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24097        mContext.enforceCallingOrSelfPermission(
24098                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24099                "Only package verification agents can read the verifier device identity");
24100
24101        synchronized (mPackages) {
24102            return mSettings.getVerifierDeviceIdentityLPw();
24103        }
24104    }
24105
24106    @Override
24107    public void setPermissionEnforced(String permission, boolean enforced) {
24108        // TODO: Now that we no longer change GID for storage, this should to away.
24109        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24110                "setPermissionEnforced");
24111        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24112            synchronized (mPackages) {
24113                if (mSettings.mReadExternalStorageEnforced == null
24114                        || mSettings.mReadExternalStorageEnforced != enforced) {
24115                    mSettings.mReadExternalStorageEnforced = enforced;
24116                    mSettings.writeLPr();
24117                }
24118            }
24119            // kill any non-foreground processes so we restart them and
24120            // grant/revoke the GID.
24121            final IActivityManager am = ActivityManager.getService();
24122            if (am != null) {
24123                final long token = Binder.clearCallingIdentity();
24124                try {
24125                    am.killProcessesBelowForeground("setPermissionEnforcement");
24126                } catch (RemoteException e) {
24127                } finally {
24128                    Binder.restoreCallingIdentity(token);
24129                }
24130            }
24131        } else {
24132            throw new IllegalArgumentException("No selective enforcement for " + permission);
24133        }
24134    }
24135
24136    @Override
24137    @Deprecated
24138    public boolean isPermissionEnforced(String permission) {
24139        // allow instant applications
24140        return true;
24141    }
24142
24143    @Override
24144    public boolean isStorageLow() {
24145        // allow instant applications
24146        final long token = Binder.clearCallingIdentity();
24147        try {
24148            final DeviceStorageMonitorInternal
24149                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24150            if (dsm != null) {
24151                return dsm.isMemoryLow();
24152            } else {
24153                return false;
24154            }
24155        } finally {
24156            Binder.restoreCallingIdentity(token);
24157        }
24158    }
24159
24160    @Override
24161    public IPackageInstaller getPackageInstaller() {
24162        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24163            return null;
24164        }
24165        return mInstallerService;
24166    }
24167
24168    private boolean userNeedsBadging(int userId) {
24169        int index = mUserNeedsBadging.indexOfKey(userId);
24170        if (index < 0) {
24171            final UserInfo userInfo;
24172            final long token = Binder.clearCallingIdentity();
24173            try {
24174                userInfo = sUserManager.getUserInfo(userId);
24175            } finally {
24176                Binder.restoreCallingIdentity(token);
24177            }
24178            final boolean b;
24179            if (userInfo != null && userInfo.isManagedProfile()) {
24180                b = true;
24181            } else {
24182                b = false;
24183            }
24184            mUserNeedsBadging.put(userId, b);
24185            return b;
24186        }
24187        return mUserNeedsBadging.valueAt(index);
24188    }
24189
24190    @Override
24191    public KeySet getKeySetByAlias(String packageName, String alias) {
24192        if (packageName == null || alias == null) {
24193            return null;
24194        }
24195        synchronized(mPackages) {
24196            final PackageParser.Package pkg = mPackages.get(packageName);
24197            if (pkg == null) {
24198                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24199                throw new IllegalArgumentException("Unknown package: " + packageName);
24200            }
24201            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24202            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24203                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24204                throw new IllegalArgumentException("Unknown package: " + packageName);
24205            }
24206            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24207            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24208        }
24209    }
24210
24211    @Override
24212    public KeySet getSigningKeySet(String packageName) {
24213        if (packageName == null) {
24214            return null;
24215        }
24216        synchronized(mPackages) {
24217            final int callingUid = Binder.getCallingUid();
24218            final int callingUserId = UserHandle.getUserId(callingUid);
24219            final PackageParser.Package pkg = mPackages.get(packageName);
24220            if (pkg == null) {
24221                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24222                throw new IllegalArgumentException("Unknown package: " + packageName);
24223            }
24224            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24225            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24226                // filter and pretend the package doesn't exist
24227                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24228                        + ", uid:" + callingUid);
24229                throw new IllegalArgumentException("Unknown package: " + packageName);
24230            }
24231            if (pkg.applicationInfo.uid != callingUid
24232                    && Process.SYSTEM_UID != callingUid) {
24233                throw new SecurityException("May not access signing KeySet of other apps.");
24234            }
24235            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24236            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24237        }
24238    }
24239
24240    @Override
24241    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24242        final int callingUid = Binder.getCallingUid();
24243        if (getInstantAppPackageName(callingUid) != null) {
24244            return false;
24245        }
24246        if (packageName == null || ks == null) {
24247            return false;
24248        }
24249        synchronized(mPackages) {
24250            final PackageParser.Package pkg = mPackages.get(packageName);
24251            if (pkg == null
24252                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24253                            UserHandle.getUserId(callingUid))) {
24254                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24255                throw new IllegalArgumentException("Unknown package: " + packageName);
24256            }
24257            IBinder ksh = ks.getToken();
24258            if (ksh instanceof KeySetHandle) {
24259                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24260                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24261            }
24262            return false;
24263        }
24264    }
24265
24266    @Override
24267    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24268        final int callingUid = Binder.getCallingUid();
24269        if (getInstantAppPackageName(callingUid) != null) {
24270            return false;
24271        }
24272        if (packageName == null || ks == null) {
24273            return false;
24274        }
24275        synchronized(mPackages) {
24276            final PackageParser.Package pkg = mPackages.get(packageName);
24277            if (pkg == null
24278                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24279                            UserHandle.getUserId(callingUid))) {
24280                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24281                throw new IllegalArgumentException("Unknown package: " + packageName);
24282            }
24283            IBinder ksh = ks.getToken();
24284            if (ksh instanceof KeySetHandle) {
24285                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24286                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24287            }
24288            return false;
24289        }
24290    }
24291
24292    private void deletePackageIfUnusedLPr(final String packageName) {
24293        PackageSetting ps = mSettings.mPackages.get(packageName);
24294        if (ps == null) {
24295            return;
24296        }
24297        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24298            // TODO Implement atomic delete if package is unused
24299            // It is currently possible that the package will be deleted even if it is installed
24300            // after this method returns.
24301            mHandler.post(new Runnable() {
24302                public void run() {
24303                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24304                            0, PackageManager.DELETE_ALL_USERS);
24305                }
24306            });
24307        }
24308    }
24309
24310    /**
24311     * Check and throw if the given before/after packages would be considered a
24312     * downgrade.
24313     */
24314    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24315            throws PackageManagerException {
24316        if (after.versionCode < before.mVersionCode) {
24317            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24318                    "Update version code " + after.versionCode + " is older than current "
24319                    + before.mVersionCode);
24320        } else if (after.versionCode == before.mVersionCode) {
24321            if (after.baseRevisionCode < before.baseRevisionCode) {
24322                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24323                        "Update base revision code " + after.baseRevisionCode
24324                        + " is older than current " + before.baseRevisionCode);
24325            }
24326
24327            if (!ArrayUtils.isEmpty(after.splitNames)) {
24328                for (int i = 0; i < after.splitNames.length; i++) {
24329                    final String splitName = after.splitNames[i];
24330                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24331                    if (j != -1) {
24332                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24333                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24334                                    "Update split " + splitName + " revision code "
24335                                    + after.splitRevisionCodes[i] + " is older than current "
24336                                    + before.splitRevisionCodes[j]);
24337                        }
24338                    }
24339                }
24340            }
24341        }
24342    }
24343
24344    private static class MoveCallbacks extends Handler {
24345        private static final int MSG_CREATED = 1;
24346        private static final int MSG_STATUS_CHANGED = 2;
24347
24348        private final RemoteCallbackList<IPackageMoveObserver>
24349                mCallbacks = new RemoteCallbackList<>();
24350
24351        private final SparseIntArray mLastStatus = new SparseIntArray();
24352
24353        public MoveCallbacks(Looper looper) {
24354            super(looper);
24355        }
24356
24357        public void register(IPackageMoveObserver callback) {
24358            mCallbacks.register(callback);
24359        }
24360
24361        public void unregister(IPackageMoveObserver callback) {
24362            mCallbacks.unregister(callback);
24363        }
24364
24365        @Override
24366        public void handleMessage(Message msg) {
24367            final SomeArgs args = (SomeArgs) msg.obj;
24368            final int n = mCallbacks.beginBroadcast();
24369            for (int i = 0; i < n; i++) {
24370                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24371                try {
24372                    invokeCallback(callback, msg.what, args);
24373                } catch (RemoteException ignored) {
24374                }
24375            }
24376            mCallbacks.finishBroadcast();
24377            args.recycle();
24378        }
24379
24380        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24381                throws RemoteException {
24382            switch (what) {
24383                case MSG_CREATED: {
24384                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24385                    break;
24386                }
24387                case MSG_STATUS_CHANGED: {
24388                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24389                    break;
24390                }
24391            }
24392        }
24393
24394        private void notifyCreated(int moveId, Bundle extras) {
24395            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24396
24397            final SomeArgs args = SomeArgs.obtain();
24398            args.argi1 = moveId;
24399            args.arg2 = extras;
24400            obtainMessage(MSG_CREATED, args).sendToTarget();
24401        }
24402
24403        private void notifyStatusChanged(int moveId, int status) {
24404            notifyStatusChanged(moveId, status, -1);
24405        }
24406
24407        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24408            Slog.v(TAG, "Move " + moveId + " status " + status);
24409
24410            final SomeArgs args = SomeArgs.obtain();
24411            args.argi1 = moveId;
24412            args.argi2 = status;
24413            args.arg3 = estMillis;
24414            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24415
24416            synchronized (mLastStatus) {
24417                mLastStatus.put(moveId, status);
24418            }
24419        }
24420    }
24421
24422    private final static class OnPermissionChangeListeners extends Handler {
24423        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24424
24425        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24426                new RemoteCallbackList<>();
24427
24428        public OnPermissionChangeListeners(Looper looper) {
24429            super(looper);
24430        }
24431
24432        @Override
24433        public void handleMessage(Message msg) {
24434            switch (msg.what) {
24435                case MSG_ON_PERMISSIONS_CHANGED: {
24436                    final int uid = msg.arg1;
24437                    handleOnPermissionsChanged(uid);
24438                } break;
24439            }
24440        }
24441
24442        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24443            mPermissionListeners.register(listener);
24444
24445        }
24446
24447        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24448            mPermissionListeners.unregister(listener);
24449        }
24450
24451        public void onPermissionsChanged(int uid) {
24452            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24453                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24454            }
24455        }
24456
24457        private void handleOnPermissionsChanged(int uid) {
24458            final int count = mPermissionListeners.beginBroadcast();
24459            try {
24460                for (int i = 0; i < count; i++) {
24461                    IOnPermissionsChangeListener callback = mPermissionListeners
24462                            .getBroadcastItem(i);
24463                    try {
24464                        callback.onPermissionsChanged(uid);
24465                    } catch (RemoteException e) {
24466                        Log.e(TAG, "Permission listener is dead", e);
24467                    }
24468                }
24469            } finally {
24470                mPermissionListeners.finishBroadcast();
24471            }
24472        }
24473    }
24474
24475    private class PackageManagerInternalImpl extends PackageManagerInternal {
24476        @Override
24477        public void setLocationPackagesProvider(PackagesProvider provider) {
24478            synchronized (mPackages) {
24479                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24480            }
24481        }
24482
24483        @Override
24484        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24485            synchronized (mPackages) {
24486                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24487            }
24488        }
24489
24490        @Override
24491        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24492            synchronized (mPackages) {
24493                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24494            }
24495        }
24496
24497        @Override
24498        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24499            synchronized (mPackages) {
24500                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24501            }
24502        }
24503
24504        @Override
24505        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24506            synchronized (mPackages) {
24507                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24508            }
24509        }
24510
24511        @Override
24512        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24513            synchronized (mPackages) {
24514                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24515            }
24516        }
24517
24518        @Override
24519        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24520            synchronized (mPackages) {
24521                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24522                        packageName, userId);
24523            }
24524        }
24525
24526        @Override
24527        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24528            synchronized (mPackages) {
24529                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24530                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24531                        packageName, userId);
24532            }
24533        }
24534
24535        @Override
24536        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24537            synchronized (mPackages) {
24538                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24539                        packageName, userId);
24540            }
24541        }
24542
24543        @Override
24544        public void setKeepUninstalledPackages(final List<String> packageList) {
24545            Preconditions.checkNotNull(packageList);
24546            List<String> removedFromList = null;
24547            synchronized (mPackages) {
24548                if (mKeepUninstalledPackages != null) {
24549                    final int packagesCount = mKeepUninstalledPackages.size();
24550                    for (int i = 0; i < packagesCount; i++) {
24551                        String oldPackage = mKeepUninstalledPackages.get(i);
24552                        if (packageList != null && packageList.contains(oldPackage)) {
24553                            continue;
24554                        }
24555                        if (removedFromList == null) {
24556                            removedFromList = new ArrayList<>();
24557                        }
24558                        removedFromList.add(oldPackage);
24559                    }
24560                }
24561                mKeepUninstalledPackages = new ArrayList<>(packageList);
24562                if (removedFromList != null) {
24563                    final int removedCount = removedFromList.size();
24564                    for (int i = 0; i < removedCount; i++) {
24565                        deletePackageIfUnusedLPr(removedFromList.get(i));
24566                    }
24567                }
24568            }
24569        }
24570
24571        @Override
24572        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24573            synchronized (mPackages) {
24574                // If we do not support permission review, done.
24575                if (!mPermissionReviewRequired) {
24576                    return false;
24577                }
24578
24579                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24580                if (packageSetting == null) {
24581                    return false;
24582                }
24583
24584                // Permission review applies only to apps not supporting the new permission model.
24585                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24586                    return false;
24587                }
24588
24589                // Legacy apps have the permission and get user consent on launch.
24590                PermissionsState permissionsState = packageSetting.getPermissionsState();
24591                return permissionsState.isPermissionReviewRequired(userId);
24592            }
24593        }
24594
24595        @Override
24596        public PackageInfo getPackageInfo(
24597                String packageName, int flags, int filterCallingUid, int userId) {
24598            return PackageManagerService.this
24599                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24600                            flags, filterCallingUid, userId);
24601        }
24602
24603        @Override
24604        public ApplicationInfo getApplicationInfo(
24605                String packageName, int flags, int filterCallingUid, int userId) {
24606            return PackageManagerService.this
24607                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24608        }
24609
24610        @Override
24611        public ActivityInfo getActivityInfo(
24612                ComponentName component, int flags, int filterCallingUid, int userId) {
24613            return PackageManagerService.this
24614                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24615        }
24616
24617        @Override
24618        public List<ResolveInfo> queryIntentActivities(
24619                Intent intent, int flags, int filterCallingUid, int userId) {
24620            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24621            return PackageManagerService.this
24622                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24623                            userId, false /*resolveForStart*/);
24624        }
24625
24626        @Override
24627        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24628                int userId) {
24629            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24630        }
24631
24632        @Override
24633        public void setDeviceAndProfileOwnerPackages(
24634                int deviceOwnerUserId, String deviceOwnerPackage,
24635                SparseArray<String> profileOwnerPackages) {
24636            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24637                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24638        }
24639
24640        @Override
24641        public boolean isPackageDataProtected(int userId, String packageName) {
24642            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24643        }
24644
24645        @Override
24646        public boolean isPackageEphemeral(int userId, String packageName) {
24647            synchronized (mPackages) {
24648                final PackageSetting ps = mSettings.mPackages.get(packageName);
24649                return ps != null ? ps.getInstantApp(userId) : false;
24650            }
24651        }
24652
24653        @Override
24654        public boolean wasPackageEverLaunched(String packageName, int userId) {
24655            synchronized (mPackages) {
24656                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24657            }
24658        }
24659
24660        @Override
24661        public void grantRuntimePermission(String packageName, String name, int userId,
24662                boolean overridePolicy) {
24663            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24664                    overridePolicy);
24665        }
24666
24667        @Override
24668        public void revokeRuntimePermission(String packageName, String name, int userId,
24669                boolean overridePolicy) {
24670            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24671                    overridePolicy);
24672        }
24673
24674        @Override
24675        public String getNameForUid(int uid) {
24676            return PackageManagerService.this.getNameForUid(uid);
24677        }
24678
24679        @Override
24680        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24681                Intent origIntent, String resolvedType, String callingPackage,
24682                Bundle verificationBundle, int userId) {
24683            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24684                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24685                    userId);
24686        }
24687
24688        @Override
24689        public void grantEphemeralAccess(int userId, Intent intent,
24690                int targetAppId, int ephemeralAppId) {
24691            synchronized (mPackages) {
24692                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24693                        targetAppId, ephemeralAppId);
24694            }
24695        }
24696
24697        @Override
24698        public boolean isInstantAppInstallerComponent(ComponentName component) {
24699            synchronized (mPackages) {
24700                return mInstantAppInstallerActivity != null
24701                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24702            }
24703        }
24704
24705        @Override
24706        public void pruneInstantApps() {
24707            mInstantAppRegistry.pruneInstantApps();
24708        }
24709
24710        @Override
24711        public String getSetupWizardPackageName() {
24712            return mSetupWizardPackage;
24713        }
24714
24715        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24716            if (policy != null) {
24717                mExternalSourcesPolicy = policy;
24718            }
24719        }
24720
24721        @Override
24722        public boolean isPackagePersistent(String packageName) {
24723            synchronized (mPackages) {
24724                PackageParser.Package pkg = mPackages.get(packageName);
24725                return pkg != null
24726                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24727                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24728                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24729                        : false;
24730            }
24731        }
24732
24733        @Override
24734        public List<PackageInfo> getOverlayPackages(int userId) {
24735            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24736            synchronized (mPackages) {
24737                for (PackageParser.Package p : mPackages.values()) {
24738                    if (p.mOverlayTarget != null) {
24739                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24740                        if (pkg != null) {
24741                            overlayPackages.add(pkg);
24742                        }
24743                    }
24744                }
24745            }
24746            return overlayPackages;
24747        }
24748
24749        @Override
24750        public List<String> getTargetPackageNames(int userId) {
24751            List<String> targetPackages = new ArrayList<>();
24752            synchronized (mPackages) {
24753                for (PackageParser.Package p : mPackages.values()) {
24754                    if (p.mOverlayTarget == null) {
24755                        targetPackages.add(p.packageName);
24756                    }
24757                }
24758            }
24759            return targetPackages;
24760        }
24761
24762        @Override
24763        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24764                @Nullable List<String> overlayPackageNames) {
24765            synchronized (mPackages) {
24766                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24767                    Slog.e(TAG, "failed to find package " + targetPackageName);
24768                    return false;
24769                }
24770                ArrayList<String> overlayPaths = null;
24771                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24772                    final int N = overlayPackageNames.size();
24773                    overlayPaths = new ArrayList<>(N);
24774                    for (int i = 0; i < N; i++) {
24775                        final String packageName = overlayPackageNames.get(i);
24776                        final PackageParser.Package pkg = mPackages.get(packageName);
24777                        if (pkg == null) {
24778                            Slog.e(TAG, "failed to find package " + packageName);
24779                            return false;
24780                        }
24781                        overlayPaths.add(pkg.baseCodePath);
24782                    }
24783                }
24784
24785                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24786                ps.setOverlayPaths(overlayPaths, userId);
24787                return true;
24788            }
24789        }
24790
24791        @Override
24792        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24793                int flags, int userId) {
24794            return resolveIntentInternal(
24795                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24796        }
24797
24798        @Override
24799        public ResolveInfo resolveService(Intent intent, String resolvedType,
24800                int flags, int userId, int callingUid) {
24801            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24802        }
24803
24804        @Override
24805        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24806            synchronized (mPackages) {
24807                mIsolatedOwners.put(isolatedUid, ownerUid);
24808            }
24809        }
24810
24811        @Override
24812        public void removeIsolatedUid(int isolatedUid) {
24813            synchronized (mPackages) {
24814                mIsolatedOwners.delete(isolatedUid);
24815            }
24816        }
24817
24818        @Override
24819        public int getUidTargetSdkVersion(int uid) {
24820            synchronized (mPackages) {
24821                return getUidTargetSdkVersionLockedLPr(uid);
24822            }
24823        }
24824
24825        @Override
24826        public boolean canAccessInstantApps(int callingUid, int userId) {
24827            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24828        }
24829    }
24830
24831    @Override
24832    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24833        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24834        synchronized (mPackages) {
24835            final long identity = Binder.clearCallingIdentity();
24836            try {
24837                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24838                        packageNames, userId);
24839            } finally {
24840                Binder.restoreCallingIdentity(identity);
24841            }
24842        }
24843    }
24844
24845    @Override
24846    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24847        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24848        synchronized (mPackages) {
24849            final long identity = Binder.clearCallingIdentity();
24850            try {
24851                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24852                        packageNames, userId);
24853            } finally {
24854                Binder.restoreCallingIdentity(identity);
24855            }
24856        }
24857    }
24858
24859    private static void enforceSystemOrPhoneCaller(String tag) {
24860        int callingUid = Binder.getCallingUid();
24861        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24862            throw new SecurityException(
24863                    "Cannot call " + tag + " from UID " + callingUid);
24864        }
24865    }
24866
24867    boolean isHistoricalPackageUsageAvailable() {
24868        return mPackageUsage.isHistoricalPackageUsageAvailable();
24869    }
24870
24871    /**
24872     * Return a <b>copy</b> of the collection of packages known to the package manager.
24873     * @return A copy of the values of mPackages.
24874     */
24875    Collection<PackageParser.Package> getPackages() {
24876        synchronized (mPackages) {
24877            return new ArrayList<>(mPackages.values());
24878        }
24879    }
24880
24881    /**
24882     * Logs process start information (including base APK hash) to the security log.
24883     * @hide
24884     */
24885    @Override
24886    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24887            String apkFile, int pid) {
24888        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24889            return;
24890        }
24891        if (!SecurityLog.isLoggingEnabled()) {
24892            return;
24893        }
24894        Bundle data = new Bundle();
24895        data.putLong("startTimestamp", System.currentTimeMillis());
24896        data.putString("processName", processName);
24897        data.putInt("uid", uid);
24898        data.putString("seinfo", seinfo);
24899        data.putString("apkFile", apkFile);
24900        data.putInt("pid", pid);
24901        Message msg = mProcessLoggingHandler.obtainMessage(
24902                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24903        msg.setData(data);
24904        mProcessLoggingHandler.sendMessage(msg);
24905    }
24906
24907    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24908        return mCompilerStats.getPackageStats(pkgName);
24909    }
24910
24911    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24912        return getOrCreateCompilerPackageStats(pkg.packageName);
24913    }
24914
24915    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24916        return mCompilerStats.getOrCreatePackageStats(pkgName);
24917    }
24918
24919    public void deleteCompilerPackageStats(String pkgName) {
24920        mCompilerStats.deletePackageStats(pkgName);
24921    }
24922
24923    @Override
24924    public int getInstallReason(String packageName, int userId) {
24925        final int callingUid = Binder.getCallingUid();
24926        enforceCrossUserPermission(callingUid, userId,
24927                true /* requireFullPermission */, false /* checkShell */,
24928                "get install reason");
24929        synchronized (mPackages) {
24930            final PackageSetting ps = mSettings.mPackages.get(packageName);
24931            if (filterAppAccessLPr(ps, callingUid, userId)) {
24932                return PackageManager.INSTALL_REASON_UNKNOWN;
24933            }
24934            if (ps != null) {
24935                return ps.getInstallReason(userId);
24936            }
24937        }
24938        return PackageManager.INSTALL_REASON_UNKNOWN;
24939    }
24940
24941    @Override
24942    public boolean canRequestPackageInstalls(String packageName, int userId) {
24943        return canRequestPackageInstallsInternal(packageName, 0, userId,
24944                true /* throwIfPermNotDeclared*/);
24945    }
24946
24947    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24948            boolean throwIfPermNotDeclared) {
24949        int callingUid = Binder.getCallingUid();
24950        int uid = getPackageUid(packageName, 0, userId);
24951        if (callingUid != uid && callingUid != Process.ROOT_UID
24952                && callingUid != Process.SYSTEM_UID) {
24953            throw new SecurityException(
24954                    "Caller uid " + callingUid + " does not own package " + packageName);
24955        }
24956        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24957        if (info == null) {
24958            return false;
24959        }
24960        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24961            return false;
24962        }
24963        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24964        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24965        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24966            if (throwIfPermNotDeclared) {
24967                throw new SecurityException("Need to declare " + appOpPermission
24968                        + " to call this api");
24969            } else {
24970                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24971                return false;
24972            }
24973        }
24974        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24975            return false;
24976        }
24977        if (mExternalSourcesPolicy != null) {
24978            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24979            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24980                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24981            }
24982        }
24983        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24984    }
24985
24986    @Override
24987    public ComponentName getInstantAppResolverSettingsComponent() {
24988        return mInstantAppResolverSettingsComponent;
24989    }
24990
24991    @Override
24992    public ComponentName getInstantAppInstallerComponent() {
24993        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24994            return null;
24995        }
24996        return mInstantAppInstallerActivity == null
24997                ? null : mInstantAppInstallerActivity.getComponentName();
24998    }
24999
25000    @Override
25001    public String getInstantAppAndroidId(String packageName, int userId) {
25002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25003                "getInstantAppAndroidId");
25004        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25005                true /* requireFullPermission */, false /* checkShell */,
25006                "getInstantAppAndroidId");
25007        // Make sure the target is an Instant App.
25008        if (!isInstantApp(packageName, userId)) {
25009            return null;
25010        }
25011        synchronized (mPackages) {
25012            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25013        }
25014    }
25015
25016    boolean canHaveOatDir(String packageName) {
25017        synchronized (mPackages) {
25018            PackageParser.Package p = mPackages.get(packageName);
25019            if (p == null) {
25020                return false;
25021            }
25022            return p.canHaveOatDir();
25023        }
25024    }
25025
25026    private String getOatDir(PackageParser.Package pkg) {
25027        if (!pkg.canHaveOatDir()) {
25028            return null;
25029        }
25030        File codePath = new File(pkg.codePath);
25031        if (codePath.isDirectory()) {
25032            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25033        }
25034        return null;
25035    }
25036
25037    void deleteOatArtifactsOfPackage(String packageName) {
25038        final String[] instructionSets;
25039        final List<String> codePaths;
25040        final String oatDir;
25041        final PackageParser.Package pkg;
25042        synchronized (mPackages) {
25043            pkg = mPackages.get(packageName);
25044        }
25045        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25046        codePaths = pkg.getAllCodePaths();
25047        oatDir = getOatDir(pkg);
25048
25049        for (String codePath : codePaths) {
25050            for (String isa : instructionSets) {
25051                try {
25052                    mInstaller.deleteOdex(codePath, isa, oatDir);
25053                } catch (InstallerException e) {
25054                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25055                }
25056            }
25057        }
25058    }
25059
25060    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25061        Set<String> unusedPackages = new HashSet<>();
25062        long currentTimeInMillis = System.currentTimeMillis();
25063        synchronized (mPackages) {
25064            for (PackageParser.Package pkg : mPackages.values()) {
25065                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25066                if (ps == null) {
25067                    continue;
25068                }
25069                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25070                        pkg.packageName);
25071                if (PackageManagerServiceUtils
25072                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25073                                downgradeTimeThresholdMillis, packageUseInfo,
25074                                pkg.getLatestPackageUseTimeInMills(),
25075                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25076                    unusedPackages.add(pkg.packageName);
25077                }
25078            }
25079        }
25080        return unusedPackages;
25081    }
25082}
25083
25084interface PackageSender {
25085    void sendPackageBroadcast(final String action, final String pkg,
25086        final Bundle extras, final int flags, final String targetPkg,
25087        final IIntentReceiver finishedReceiver, final int[] userIds);
25088    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25089        int appId, int... userIds);
25090}
25091