PackageManagerService.java revision a27be6072e94ffc90892004378a91f0f60ecc74f
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_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_OEM;
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.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108
109import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
110
111import android.Manifest;
112import android.annotation.IntDef;
113import android.annotation.NonNull;
114import android.annotation.Nullable;
115import android.app.ActivityManager;
116import android.app.AppOpsManager;
117import android.app.IActivityManager;
118import android.app.ResourcesManager;
119import android.app.admin.IDevicePolicyManager;
120import android.app.admin.SecurityLog;
121import android.app.backup.IBackupManager;
122import android.content.BroadcastReceiver;
123import android.content.ComponentName;
124import android.content.ContentResolver;
125import android.content.Context;
126import android.content.IIntentReceiver;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.IntentSender.SendIntentException;
131import android.content.ServiceConnection;
132import android.content.pm.ActivityInfo;
133import android.content.pm.ApplicationInfo;
134import android.content.pm.AppsQueryHelper;
135import android.content.pm.AuxiliaryResolveInfo;
136import android.content.pm.ChangedPackages;
137import android.content.pm.ComponentInfo;
138import android.content.pm.FallbackCategoryProvider;
139import android.content.pm.FeatureInfo;
140import android.content.pm.IDexModuleRegisterCallback;
141import android.content.pm.IOnPermissionsChangeListener;
142import android.content.pm.IPackageDataObserver;
143import android.content.pm.IPackageDeleteObserver;
144import android.content.pm.IPackageDeleteObserver2;
145import android.content.pm.IPackageInstallObserver2;
146import android.content.pm.IPackageInstaller;
147import android.content.pm.IPackageManager;
148import android.content.pm.IPackageManagerNative;
149import android.content.pm.IPackageMoveObserver;
150import android.content.pm.IPackageStatsObserver;
151import android.content.pm.InstantAppInfo;
152import android.content.pm.InstantAppRequest;
153import android.content.pm.InstantAppResolveInfo;
154import android.content.pm.InstrumentationInfo;
155import android.content.pm.IntentFilterVerificationInfo;
156import android.content.pm.KeySet;
157import android.content.pm.PackageCleanItem;
158import android.content.pm.PackageInfo;
159import android.content.pm.PackageInfoLite;
160import android.content.pm.PackageInstaller;
161import android.content.pm.PackageManager;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageManagerInternal;
164import android.content.pm.PackageParser;
165import android.content.pm.PackageParser.ActivityIntentInfo;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.DisplayMetrics;
233import android.util.EventLog;
234import android.util.ExceptionUtils;
235import android.util.Log;
236import android.util.LogPrinter;
237import android.util.MathUtils;
238import android.util.PackageUtils;
239import android.util.Pair;
240import android.util.PrintStreamPrinter;
241import android.util.Slog;
242import android.util.SparseArray;
243import android.util.SparseBooleanArray;
244import android.util.SparseIntArray;
245import android.util.TimingsTraceLog;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.PermissionsState.PermissionState;
286import com.android.server.pm.Settings.DatabaseVersion;
287import com.android.server.pm.Settings.VersionInfo;
288import com.android.server.pm.dex.DexManager;
289import com.android.server.pm.dex.DexoptOptions;
290import com.android.server.pm.dex.PackageDexUsage;
291import com.android.server.pm.permission.BasePermission;
292import com.android.server.storage.DeviceStorageMonitorInternal;
293
294import dalvik.system.CloseGuard;
295import dalvik.system.DexFile;
296import dalvik.system.VMRuntime;
297
298import libcore.io.IoUtils;
299import libcore.io.Streams;
300import libcore.util.EmptyArray;
301
302import org.xmlpull.v1.XmlPullParser;
303import org.xmlpull.v1.XmlPullParserException;
304import org.xmlpull.v1.XmlSerializer;
305
306import java.io.BufferedOutputStream;
307import java.io.BufferedReader;
308import java.io.ByteArrayInputStream;
309import java.io.ByteArrayOutputStream;
310import java.io.File;
311import java.io.FileDescriptor;
312import java.io.FileInputStream;
313import java.io.FileOutputStream;
314import java.io.FileReader;
315import java.io.FilenameFilter;
316import java.io.IOException;
317import java.io.InputStream;
318import java.io.OutputStream;
319import java.io.PrintWriter;
320import java.lang.annotation.Retention;
321import java.lang.annotation.RetentionPolicy;
322import java.nio.charset.StandardCharsets;
323import java.security.DigestInputStream;
324import java.security.MessageDigest;
325import java.security.NoSuchAlgorithmException;
326import java.security.PublicKey;
327import java.security.SecureRandom;
328import java.security.cert.Certificate;
329import java.security.cert.CertificateEncodingException;
330import java.security.cert.CertificateException;
331import java.text.SimpleDateFormat;
332import java.util.ArrayList;
333import java.util.Arrays;
334import java.util.Collection;
335import java.util.Collections;
336import java.util.Comparator;
337import java.util.Date;
338import java.util.HashMap;
339import java.util.HashSet;
340import java.util.Iterator;
341import java.util.List;
342import java.util.Map;
343import java.util.Objects;
344import java.util.Set;
345import java.util.concurrent.CountDownLatch;
346import java.util.concurrent.Future;
347import java.util.concurrent.TimeUnit;
348import java.util.concurrent.atomic.AtomicBoolean;
349import java.util.concurrent.atomic.AtomicInteger;
350import java.util.zip.GZIPInputStream;
351
352/**
353 * Keep track of all those APKs everywhere.
354 * <p>
355 * Internally there are two important locks:
356 * <ul>
357 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
358 * and other related state. It is a fine-grained lock that should only be held
359 * momentarily, as it's one of the most contended locks in the system.
360 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
361 * operations typically involve heavy lifting of application data on disk. Since
362 * {@code installd} is single-threaded, and it's operations can often be slow,
363 * this lock should never be acquired while already holding {@link #mPackages}.
364 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
365 * holding {@link #mInstallLock}.
366 * </ul>
367 * Many internal methods rely on the caller to hold the appropriate locks, and
368 * this contract is expressed through method name suffixes:
369 * <ul>
370 * <li>fooLI(): the caller must hold {@link #mInstallLock}
371 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
372 * being modified must be frozen
373 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
374 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
375 * </ul>
376 * <p>
377 * Because this class is very central to the platform's security; please run all
378 * CTS and unit tests whenever making modifications:
379 *
380 * <pre>
381 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
382 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
383 * </pre>
384 */
385public class PackageManagerService extends IPackageManager.Stub
386        implements PackageSender {
387    static final String TAG = "PackageManager";
388    public static final boolean DEBUG_SETTINGS = false;
389    static final boolean DEBUG_PREFERRED = false;
390    static final boolean DEBUG_UPGRADE = false;
391    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
392    private static final boolean DEBUG_BACKUP = false;
393    private static final boolean DEBUG_INSTALL = false;
394    private static final boolean DEBUG_REMOVE = false;
395    private static final boolean DEBUG_BROADCASTS = false;
396    private static final boolean DEBUG_SHOW_INFO = false;
397    private static final boolean DEBUG_PACKAGE_INFO = false;
398    private static final boolean DEBUG_INTENT_MATCHING = false;
399    public static final boolean DEBUG_PACKAGE_SCANNING = false;
400    private static final boolean DEBUG_VERIFY = false;
401    private static final boolean DEBUG_FILTERS = false;
402    private static final boolean DEBUG_PERMISSIONS = false;
403    private static final boolean DEBUG_SHARED_LIBRARIES = false;
404    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
405
406    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
407    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
408    // user, but by default initialize to this.
409    public static final boolean DEBUG_DEXOPT = false;
410
411    private static final boolean DEBUG_ABI_SELECTION = false;
412    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
413    private static final boolean DEBUG_TRIAGED_MISSING = false;
414    private static final boolean DEBUG_APP_DATA = false;
415
416    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
417    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
418
419    private static final boolean HIDE_EPHEMERAL_APIS = false;
420
421    private static final boolean ENABLE_FREE_CACHE_V2 =
422            SystemProperties.getBoolean("fw.free_cache_v2", true);
423
424    private static final int RADIO_UID = Process.PHONE_UID;
425    private static final int LOG_UID = Process.LOG_UID;
426    private static final int NFC_UID = Process.NFC_UID;
427    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
428    private static final int SHELL_UID = Process.SHELL_UID;
429
430    // Cap the size of permission trees that 3rd party apps can define
431    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
432
433    // Suffix used during package installation when copying/moving
434    // package apks to install directory.
435    private static final String INSTALL_PACKAGE_SUFFIX = "-";
436
437    static final int SCAN_NO_DEX = 1<<1;
438    static final int SCAN_FORCE_DEX = 1<<2;
439    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
440    static final int SCAN_NEW_INSTALL = 1<<4;
441    static final int SCAN_UPDATE_TIME = 1<<5;
442    static final int SCAN_BOOTING = 1<<6;
443    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
444    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
445    static final int SCAN_REPLACING = 1<<9;
446    static final int SCAN_REQUIRE_KNOWN = 1<<10;
447    static final int SCAN_MOVE = 1<<11;
448    static final int SCAN_INITIAL = 1<<12;
449    static final int SCAN_CHECK_ONLY = 1<<13;
450    static final int SCAN_DONT_KILL_APP = 1<<14;
451    static final int SCAN_IGNORE_FROZEN = 1<<15;
452    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
453    static final int SCAN_AS_INSTANT_APP = 1<<17;
454    static final int SCAN_AS_FULL_APP = 1<<18;
455    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
456    /** Should not be with the scan flags */
457    static final int FLAGS_REMOVE_CHATTY = 1<<31;
458
459    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
460    /** Extension of the compressed packages */
461    private final static String COMPRESSED_EXTENSION = ".gz";
462    /** Suffix of stub packages on the system partition */
463    private final static String STUB_SUFFIX = "-Stub";
464
465    private static final int[] EMPTY_INT_ARRAY = new int[0];
466
467    private static final int TYPE_UNKNOWN = 0;
468    private static final int TYPE_ACTIVITY = 1;
469    private static final int TYPE_RECEIVER = 2;
470    private static final int TYPE_SERVICE = 3;
471    private static final int TYPE_PROVIDER = 4;
472    @IntDef(prefix = { "TYPE_" }, value = {
473            TYPE_UNKNOWN,
474            TYPE_ACTIVITY,
475            TYPE_RECEIVER,
476            TYPE_SERVICE,
477            TYPE_PROVIDER,
478    })
479    @Retention(RetentionPolicy.SOURCE)
480    public @interface ComponentType {}
481
482    /**
483     * Timeout (in milliseconds) after which the watchdog should declare that
484     * our handler thread is wedged.  The usual default for such things is one
485     * minute but we sometimes do very lengthy I/O operations on this thread,
486     * such as installing multi-gigabyte applications, so ours needs to be longer.
487     */
488    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
489
490    /**
491     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
492     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
493     * settings entry if available, otherwise we use the hardcoded default.  If it's been
494     * more than this long since the last fstrim, we force one during the boot sequence.
495     *
496     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
497     * one gets run at the next available charging+idle time.  This final mandatory
498     * no-fstrim check kicks in only of the other scheduling criteria is never met.
499     */
500    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
501
502    /**
503     * Whether verification is enabled by default.
504     */
505    private static final boolean DEFAULT_VERIFY_ENABLE = true;
506
507    /**
508     * The default maximum time to wait for the verification agent to return in
509     * milliseconds.
510     */
511    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
512
513    /**
514     * The default response for package verification timeout.
515     *
516     * This can be either PackageManager.VERIFICATION_ALLOW or
517     * PackageManager.VERIFICATION_REJECT.
518     */
519    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
520
521    static final String PLATFORM_PACKAGE_NAME = "android";
522
523    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
524
525    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
526            DEFAULT_CONTAINER_PACKAGE,
527            "com.android.defcontainer.DefaultContainerService");
528
529    private static final String KILL_APP_REASON_GIDS_CHANGED =
530            "permission grant or revoke changed gids";
531
532    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
533            "permissions revoked";
534
535    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
536
537    private static final String PACKAGE_SCHEME = "package";
538
539    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
540
541    /** Permission grant: not grant the permission. */
542    private static final int GRANT_DENIED = 1;
543
544    /** Permission grant: grant the permission as an install permission. */
545    private static final int GRANT_INSTALL = 2;
546
547    /** Permission grant: grant the permission as a runtime one. */
548    private static final int GRANT_RUNTIME = 3;
549
550    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
551    private static final int GRANT_UPGRADE = 4;
552
553    /** Canonical intent used to identify what counts as a "web browser" app */
554    private static final Intent sBrowserIntent;
555    static {
556        sBrowserIntent = new Intent();
557        sBrowserIntent.setAction(Intent.ACTION_VIEW);
558        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
559        sBrowserIntent.setData(Uri.parse("http:"));
560    }
561
562    /**
563     * The set of all protected actions [i.e. those actions for which a high priority
564     * intent filter is disallowed].
565     */
566    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
567    static {
568        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
570        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
571        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
572    }
573
574    // Compilation reasons.
575    public static final int REASON_FIRST_BOOT = 0;
576    public static final int REASON_BOOT = 1;
577    public static final int REASON_INSTALL = 2;
578    public static final int REASON_BACKGROUND_DEXOPT = 3;
579    public static final int REASON_AB_OTA = 4;
580    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
581    public static final int REASON_SHARED = 6;
582
583    public static final int REASON_LAST = REASON_SHARED;
584
585    /** All dangerous permission names in the same order as the events in MetricsEvent */
586    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
587            Manifest.permission.READ_CALENDAR,
588            Manifest.permission.WRITE_CALENDAR,
589            Manifest.permission.CAMERA,
590            Manifest.permission.READ_CONTACTS,
591            Manifest.permission.WRITE_CONTACTS,
592            Manifest.permission.GET_ACCOUNTS,
593            Manifest.permission.ACCESS_FINE_LOCATION,
594            Manifest.permission.ACCESS_COARSE_LOCATION,
595            Manifest.permission.RECORD_AUDIO,
596            Manifest.permission.READ_PHONE_STATE,
597            Manifest.permission.CALL_PHONE,
598            Manifest.permission.READ_CALL_LOG,
599            Manifest.permission.WRITE_CALL_LOG,
600            Manifest.permission.ADD_VOICEMAIL,
601            Manifest.permission.USE_SIP,
602            Manifest.permission.PROCESS_OUTGOING_CALLS,
603            Manifest.permission.READ_CELL_BROADCASTS,
604            Manifest.permission.BODY_SENSORS,
605            Manifest.permission.SEND_SMS,
606            Manifest.permission.RECEIVE_SMS,
607            Manifest.permission.READ_SMS,
608            Manifest.permission.RECEIVE_WAP_PUSH,
609            Manifest.permission.RECEIVE_MMS,
610            Manifest.permission.READ_EXTERNAL_STORAGE,
611            Manifest.permission.WRITE_EXTERNAL_STORAGE,
612            Manifest.permission.READ_PHONE_NUMBERS,
613            Manifest.permission.ANSWER_PHONE_CALLS);
614
615
616    /**
617     * Version number for the package parser cache. Increment this whenever the format or
618     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
619     */
620    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
621
622    /**
623     * Whether the package parser cache is enabled.
624     */
625    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
626
627    final ServiceThread mHandlerThread;
628
629    final PackageHandler mHandler;
630
631    private final ProcessLoggingHandler mProcessLoggingHandler;
632
633    /**
634     * Messages for {@link #mHandler} that need to wait for system ready before
635     * being dispatched.
636     */
637    private ArrayList<Message> mPostSystemReadyMessages;
638
639    final int mSdkVersion = Build.VERSION.SDK_INT;
640
641    final Context mContext;
642    final boolean mFactoryTest;
643    final boolean mOnlyCore;
644    final DisplayMetrics mMetrics;
645    final int mDefParseFlags;
646    final String[] mSeparateProcesses;
647    final boolean mIsUpgrade;
648    final boolean mIsPreNUpgrade;
649    final boolean mIsPreNMR1Upgrade;
650
651    // Have we told the Activity Manager to whitelist the default container service by uid yet?
652    @GuardedBy("mPackages")
653    boolean mDefaultContainerWhitelisted = false;
654
655    @GuardedBy("mPackages")
656    private boolean mDexOptDialogShown;
657
658    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
659    // LOCK HELD.  Can be called with mInstallLock held.
660    @GuardedBy("mInstallLock")
661    final Installer mInstaller;
662
663    /** Directory where installed third-party apps stored */
664    final File mAppInstallDir;
665
666    /**
667     * Directory to which applications installed internally have their
668     * 32 bit native libraries copied.
669     */
670    private File mAppLib32InstallDir;
671
672    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
673    // apps.
674    final File mDrmAppPrivateInstallDir;
675
676    // ----------------------------------------------------------------
677
678    // Lock for state used when installing and doing other long running
679    // operations.  Methods that must be called with this lock held have
680    // the suffix "LI".
681    final Object mInstallLock = new Object();
682
683    // ----------------------------------------------------------------
684
685    // Keys are String (package name), values are Package.  This also serves
686    // as the lock for the global state.  Methods that must be called with
687    // this lock held have the prefix "LP".
688    @GuardedBy("mPackages")
689    final ArrayMap<String, PackageParser.Package> mPackages =
690            new ArrayMap<String, PackageParser.Package>();
691
692    final ArrayMap<String, Set<String>> mKnownCodebase =
693            new ArrayMap<String, Set<String>>();
694
695    // Keys are isolated uids and values are the uid of the application
696    // that created the isolated proccess.
697    @GuardedBy("mPackages")
698    final SparseIntArray mIsolatedOwners = new SparseIntArray();
699
700    /**
701     * Tracks new system packages [received in an OTA] that we expect to
702     * find updated user-installed versions. Keys are package name, values
703     * are package location.
704     */
705    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
706    /**
707     * Tracks high priority intent filters for protected actions. During boot, certain
708     * filter actions are protected and should never be allowed to have a high priority
709     * intent filter for them. However, there is one, and only one exception -- the
710     * setup wizard. It must be able to define a high priority intent filter for these
711     * actions to ensure there are no escapes from the wizard. We need to delay processing
712     * of these during boot as we need to look at all of the system packages in order
713     * to know which component is the setup wizard.
714     */
715    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
716    /**
717     * Whether or not processing protected filters should be deferred.
718     */
719    private boolean mDeferProtectedFilters = true;
720
721    /**
722     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
723     */
724    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
725    /**
726     * Whether or not system app permissions should be promoted from install to runtime.
727     */
728    boolean mPromoteSystemApps;
729
730    @GuardedBy("mPackages")
731    final Settings mSettings;
732
733    /**
734     * Set of package names that are currently "frozen", which means active
735     * surgery is being done on the code/data for that package. The platform
736     * will refuse to launch frozen packages to avoid race conditions.
737     *
738     * @see PackageFreezer
739     */
740    @GuardedBy("mPackages")
741    final ArraySet<String> mFrozenPackages = new ArraySet<>();
742
743    final ProtectedPackages mProtectedPackages;
744
745    @GuardedBy("mLoadedVolumes")
746    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
747
748    boolean mFirstBoot;
749
750    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
751
752    // System configuration read by SystemConfig.
753    final int[] mGlobalGids;
754    final SparseArray<ArraySet<String>> mSystemPermissions;
755    @GuardedBy("mAvailableFeatures")
756    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
757
758    // If mac_permissions.xml was found for seinfo labeling.
759    boolean mFoundPolicyFile;
760
761    private final InstantAppRegistry mInstantAppRegistry;
762
763    @GuardedBy("mPackages")
764    int mChangedPackagesSequenceNumber;
765    /**
766     * List of changed [installed, removed or updated] packages.
767     * mapping from user id -> sequence number -> package name
768     */
769    @GuardedBy("mPackages")
770    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
771    /**
772     * The sequence number of the last change to a package.
773     * mapping from user id -> package name -> sequence number
774     */
775    @GuardedBy("mPackages")
776    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
777
778    class PackageParserCallback implements PackageParser.Callback {
779        @Override public final boolean hasFeature(String feature) {
780            return PackageManagerService.this.hasSystemFeature(feature, 0);
781        }
782
783        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
784                Collection<PackageParser.Package> allPackages, String targetPackageName) {
785            List<PackageParser.Package> overlayPackages = null;
786            for (PackageParser.Package p : allPackages) {
787                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
788                    if (overlayPackages == null) {
789                        overlayPackages = new ArrayList<PackageParser.Package>();
790                    }
791                    overlayPackages.add(p);
792                }
793            }
794            if (overlayPackages != null) {
795                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
796                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
797                        return p1.mOverlayPriority - p2.mOverlayPriority;
798                    }
799                };
800                Collections.sort(overlayPackages, cmp);
801            }
802            return overlayPackages;
803        }
804
805        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
806                String targetPackageName, String targetPath) {
807            if ("android".equals(targetPackageName)) {
808                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
809                // native AssetManager.
810                return null;
811            }
812            List<PackageParser.Package> overlayPackages =
813                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
814            if (overlayPackages == null || overlayPackages.isEmpty()) {
815                return null;
816            }
817            List<String> overlayPathList = null;
818            for (PackageParser.Package overlayPackage : overlayPackages) {
819                if (targetPath == null) {
820                    if (overlayPathList == null) {
821                        overlayPathList = new ArrayList<String>();
822                    }
823                    overlayPathList.add(overlayPackage.baseCodePath);
824                    continue;
825                }
826
827                try {
828                    // Creates idmaps for system to parse correctly the Android manifest of the
829                    // target package.
830                    //
831                    // OverlayManagerService will update each of them with a correct gid from its
832                    // target package app id.
833                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
834                            UserHandle.getSharedAppGid(
835                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
836                    if (overlayPathList == null) {
837                        overlayPathList = new ArrayList<String>();
838                    }
839                    overlayPathList.add(overlayPackage.baseCodePath);
840                } catch (InstallerException e) {
841                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
842                            overlayPackage.baseCodePath);
843                }
844            }
845            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
846        }
847
848        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
849            synchronized (mPackages) {
850                return getStaticOverlayPathsLocked(
851                        mPackages.values(), targetPackageName, targetPath);
852            }
853        }
854
855        @Override public final String[] getOverlayApks(String targetPackageName) {
856            return getStaticOverlayPaths(targetPackageName, null);
857        }
858
859        @Override public final String[] getOverlayPaths(String targetPackageName,
860                String targetPath) {
861            return getStaticOverlayPaths(targetPackageName, targetPath);
862        }
863    };
864
865    class ParallelPackageParserCallback extends PackageParserCallback {
866        List<PackageParser.Package> mOverlayPackages = null;
867
868        void findStaticOverlayPackages() {
869            synchronized (mPackages) {
870                for (PackageParser.Package p : mPackages.values()) {
871                    if (p.mIsStaticOverlay) {
872                        if (mOverlayPackages == null) {
873                            mOverlayPackages = new ArrayList<PackageParser.Package>();
874                        }
875                        mOverlayPackages.add(p);
876                    }
877                }
878            }
879        }
880
881        @Override
882        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
883            // We can trust mOverlayPackages without holding mPackages because package uninstall
884            // can't happen while running parallel parsing.
885            // Moreover holding mPackages on each parsing thread causes dead-lock.
886            return mOverlayPackages == null ? null :
887                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
888        }
889    }
890
891    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
892    final ParallelPackageParserCallback mParallelPackageParserCallback =
893            new ParallelPackageParserCallback();
894
895    public static final class SharedLibraryEntry {
896        public final @Nullable String path;
897        public final @Nullable String apk;
898        public final @NonNull SharedLibraryInfo info;
899
900        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
901                String declaringPackageName, int declaringPackageVersionCode) {
902            path = _path;
903            apk = _apk;
904            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
905                    declaringPackageName, declaringPackageVersionCode), null);
906        }
907    }
908
909    // Currently known shared libraries.
910    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
911    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
912            new ArrayMap<>();
913
914    // All available activities, for your resolving pleasure.
915    final ActivityIntentResolver mActivities =
916            new ActivityIntentResolver();
917
918    // All available receivers, for your resolving pleasure.
919    final ActivityIntentResolver mReceivers =
920            new ActivityIntentResolver();
921
922    // All available services, for your resolving pleasure.
923    final ServiceIntentResolver mServices = new ServiceIntentResolver();
924
925    // All available providers, for your resolving pleasure.
926    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
927
928    // Mapping from provider base names (first directory in content URI codePath)
929    // to the provider information.
930    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
931            new ArrayMap<String, PackageParser.Provider>();
932
933    // Mapping from instrumentation class names to info about them.
934    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
935            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
936
937    // Mapping from permission names to info about them.
938    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
939            new ArrayMap<String, PackageParser.PermissionGroup>();
940
941    // Packages whose data we have transfered into another package, thus
942    // should no longer exist.
943    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
944
945    // Broadcast actions that are only available to the system.
946    @GuardedBy("mProtectedBroadcasts")
947    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
948
949    /** List of packages waiting for verification. */
950    final SparseArray<PackageVerificationState> mPendingVerification
951            = new SparseArray<PackageVerificationState>();
952
953    /** Set of packages associated with each app op permission. */
954    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
955
956    final PackageInstallerService mInstallerService;
957
958    private final PackageDexOptimizer mPackageDexOptimizer;
959    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
960    // is used by other apps).
961    private final DexManager mDexManager;
962
963    private AtomicInteger mNextMoveId = new AtomicInteger();
964    private final MoveCallbacks mMoveCallbacks;
965
966    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
967
968    // Cache of users who need badging.
969    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
970
971    /** Token for keys in mPendingVerification. */
972    private int mPendingVerificationToken = 0;
973
974    volatile boolean mSystemReady;
975    volatile boolean mSafeMode;
976    volatile boolean mHasSystemUidErrors;
977    private volatile boolean mEphemeralAppsDisabled;
978
979    ApplicationInfo mAndroidApplication;
980    final ActivityInfo mResolveActivity = new ActivityInfo();
981    final ResolveInfo mResolveInfo = new ResolveInfo();
982    ComponentName mResolveComponentName;
983    PackageParser.Package mPlatformPackage;
984    ComponentName mCustomResolverComponentName;
985
986    boolean mResolverReplaced = false;
987
988    private final @Nullable ComponentName mIntentFilterVerifierComponent;
989    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
990
991    private int mIntentFilterVerificationToken = 0;
992
993    /** The service connection to the ephemeral resolver */
994    final EphemeralResolverConnection mInstantAppResolverConnection;
995    /** Component used to show resolver settings for Instant Apps */
996    final ComponentName mInstantAppResolverSettingsComponent;
997
998    /** Activity used to install instant applications */
999    ActivityInfo mInstantAppInstallerActivity;
1000    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1001
1002    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1003            = new SparseArray<IntentFilterVerificationState>();
1004
1005    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1006
1007    // List of packages names to keep cached, even if they are uninstalled for all users
1008    private List<String> mKeepUninstalledPackages;
1009
1010    private UserManagerInternal mUserManagerInternal;
1011
1012    private DeviceIdleController.LocalService mDeviceIdleController;
1013
1014    private File mCacheDir;
1015
1016    private ArraySet<String> mPrivappPermissionsViolations;
1017
1018    private Future<?> mPrepareAppDataFuture;
1019
1020    private static class IFVerificationParams {
1021        PackageParser.Package pkg;
1022        boolean replacing;
1023        int userId;
1024        int verifierUid;
1025
1026        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1027                int _userId, int _verifierUid) {
1028            pkg = _pkg;
1029            replacing = _replacing;
1030            userId = _userId;
1031            replacing = _replacing;
1032            verifierUid = _verifierUid;
1033        }
1034    }
1035
1036    private interface IntentFilterVerifier<T extends IntentFilter> {
1037        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1038                                               T filter, String packageName);
1039        void startVerifications(int userId);
1040        void receiveVerificationResponse(int verificationId);
1041    }
1042
1043    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1044        private Context mContext;
1045        private ComponentName mIntentFilterVerifierComponent;
1046        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1047
1048        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1049            mContext = context;
1050            mIntentFilterVerifierComponent = verifierComponent;
1051        }
1052
1053        private String getDefaultScheme() {
1054            return IntentFilter.SCHEME_HTTPS;
1055        }
1056
1057        @Override
1058        public void startVerifications(int userId) {
1059            // Launch verifications requests
1060            int count = mCurrentIntentFilterVerifications.size();
1061            for (int n=0; n<count; n++) {
1062                int verificationId = mCurrentIntentFilterVerifications.get(n);
1063                final IntentFilterVerificationState ivs =
1064                        mIntentFilterVerificationStates.get(verificationId);
1065
1066                String packageName = ivs.getPackageName();
1067
1068                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1069                final int filterCount = filters.size();
1070                ArraySet<String> domainsSet = new ArraySet<>();
1071                for (int m=0; m<filterCount; m++) {
1072                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1073                    domainsSet.addAll(filter.getHostsList());
1074                }
1075                synchronized (mPackages) {
1076                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1077                            packageName, domainsSet) != null) {
1078                        scheduleWriteSettingsLocked();
1079                    }
1080                }
1081                sendVerificationRequest(verificationId, ivs);
1082            }
1083            mCurrentIntentFilterVerifications.clear();
1084        }
1085
1086        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1087            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1090                    verificationId);
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1093                    getDefaultScheme());
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1096                    ivs.getHostsString());
1097            verificationIntent.putExtra(
1098                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1099                    ivs.getPackageName());
1100            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1101            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1102
1103            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1104            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1105                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1106                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1107
1108            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1109            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1110                    "Sending IntentFilter verification broadcast");
1111        }
1112
1113        public void receiveVerificationResponse(int verificationId) {
1114            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1115
1116            final boolean verified = ivs.isVerified();
1117
1118            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1119            final int count = filters.size();
1120            if (DEBUG_DOMAIN_VERIFICATION) {
1121                Slog.i(TAG, "Received verification response " + verificationId
1122                        + " for " + count + " filters, verified=" + verified);
1123            }
1124            for (int n=0; n<count; n++) {
1125                PackageParser.ActivityIntentInfo filter = filters.get(n);
1126                filter.setVerified(verified);
1127
1128                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1129                        + " verified with result:" + verified + " and hosts:"
1130                        + ivs.getHostsString());
1131            }
1132
1133            mIntentFilterVerificationStates.remove(verificationId);
1134
1135            final String packageName = ivs.getPackageName();
1136            IntentFilterVerificationInfo ivi = null;
1137
1138            synchronized (mPackages) {
1139                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1140            }
1141            if (ivi == null) {
1142                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1143                        + verificationId + " packageName:" + packageName);
1144                return;
1145            }
1146            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1147                    "Updating IntentFilterVerificationInfo for package " + packageName
1148                            +" verificationId:" + verificationId);
1149
1150            synchronized (mPackages) {
1151                if (verified) {
1152                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1153                } else {
1154                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1155                }
1156                scheduleWriteSettingsLocked();
1157
1158                final int userId = ivs.getUserId();
1159                if (userId != UserHandle.USER_ALL) {
1160                    final int userStatus =
1161                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1162
1163                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1164                    boolean needUpdate = false;
1165
1166                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1167                    // already been set by the User thru the Disambiguation dialog
1168                    switch (userStatus) {
1169                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1170                            if (verified) {
1171                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1172                            } else {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1174                            }
1175                            needUpdate = true;
1176                            break;
1177
1178                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1179                            if (verified) {
1180                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1181                                needUpdate = true;
1182                            }
1183                            break;
1184
1185                        default:
1186                            // Nothing to do
1187                    }
1188
1189                    if (needUpdate) {
1190                        mSettings.updateIntentFilterVerificationStatusLPw(
1191                                packageName, updatedStatus, userId);
1192                        scheduleWritePackageRestrictionsLocked(userId);
1193                    }
1194                }
1195            }
1196        }
1197
1198        @Override
1199        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1200                    ActivityIntentInfo filter, String packageName) {
1201            if (!hasValidDomains(filter)) {
1202                return false;
1203            }
1204            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1205            if (ivs == null) {
1206                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1207                        packageName);
1208            }
1209            if (DEBUG_DOMAIN_VERIFICATION) {
1210                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1211            }
1212            ivs.addFilter(filter);
1213            return true;
1214        }
1215
1216        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1217                int userId, int verificationId, String packageName) {
1218            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1219                    verifierUid, userId, packageName);
1220            ivs.setPendingState();
1221            synchronized (mPackages) {
1222                mIntentFilterVerificationStates.append(verificationId, ivs);
1223                mCurrentIntentFilterVerifications.add(verificationId);
1224            }
1225            return ivs;
1226        }
1227    }
1228
1229    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1230        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1231                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1232                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1233    }
1234
1235    // Set of pending broadcasts for aggregating enable/disable of components.
1236    static class PendingPackageBroadcasts {
1237        // for each user id, a map of <package name -> components within that package>
1238        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1239
1240        public PendingPackageBroadcasts() {
1241            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1242        }
1243
1244        public ArrayList<String> get(int userId, String packageName) {
1245            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1246            return packages.get(packageName);
1247        }
1248
1249        public void put(int userId, String packageName, ArrayList<String> components) {
1250            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1251            packages.put(packageName, components);
1252        }
1253
1254        public void remove(int userId, String packageName) {
1255            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1256            if (packages != null) {
1257                packages.remove(packageName);
1258            }
1259        }
1260
1261        public void remove(int userId) {
1262            mUidMap.remove(userId);
1263        }
1264
1265        public int userIdCount() {
1266            return mUidMap.size();
1267        }
1268
1269        public int userIdAt(int n) {
1270            return mUidMap.keyAt(n);
1271        }
1272
1273        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1274            return mUidMap.get(userId);
1275        }
1276
1277        public int size() {
1278            // total number of pending broadcast entries across all userIds
1279            int num = 0;
1280            for (int i = 0; i< mUidMap.size(); i++) {
1281                num += mUidMap.valueAt(i).size();
1282            }
1283            return num;
1284        }
1285
1286        public void clear() {
1287            mUidMap.clear();
1288        }
1289
1290        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1291            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1292            if (map == null) {
1293                map = new ArrayMap<String, ArrayList<String>>();
1294                mUidMap.put(userId, map);
1295            }
1296            return map;
1297        }
1298    }
1299    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1300
1301    // Service Connection to remote media container service to copy
1302    // package uri's from external media onto secure containers
1303    // or internal storage.
1304    private IMediaContainerService mContainerService = null;
1305
1306    static final int SEND_PENDING_BROADCAST = 1;
1307    static final int MCS_BOUND = 3;
1308    static final int END_COPY = 4;
1309    static final int INIT_COPY = 5;
1310    static final int MCS_UNBIND = 6;
1311    static final int START_CLEANING_PACKAGE = 7;
1312    static final int FIND_INSTALL_LOC = 8;
1313    static final int POST_INSTALL = 9;
1314    static final int MCS_RECONNECT = 10;
1315    static final int MCS_GIVE_UP = 11;
1316    static final int WRITE_SETTINGS = 13;
1317    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1318    static final int PACKAGE_VERIFIED = 15;
1319    static final int CHECK_PENDING_VERIFICATION = 16;
1320    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1321    static final int INTENT_FILTER_VERIFIED = 18;
1322    static final int WRITE_PACKAGE_LIST = 19;
1323    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1324
1325    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1326
1327    // Delay time in millisecs
1328    static final int BROADCAST_DELAY = 10 * 1000;
1329
1330    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1331            2 * 60 * 60 * 1000L; /* two hours */
1332
1333    static UserManagerService sUserManager;
1334
1335    // Stores a list of users whose package restrictions file needs to be updated
1336    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1337
1338    final private DefaultContainerConnection mDefContainerConn =
1339            new DefaultContainerConnection();
1340    class DefaultContainerConnection implements ServiceConnection {
1341        public void onServiceConnected(ComponentName name, IBinder service) {
1342            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1343            final IMediaContainerService imcs = IMediaContainerService.Stub
1344                    .asInterface(Binder.allowBlocking(service));
1345            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1346        }
1347
1348        public void onServiceDisconnected(ComponentName name) {
1349            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1350        }
1351    }
1352
1353    // Recordkeeping of restore-after-install operations that are currently in flight
1354    // between the Package Manager and the Backup Manager
1355    static class PostInstallData {
1356        public InstallArgs args;
1357        public PackageInstalledInfo res;
1358
1359        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1360            args = _a;
1361            res = _r;
1362        }
1363    }
1364
1365    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1366    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1367
1368    // XML tags for backup/restore of various bits of state
1369    private static final String TAG_PREFERRED_BACKUP = "pa";
1370    private static final String TAG_DEFAULT_APPS = "da";
1371    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1372
1373    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1374    private static final String TAG_ALL_GRANTS = "rt-grants";
1375    private static final String TAG_GRANT = "grant";
1376    private static final String ATTR_PACKAGE_NAME = "pkg";
1377
1378    private static final String TAG_PERMISSION = "perm";
1379    private static final String ATTR_PERMISSION_NAME = "name";
1380    private static final String ATTR_IS_GRANTED = "g";
1381    private static final String ATTR_USER_SET = "set";
1382    private static final String ATTR_USER_FIXED = "fixed";
1383    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1384
1385    // System/policy permission grants are not backed up
1386    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1387            FLAG_PERMISSION_POLICY_FIXED
1388            | FLAG_PERMISSION_SYSTEM_FIXED
1389            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1390
1391    // And we back up these user-adjusted states
1392    private static final int USER_RUNTIME_GRANT_MASK =
1393            FLAG_PERMISSION_USER_SET
1394            | FLAG_PERMISSION_USER_FIXED
1395            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1396
1397    final @Nullable String mRequiredVerifierPackage;
1398    final @NonNull String mRequiredInstallerPackage;
1399    final @NonNull String mRequiredUninstallerPackage;
1400    final @Nullable String mSetupWizardPackage;
1401    final @Nullable String mStorageManagerPackage;
1402    final @NonNull String mServicesSystemSharedLibraryPackageName;
1403    final @NonNull String mSharedSystemSharedLibraryPackageName;
1404
1405    final boolean mPermissionReviewRequired;
1406
1407    private final PackageUsage mPackageUsage = new PackageUsage();
1408    private final CompilerStats mCompilerStats = new CompilerStats();
1409
1410    class PackageHandler extends Handler {
1411        private boolean mBound = false;
1412        final ArrayList<HandlerParams> mPendingInstalls =
1413            new ArrayList<HandlerParams>();
1414
1415        private boolean connectToService() {
1416            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1417                    " DefaultContainerService");
1418            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1419            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1420            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1421                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1422                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423                mBound = true;
1424                return true;
1425            }
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427            return false;
1428        }
1429
1430        private void disconnectService() {
1431            mContainerService = null;
1432            mBound = false;
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1434            mContext.unbindService(mDefContainerConn);
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1436        }
1437
1438        PackageHandler(Looper looper) {
1439            super(looper);
1440        }
1441
1442        public void handleMessage(Message msg) {
1443            try {
1444                doHandleMessage(msg);
1445            } finally {
1446                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1447            }
1448        }
1449
1450        void doHandleMessage(Message msg) {
1451            switch (msg.what) {
1452                case INIT_COPY: {
1453                    HandlerParams params = (HandlerParams) msg.obj;
1454                    int idx = mPendingInstalls.size();
1455                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1456                    // If a bind was already initiated we dont really
1457                    // need to do anything. The pending install
1458                    // will be processed later on.
1459                    if (!mBound) {
1460                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1461                                System.identityHashCode(mHandler));
1462                        // If this is the only one pending we might
1463                        // have to bind to the service again.
1464                        if (!connectToService()) {
1465                            Slog.e(TAG, "Failed to bind to media container service");
1466                            params.serviceError();
1467                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1468                                    System.identityHashCode(mHandler));
1469                            if (params.traceMethod != null) {
1470                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1471                                        params.traceCookie);
1472                            }
1473                            return;
1474                        } else {
1475                            // Once we bind to the service, the first
1476                            // pending request will be processed.
1477                            mPendingInstalls.add(idx, params);
1478                        }
1479                    } else {
1480                        mPendingInstalls.add(idx, params);
1481                        // Already bound to the service. Just make
1482                        // sure we trigger off processing the first request.
1483                        if (idx == 0) {
1484                            mHandler.sendEmptyMessage(MCS_BOUND);
1485                        }
1486                    }
1487                    break;
1488                }
1489                case MCS_BOUND: {
1490                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1491                    if (msg.obj != null) {
1492                        mContainerService = (IMediaContainerService) msg.obj;
1493                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1494                                System.identityHashCode(mHandler));
1495                    }
1496                    if (mContainerService == null) {
1497                        if (!mBound) {
1498                            // Something seriously wrong since we are not bound and we are not
1499                            // waiting for connection. Bail out.
1500                            Slog.e(TAG, "Cannot bind to media container service");
1501                            for (HandlerParams params : mPendingInstalls) {
1502                                // Indicate service bind error
1503                                params.serviceError();
1504                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1505                                        System.identityHashCode(params));
1506                                if (params.traceMethod != null) {
1507                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1508                                            params.traceMethod, params.traceCookie);
1509                                }
1510                                return;
1511                            }
1512                            mPendingInstalls.clear();
1513                        } else {
1514                            Slog.w(TAG, "Waiting to connect to media container service");
1515                        }
1516                    } else if (mPendingInstalls.size() > 0) {
1517                        HandlerParams params = mPendingInstalls.get(0);
1518                        if (params != null) {
1519                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1520                                    System.identityHashCode(params));
1521                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1522                            if (params.startCopy()) {
1523                                // We are done...  look for more work or to
1524                                // go idle.
1525                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1526                                        "Checking for more work or unbind...");
1527                                // Delete pending install
1528                                if (mPendingInstalls.size() > 0) {
1529                                    mPendingInstalls.remove(0);
1530                                }
1531                                if (mPendingInstalls.size() == 0) {
1532                                    if (mBound) {
1533                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1534                                                "Posting delayed MCS_UNBIND");
1535                                        removeMessages(MCS_UNBIND);
1536                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1537                                        // Unbind after a little delay, to avoid
1538                                        // continual thrashing.
1539                                        sendMessageDelayed(ubmsg, 10000);
1540                                    }
1541                                } else {
1542                                    // There are more pending requests in queue.
1543                                    // Just post MCS_BOUND message to trigger processing
1544                                    // of next pending install.
1545                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1546                                            "Posting MCS_BOUND for next work");
1547                                    mHandler.sendEmptyMessage(MCS_BOUND);
1548                                }
1549                            }
1550                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1551                        }
1552                    } else {
1553                        // Should never happen ideally.
1554                        Slog.w(TAG, "Empty queue");
1555                    }
1556                    break;
1557                }
1558                case MCS_RECONNECT: {
1559                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1560                    if (mPendingInstalls.size() > 0) {
1561                        if (mBound) {
1562                            disconnectService();
1563                        }
1564                        if (!connectToService()) {
1565                            Slog.e(TAG, "Failed to bind to media container service");
1566                            for (HandlerParams params : mPendingInstalls) {
1567                                // Indicate service bind error
1568                                params.serviceError();
1569                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1570                                        System.identityHashCode(params));
1571                            }
1572                            mPendingInstalls.clear();
1573                        }
1574                    }
1575                    break;
1576                }
1577                case MCS_UNBIND: {
1578                    // If there is no actual work left, then time to unbind.
1579                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1580
1581                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1582                        if (mBound) {
1583                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1584
1585                            disconnectService();
1586                        }
1587                    } else if (mPendingInstalls.size() > 0) {
1588                        // There are more pending requests in queue.
1589                        // Just post MCS_BOUND message to trigger processing
1590                        // of next pending install.
1591                        mHandler.sendEmptyMessage(MCS_BOUND);
1592                    }
1593
1594                    break;
1595                }
1596                case MCS_GIVE_UP: {
1597                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1598                    HandlerParams params = mPendingInstalls.remove(0);
1599                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1600                            System.identityHashCode(params));
1601                    break;
1602                }
1603                case SEND_PENDING_BROADCAST: {
1604                    String packages[];
1605                    ArrayList<String> components[];
1606                    int size = 0;
1607                    int uids[];
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        if (mPendingBroadcasts == null) {
1611                            return;
1612                        }
1613                        size = mPendingBroadcasts.size();
1614                        if (size <= 0) {
1615                            // Nothing to be done. Just return
1616                            return;
1617                        }
1618                        packages = new String[size];
1619                        components = new ArrayList[size];
1620                        uids = new int[size];
1621                        int i = 0;  // filling out the above arrays
1622
1623                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1624                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1625                            Iterator<Map.Entry<String, ArrayList<String>>> it
1626                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1627                                            .entrySet().iterator();
1628                            while (it.hasNext() && i < size) {
1629                                Map.Entry<String, ArrayList<String>> ent = it.next();
1630                                packages[i] = ent.getKey();
1631                                components[i] = ent.getValue();
1632                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1633                                uids[i] = (ps != null)
1634                                        ? UserHandle.getUid(packageUserId, ps.appId)
1635                                        : -1;
1636                                i++;
1637                            }
1638                        }
1639                        size = i;
1640                        mPendingBroadcasts.clear();
1641                    }
1642                    // Send broadcasts
1643                    for (int i = 0; i < size; i++) {
1644                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1645                    }
1646                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647                    break;
1648                }
1649                case START_CLEANING_PACKAGE: {
1650                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1651                    final String packageName = (String)msg.obj;
1652                    final int userId = msg.arg1;
1653                    final boolean andCode = msg.arg2 != 0;
1654                    synchronized (mPackages) {
1655                        if (userId == UserHandle.USER_ALL) {
1656                            int[] users = sUserManager.getUserIds();
1657                            for (int user : users) {
1658                                mSettings.addPackageToCleanLPw(
1659                                        new PackageCleanItem(user, packageName, andCode));
1660                            }
1661                        } else {
1662                            mSettings.addPackageToCleanLPw(
1663                                    new PackageCleanItem(userId, packageName, andCode));
1664                        }
1665                    }
1666                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1667                    startCleaningPackages();
1668                } break;
1669                case POST_INSTALL: {
1670                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1671
1672                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1673                    final boolean didRestore = (msg.arg2 != 0);
1674                    mRunningInstalls.delete(msg.arg1);
1675
1676                    if (data != null) {
1677                        InstallArgs args = data.args;
1678                        PackageInstalledInfo parentRes = data.res;
1679
1680                        final boolean grantPermissions = (args.installFlags
1681                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1682                        final boolean killApp = (args.installFlags
1683                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1684                        final boolean virtualPreload = ((args.installFlags
1685                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1686                        final String[] grantedPermissions = args.installGrantPermissions;
1687
1688                        // Handle the parent package
1689                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1690                                virtualPreload, grantedPermissions, didRestore,
1691                                args.installerPackageName, args.observer);
1692
1693                        // Handle the child packages
1694                        final int childCount = (parentRes.addedChildPackages != null)
1695                                ? parentRes.addedChildPackages.size() : 0;
1696                        for (int i = 0; i < childCount; i++) {
1697                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1698                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1699                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1700                                    args.installerPackageName, args.observer);
1701                        }
1702
1703                        // Log tracing if needed
1704                        if (args.traceMethod != null) {
1705                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1706                                    args.traceCookie);
1707                        }
1708                    } else {
1709                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1710                    }
1711
1712                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1713                } break;
1714                case WRITE_SETTINGS: {
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1716                    synchronized (mPackages) {
1717                        removeMessages(WRITE_SETTINGS);
1718                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1719                        mSettings.writeLPr();
1720                        mDirtyUsers.clear();
1721                    }
1722                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1723                } break;
1724                case WRITE_PACKAGE_RESTRICTIONS: {
1725                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1726                    synchronized (mPackages) {
1727                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1728                        for (int userId : mDirtyUsers) {
1729                            mSettings.writePackageRestrictionsLPr(userId);
1730                        }
1731                        mDirtyUsers.clear();
1732                    }
1733                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1734                } break;
1735                case WRITE_PACKAGE_LIST: {
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1737                    synchronized (mPackages) {
1738                        removeMessages(WRITE_PACKAGE_LIST);
1739                        mSettings.writePackageListLPr(msg.arg1);
1740                    }
1741                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1742                } break;
1743                case CHECK_PENDING_VERIFICATION: {
1744                    final int verificationId = msg.arg1;
1745                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1746
1747                    if ((state != null) && !state.timeoutExtended()) {
1748                        final InstallArgs args = state.getInstallArgs();
1749                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1750
1751                        Slog.i(TAG, "Verification timed out for " + originUri);
1752                        mPendingVerification.remove(verificationId);
1753
1754                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1755
1756                        final UserHandle user = args.getUser();
1757                        if (getDefaultVerificationResponse(user)
1758                                == PackageManager.VERIFICATION_ALLOW) {
1759                            Slog.i(TAG, "Continuing with installation of " + originUri);
1760                            state.setVerifierResponse(Binder.getCallingUid(),
1761                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1762                            broadcastPackageVerified(verificationId, originUri,
1763                                    PackageManager.VERIFICATION_ALLOW, user);
1764                            try {
1765                                ret = args.copyApk(mContainerService, true);
1766                            } catch (RemoteException e) {
1767                                Slog.e(TAG, "Could not contact the ContainerService");
1768                            }
1769                        } else {
1770                            broadcastPackageVerified(verificationId, originUri,
1771                                    PackageManager.VERIFICATION_REJECT, user);
1772                        }
1773
1774                        Trace.asyncTraceEnd(
1775                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1776
1777                        processPendingInstall(args, ret);
1778                        mHandler.sendEmptyMessage(MCS_UNBIND);
1779                    }
1780                    break;
1781                }
1782                case PACKAGE_VERIFIED: {
1783                    final int verificationId = msg.arg1;
1784
1785                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1786                    if (state == null) {
1787                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1788                        break;
1789                    }
1790
1791                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1792
1793                    state.setVerifierResponse(response.callerUid, response.code);
1794
1795                    if (state.isVerificationComplete()) {
1796                        mPendingVerification.remove(verificationId);
1797
1798                        final InstallArgs args = state.getInstallArgs();
1799                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1800
1801                        int ret;
1802                        if (state.isInstallAllowed()) {
1803                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1804                            broadcastPackageVerified(verificationId, originUri,
1805                                    response.code, state.getInstallArgs().getUser());
1806                            try {
1807                                ret = args.copyApk(mContainerService, true);
1808                            } catch (RemoteException e) {
1809                                Slog.e(TAG, "Could not contact the ContainerService");
1810                            }
1811                        } else {
1812                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1813                        }
1814
1815                        Trace.asyncTraceEnd(
1816                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1817
1818                        processPendingInstall(args, ret);
1819                        mHandler.sendEmptyMessage(MCS_UNBIND);
1820                    }
1821
1822                    break;
1823                }
1824                case START_INTENT_FILTER_VERIFICATIONS: {
1825                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1826                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1827                            params.replacing, params.pkg);
1828                    break;
1829                }
1830                case INTENT_FILTER_VERIFIED: {
1831                    final int verificationId = msg.arg1;
1832
1833                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1834                            verificationId);
1835                    if (state == null) {
1836                        Slog.w(TAG, "Invalid IntentFilter verification token "
1837                                + verificationId + " received");
1838                        break;
1839                    }
1840
1841                    final int userId = state.getUserId();
1842
1843                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1844                            "Processing IntentFilter verification with token:"
1845                            + verificationId + " and userId:" + userId);
1846
1847                    final IntentFilterVerificationResponse response =
1848                            (IntentFilterVerificationResponse) msg.obj;
1849
1850                    state.setVerifierResponse(response.callerUid, response.code);
1851
1852                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1853                            "IntentFilter verification with token:" + verificationId
1854                            + " and userId:" + userId
1855                            + " is settings verifier response with response code:"
1856                            + response.code);
1857
1858                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1859                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1860                                + response.getFailedDomainsString());
1861                    }
1862
1863                    if (state.isVerificationComplete()) {
1864                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1865                    } else {
1866                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1867                                "IntentFilter verification with token:" + verificationId
1868                                + " was not said to be complete");
1869                    }
1870
1871                    break;
1872                }
1873                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1874                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1875                            mInstantAppResolverConnection,
1876                            (InstantAppRequest) msg.obj,
1877                            mInstantAppInstallerActivity,
1878                            mHandler);
1879                }
1880            }
1881        }
1882    }
1883
1884    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1885            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1886            boolean launchedForRestore, String installerPackage,
1887            IPackageInstallObserver2 installObserver) {
1888        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1889            // Send the removed broadcasts
1890            if (res.removedInfo != null) {
1891                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1892            }
1893
1894            // Now that we successfully installed the package, grant runtime
1895            // permissions if requested before broadcasting the install. Also
1896            // for legacy apps in permission review mode we clear the permission
1897            // review flag which is used to emulate runtime permissions for
1898            // legacy apps.
1899            if (grantPermissions) {
1900                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1901            }
1902
1903            final boolean update = res.removedInfo != null
1904                    && res.removedInfo.removedPackage != null;
1905            final String installerPackageName =
1906                    res.installerPackageName != null
1907                            ? res.installerPackageName
1908                            : res.removedInfo != null
1909                                    ? res.removedInfo.installerPackageName
1910                                    : null;
1911
1912            // If this is the first time we have child packages for a disabled privileged
1913            // app that had no children, we grant requested runtime permissions to the new
1914            // children if the parent on the system image had them already granted.
1915            if (res.pkg.parentPackage != null) {
1916                synchronized (mPackages) {
1917                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1918                }
1919            }
1920
1921            synchronized (mPackages) {
1922                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1923            }
1924
1925            final String packageName = res.pkg.applicationInfo.packageName;
1926
1927            // Determine the set of users who are adding this package for
1928            // the first time vs. those who are seeing an update.
1929            int[] firstUsers = EMPTY_INT_ARRAY;
1930            int[] updateUsers = EMPTY_INT_ARRAY;
1931            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1932            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1933            for (int newUser : res.newUsers) {
1934                if (ps.getInstantApp(newUser)) {
1935                    continue;
1936                }
1937                if (allNewUsers) {
1938                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1939                    continue;
1940                }
1941                boolean isNew = true;
1942                for (int origUser : res.origUsers) {
1943                    if (origUser == newUser) {
1944                        isNew = false;
1945                        break;
1946                    }
1947                }
1948                if (isNew) {
1949                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1950                } else {
1951                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1952                }
1953            }
1954
1955            // Send installed broadcasts if the package is not a static shared lib.
1956            if (res.pkg.staticSharedLibName == null) {
1957                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1958
1959                // Send added for users that see the package for the first time
1960                // sendPackageAddedForNewUsers also deals with system apps
1961                int appId = UserHandle.getAppId(res.uid);
1962                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1963                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1964                        virtualPreload /*startReceiver*/, appId, firstUsers);
1965
1966                // Send added for users that don't see the package for the first time
1967                Bundle extras = new Bundle(1);
1968                extras.putInt(Intent.EXTRA_UID, res.uid);
1969                if (update) {
1970                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1971                }
1972                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1973                        extras, 0 /*flags*/,
1974                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1975                if (installerPackageName != null) {
1976                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977                            extras, 0 /*flags*/,
1978                            installerPackageName, null /*finishedReceiver*/, updateUsers);
1979                }
1980
1981                // Send replaced for users that don't see the package for the first time
1982                if (update) {
1983                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1984                            packageName, extras, 0 /*flags*/,
1985                            null /*targetPackage*/, null /*finishedReceiver*/,
1986                            updateUsers);
1987                    if (installerPackageName != null) {
1988                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1989                                extras, 0 /*flags*/,
1990                                installerPackageName, null /*finishedReceiver*/, updateUsers);
1991                    }
1992                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1993                            null /*package*/, null /*extras*/, 0 /*flags*/,
1994                            packageName /*targetPackage*/,
1995                            null /*finishedReceiver*/, updateUsers);
1996                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1997                    // First-install and we did a restore, so we're responsible for the
1998                    // first-launch broadcast.
1999                    if (DEBUG_BACKUP) {
2000                        Slog.i(TAG, "Post-restore of " + packageName
2001                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2002                    }
2003                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2004                }
2005
2006                // Send broadcast package appeared if forward locked/external for all users
2007                // treat asec-hosted packages like removable media on upgrade
2008                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2009                    if (DEBUG_INSTALL) {
2010                        Slog.i(TAG, "upgrading pkg " + res.pkg
2011                                + " is ASEC-hosted -> AVAILABLE");
2012                    }
2013                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2014                    ArrayList<String> pkgList = new ArrayList<>(1);
2015                    pkgList.add(packageName);
2016                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2017                }
2018            }
2019
2020            // Work that needs to happen on first install within each user
2021            if (firstUsers != null && firstUsers.length > 0) {
2022                synchronized (mPackages) {
2023                    for (int userId : firstUsers) {
2024                        // If this app is a browser and it's newly-installed for some
2025                        // users, clear any default-browser state in those users. The
2026                        // app's nature doesn't depend on the user, so we can just check
2027                        // its browser nature in any user and generalize.
2028                        if (packageIsBrowser(packageName, userId)) {
2029                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2030                        }
2031
2032                        // We may also need to apply pending (restored) runtime
2033                        // permission grants within these users.
2034                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2035                    }
2036                }
2037            }
2038
2039            // Log current value of "unknown sources" setting
2040            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2041                    getUnknownSourcesSettings());
2042
2043            // Remove the replaced package's older resources safely now
2044            // We delete after a gc for applications  on sdcard.
2045            if (res.removedInfo != null && res.removedInfo.args != null) {
2046                Runtime.getRuntime().gc();
2047                synchronized (mInstallLock) {
2048                    res.removedInfo.args.doPostDeleteLI(true);
2049                }
2050            } else {
2051                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2052                // and not block here.
2053                VMRuntime.getRuntime().requestConcurrentGC();
2054            }
2055
2056            // Notify DexManager that the package was installed for new users.
2057            // The updated users should already be indexed and the package code paths
2058            // should not change.
2059            // Don't notify the manager for ephemeral apps as they are not expected to
2060            // survive long enough to benefit of background optimizations.
2061            for (int userId : firstUsers) {
2062                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2063                // There's a race currently where some install events may interleave with an uninstall.
2064                // This can lead to package info being null (b/36642664).
2065                if (info != null) {
2066                    mDexManager.notifyPackageInstalled(info, userId);
2067                }
2068            }
2069        }
2070
2071        // If someone is watching installs - notify them
2072        if (installObserver != null) {
2073            try {
2074                Bundle extras = extrasForInstallResult(res);
2075                installObserver.onPackageInstalled(res.name, res.returnCode,
2076                        res.returnMsg, extras);
2077            } catch (RemoteException e) {
2078                Slog.i(TAG, "Observer no longer exists.");
2079            }
2080        }
2081    }
2082
2083    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2084            PackageParser.Package pkg) {
2085        if (pkg.parentPackage == null) {
2086            return;
2087        }
2088        if (pkg.requestedPermissions == null) {
2089            return;
2090        }
2091        final PackageSetting disabledSysParentPs = mSettings
2092                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2093        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2094                || !disabledSysParentPs.isPrivileged()
2095                || (disabledSysParentPs.childPackageNames != null
2096                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2097            return;
2098        }
2099        final int[] allUserIds = sUserManager.getUserIds();
2100        final int permCount = pkg.requestedPermissions.size();
2101        for (int i = 0; i < permCount; i++) {
2102            String permission = pkg.requestedPermissions.get(i);
2103            BasePermission bp = mSettings.mPermissions.get(permission);
2104            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2105                continue;
2106            }
2107            for (int userId : allUserIds) {
2108                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2109                        permission, userId)) {
2110                    grantRuntimePermission(pkg.packageName, permission, userId);
2111                }
2112            }
2113        }
2114    }
2115
2116    private StorageEventListener mStorageListener = new StorageEventListener() {
2117        @Override
2118        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2119            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2120                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2121                    final String volumeUuid = vol.getFsUuid();
2122
2123                    // Clean up any users or apps that were removed or recreated
2124                    // while this volume was missing
2125                    sUserManager.reconcileUsers(volumeUuid);
2126                    reconcileApps(volumeUuid);
2127
2128                    // Clean up any install sessions that expired or were
2129                    // cancelled while this volume was missing
2130                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2131
2132                    loadPrivatePackages(vol);
2133
2134                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2135                    unloadPrivatePackages(vol);
2136                }
2137            }
2138        }
2139
2140        @Override
2141        public void onVolumeForgotten(String fsUuid) {
2142            if (TextUtils.isEmpty(fsUuid)) {
2143                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2144                return;
2145            }
2146
2147            // Remove any apps installed on the forgotten volume
2148            synchronized (mPackages) {
2149                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2150                for (PackageSetting ps : packages) {
2151                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2152                    deletePackageVersioned(new VersionedPackage(ps.name,
2153                            PackageManager.VERSION_CODE_HIGHEST),
2154                            new LegacyPackageDeleteObserver(null).getBinder(),
2155                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2156                    // Try very hard to release any references to this package
2157                    // so we don't risk the system server being killed due to
2158                    // open FDs
2159                    AttributeCache.instance().removePackage(ps.name);
2160                }
2161
2162                mSettings.onVolumeForgotten(fsUuid);
2163                mSettings.writeLPr();
2164            }
2165        }
2166    };
2167
2168    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2169            String[] grantedPermissions) {
2170        for (int userId : userIds) {
2171            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2172        }
2173    }
2174
2175    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2176            String[] grantedPermissions) {
2177        PackageSetting ps = (PackageSetting) pkg.mExtras;
2178        if (ps == null) {
2179            return;
2180        }
2181
2182        PermissionsState permissionsState = ps.getPermissionsState();
2183
2184        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2185                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2186
2187        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2188                >= Build.VERSION_CODES.M;
2189
2190        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2191
2192        for (String permission : pkg.requestedPermissions) {
2193            final BasePermission bp;
2194            synchronized (mPackages) {
2195                bp = mSettings.mPermissions.get(permission);
2196            }
2197            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2198                    && (!instantApp || bp.isInstant())
2199                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2200                    && (grantedPermissions == null
2201                           || ArrayUtils.contains(grantedPermissions, permission))) {
2202                final int flags = permissionsState.getPermissionFlags(permission, userId);
2203                if (supportsRuntimePermissions) {
2204                    // Installer cannot change immutable permissions.
2205                    if ((flags & immutableFlags) == 0) {
2206                        grantRuntimePermission(pkg.packageName, permission, userId);
2207                    }
2208                } else if (mPermissionReviewRequired) {
2209                    // In permission review mode we clear the review flag when we
2210                    // are asked to install the app with all permissions granted.
2211                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2212                        updatePermissionFlags(permission, pkg.packageName,
2213                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2214                    }
2215                }
2216            }
2217        }
2218    }
2219
2220    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2221        Bundle extras = null;
2222        switch (res.returnCode) {
2223            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2224                extras = new Bundle();
2225                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2226                        res.origPermission);
2227                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2228                        res.origPackage);
2229                break;
2230            }
2231            case PackageManager.INSTALL_SUCCEEDED: {
2232                extras = new Bundle();
2233                extras.putBoolean(Intent.EXTRA_REPLACING,
2234                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2235                break;
2236            }
2237        }
2238        return extras;
2239    }
2240
2241    void scheduleWriteSettingsLocked() {
2242        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2243            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2244        }
2245    }
2246
2247    void scheduleWritePackageListLocked(int userId) {
2248        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2249            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2250            msg.arg1 = userId;
2251            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2252        }
2253    }
2254
2255    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2256        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2257        scheduleWritePackageRestrictionsLocked(userId);
2258    }
2259
2260    void scheduleWritePackageRestrictionsLocked(int userId) {
2261        final int[] userIds = (userId == UserHandle.USER_ALL)
2262                ? sUserManager.getUserIds() : new int[]{userId};
2263        for (int nextUserId : userIds) {
2264            if (!sUserManager.exists(nextUserId)) return;
2265            mDirtyUsers.add(nextUserId);
2266            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2267                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2268            }
2269        }
2270    }
2271
2272    public static PackageManagerService main(Context context, Installer installer,
2273            boolean factoryTest, boolean onlyCore) {
2274        // Self-check for initial settings.
2275        PackageManagerServiceCompilerMapping.checkProperties();
2276
2277        PackageManagerService m = new PackageManagerService(context, installer,
2278                factoryTest, onlyCore);
2279        m.enableSystemUserPackages();
2280        ServiceManager.addService("package", m);
2281        final PackageManagerNative pmn = m.new PackageManagerNative();
2282        ServiceManager.addService("package_native", pmn);
2283        return m;
2284    }
2285
2286    private void enableSystemUserPackages() {
2287        if (!UserManager.isSplitSystemUser()) {
2288            return;
2289        }
2290        // For system user, enable apps based on the following conditions:
2291        // - app is whitelisted or belong to one of these groups:
2292        //   -- system app which has no launcher icons
2293        //   -- system app which has INTERACT_ACROSS_USERS permission
2294        //   -- system IME app
2295        // - app is not in the blacklist
2296        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2297        Set<String> enableApps = new ArraySet<>();
2298        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2299                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2300                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2301        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2302        enableApps.addAll(wlApps);
2303        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2304                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2305        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2306        enableApps.removeAll(blApps);
2307        Log.i(TAG, "Applications installed for system user: " + enableApps);
2308        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2309                UserHandle.SYSTEM);
2310        final int allAppsSize = allAps.size();
2311        synchronized (mPackages) {
2312            for (int i = 0; i < allAppsSize; i++) {
2313                String pName = allAps.get(i);
2314                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2315                // Should not happen, but we shouldn't be failing if it does
2316                if (pkgSetting == null) {
2317                    continue;
2318                }
2319                boolean install = enableApps.contains(pName);
2320                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2321                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2322                            + " for system user");
2323                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2324                }
2325            }
2326            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2327        }
2328    }
2329
2330    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2331        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2332                Context.DISPLAY_SERVICE);
2333        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2334    }
2335
2336    /**
2337     * Requests that files preopted on a secondary system partition be copied to the data partition
2338     * if possible.  Note that the actual copying of the files is accomplished by init for security
2339     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2340     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2341     */
2342    private static void requestCopyPreoptedFiles() {
2343        final int WAIT_TIME_MS = 100;
2344        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2345        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2346            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2347            // We will wait for up to 100 seconds.
2348            final long timeStart = SystemClock.uptimeMillis();
2349            final long timeEnd = timeStart + 100 * 1000;
2350            long timeNow = timeStart;
2351            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2352                try {
2353                    Thread.sleep(WAIT_TIME_MS);
2354                } catch (InterruptedException e) {
2355                    // Do nothing
2356                }
2357                timeNow = SystemClock.uptimeMillis();
2358                if (timeNow > timeEnd) {
2359                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2360                    Slog.wtf(TAG, "cppreopt did not finish!");
2361                    break;
2362                }
2363            }
2364
2365            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2366        }
2367    }
2368
2369    public PackageManagerService(Context context, Installer installer,
2370            boolean factoryTest, boolean onlyCore) {
2371        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2372        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2373        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2374                SystemClock.uptimeMillis());
2375
2376        if (mSdkVersion <= 0) {
2377            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2378        }
2379
2380        mContext = context;
2381
2382        mPermissionReviewRequired = context.getResources().getBoolean(
2383                R.bool.config_permissionReviewRequired);
2384
2385        mFactoryTest = factoryTest;
2386        mOnlyCore = onlyCore;
2387        mMetrics = new DisplayMetrics();
2388        mSettings = new Settings(mPackages);
2389        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2390                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2391        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2392                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2393        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2394                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2395        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2396                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2398                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401
2402        String separateProcesses = SystemProperties.get("debug.separate_processes");
2403        if (separateProcesses != null && separateProcesses.length() > 0) {
2404            if ("*".equals(separateProcesses)) {
2405                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2406                mSeparateProcesses = null;
2407                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2408            } else {
2409                mDefParseFlags = 0;
2410                mSeparateProcesses = separateProcesses.split(",");
2411                Slog.w(TAG, "Running with debug.separate_processes: "
2412                        + separateProcesses);
2413            }
2414        } else {
2415            mDefParseFlags = 0;
2416            mSeparateProcesses = null;
2417        }
2418
2419        mInstaller = installer;
2420        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2421                "*dexopt*");
2422        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2423        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2424
2425        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2426                FgThread.get().getLooper());
2427
2428        getDefaultDisplayMetrics(context, mMetrics);
2429
2430        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2431        SystemConfig systemConfig = SystemConfig.getInstance();
2432        mGlobalGids = systemConfig.getGlobalGids();
2433        mSystemPermissions = systemConfig.getSystemPermissions();
2434        mAvailableFeatures = systemConfig.getAvailableFeatures();
2435        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2436
2437        mProtectedPackages = new ProtectedPackages(mContext);
2438
2439        synchronized (mInstallLock) {
2440        // writer
2441        synchronized (mPackages) {
2442            mHandlerThread = new ServiceThread(TAG,
2443                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2444            mHandlerThread.start();
2445            mHandler = new PackageHandler(mHandlerThread.getLooper());
2446            mProcessLoggingHandler = new ProcessLoggingHandler();
2447            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2448
2449            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2450            mInstantAppRegistry = new InstantAppRegistry(this);
2451
2452            File dataDir = Environment.getDataDirectory();
2453            mAppInstallDir = new File(dataDir, "app");
2454            mAppLib32InstallDir = new File(dataDir, "app-lib");
2455            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2456            sUserManager = new UserManagerService(context, this,
2457                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2458
2459            // Propagate permission configuration in to package manager.
2460            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2461                    = systemConfig.getPermissions();
2462            for (int i=0; i<permConfig.size(); i++) {
2463                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2464                BasePermission bp = mSettings.mPermissions.get(perm.name);
2465                if (bp == null) {
2466                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2467                    mSettings.mPermissions.put(perm.name, bp);
2468                }
2469                if (perm.gids != null) {
2470                    bp.setGids(perm.gids, perm.perUser);
2471                }
2472            }
2473
2474            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2475            final int builtInLibCount = libConfig.size();
2476            for (int i = 0; i < builtInLibCount; i++) {
2477                String name = libConfig.keyAt(i);
2478                String path = libConfig.valueAt(i);
2479                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2480                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2481            }
2482
2483            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2484
2485            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2486            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2487            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2488
2489            // Clean up orphaned packages for which the code path doesn't exist
2490            // and they are an update to a system app - caused by bug/32321269
2491            final int packageSettingCount = mSettings.mPackages.size();
2492            for (int i = packageSettingCount - 1; i >= 0; i--) {
2493                PackageSetting ps = mSettings.mPackages.valueAt(i);
2494                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2495                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2496                    mSettings.mPackages.removeAt(i);
2497                    mSettings.enableSystemPackageLPw(ps.name);
2498                }
2499            }
2500
2501            if (mFirstBoot) {
2502                requestCopyPreoptedFiles();
2503            }
2504
2505            String customResolverActivity = Resources.getSystem().getString(
2506                    R.string.config_customResolverActivity);
2507            if (TextUtils.isEmpty(customResolverActivity)) {
2508                customResolverActivity = null;
2509            } else {
2510                mCustomResolverComponentName = ComponentName.unflattenFromString(
2511                        customResolverActivity);
2512            }
2513
2514            long startTime = SystemClock.uptimeMillis();
2515
2516            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2517                    startTime);
2518
2519            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2520            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2521
2522            if (bootClassPath == null) {
2523                Slog.w(TAG, "No BOOTCLASSPATH found!");
2524            }
2525
2526            if (systemServerClassPath == null) {
2527                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2528            }
2529
2530            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2531
2532            final VersionInfo ver = mSettings.getInternalVersion();
2533            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2534            if (mIsUpgrade) {
2535                logCriticalInfo(Log.INFO,
2536                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2537            }
2538
2539            // when upgrading from pre-M, promote system app permissions from install to runtime
2540            mPromoteSystemApps =
2541                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2542
2543            // When upgrading from pre-N, we need to handle package extraction like first boot,
2544            // as there is no profiling data available.
2545            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2546
2547            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2548
2549            // save off the names of pre-existing system packages prior to scanning; we don't
2550            // want to automatically grant runtime permissions for new system apps
2551            if (mPromoteSystemApps) {
2552                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2553                while (pkgSettingIter.hasNext()) {
2554                    PackageSetting ps = pkgSettingIter.next();
2555                    if (isSystemApp(ps)) {
2556                        mExistingSystemPackages.add(ps.name);
2557                    }
2558                }
2559            }
2560
2561            mCacheDir = preparePackageParserCache(mIsUpgrade);
2562
2563            // Set flag to monitor and not change apk file paths when
2564            // scanning install directories.
2565            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2566
2567            if (mIsUpgrade || mFirstBoot) {
2568                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2569            }
2570
2571            // Collect vendor overlay packages. (Do this before scanning any apps.)
2572            // For security and version matching reason, only consider
2573            // overlay packages if they reside in the right directory.
2574            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2575                    | PackageParser.PARSE_IS_SYSTEM
2576                    | PackageParser.PARSE_IS_SYSTEM_DIR
2577                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2578
2579            mParallelPackageParserCallback.findStaticOverlayPackages();
2580
2581            // Find base frameworks (resource packages without code).
2582            scanDirTracedLI(frameworkDir, mDefParseFlags
2583                    | PackageParser.PARSE_IS_SYSTEM
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR
2585                    | PackageParser.PARSE_IS_PRIVILEGED,
2586                    scanFlags | SCAN_NO_DEX, 0);
2587
2588            // Collected privileged system packages.
2589            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2590            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2591                    | PackageParser.PARSE_IS_SYSTEM
2592                    | PackageParser.PARSE_IS_SYSTEM_DIR
2593                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2594
2595            // Collect ordinary system packages.
2596            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2597            scanDirTracedLI(systemAppDir, mDefParseFlags
2598                    | PackageParser.PARSE_IS_SYSTEM
2599                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2600
2601            // Collect all vendor packages.
2602            File vendorAppDir = new File("/vendor/app");
2603            try {
2604                vendorAppDir = vendorAppDir.getCanonicalFile();
2605            } catch (IOException e) {
2606                // failed to look up canonical path, continue with original one
2607            }
2608            scanDirTracedLI(vendorAppDir, mDefParseFlags
2609                    | PackageParser.PARSE_IS_SYSTEM
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2611
2612            // Collect all OEM packages.
2613            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2614            scanDirTracedLI(oemAppDir, mDefParseFlags
2615                    | PackageParser.PARSE_IS_SYSTEM
2616                    | PackageParser.PARSE_IS_SYSTEM_DIR
2617                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2618
2619            // Prune any system packages that no longer exist.
2620            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2621            // Stub packages must either be replaced with full versions in the /data
2622            // partition or be disabled.
2623            final List<String> stubSystemApps = new ArrayList<>();
2624            if (!mOnlyCore) {
2625                // do this first before mucking with mPackages for the "expecting better" case
2626                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2627                while (pkgIterator.hasNext()) {
2628                    final PackageParser.Package pkg = pkgIterator.next();
2629                    if (pkg.isStub) {
2630                        stubSystemApps.add(pkg.packageName);
2631                    }
2632                }
2633
2634                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2635                while (psit.hasNext()) {
2636                    PackageSetting ps = psit.next();
2637
2638                    /*
2639                     * If this is not a system app, it can't be a
2640                     * disable system app.
2641                     */
2642                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2643                        continue;
2644                    }
2645
2646                    /*
2647                     * If the package is scanned, it's not erased.
2648                     */
2649                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2650                    if (scannedPkg != null) {
2651                        /*
2652                         * If the system app is both scanned and in the
2653                         * disabled packages list, then it must have been
2654                         * added via OTA. Remove it from the currently
2655                         * scanned package so the previously user-installed
2656                         * application can be scanned.
2657                         */
2658                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2659                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2660                                    + ps.name + "; removing system app.  Last known codePath="
2661                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2662                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2663                                    + scannedPkg.mVersionCode);
2664                            removePackageLI(scannedPkg, true);
2665                            mExpectingBetter.put(ps.name, ps.codePath);
2666                        }
2667
2668                        continue;
2669                    }
2670
2671                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2672                        psit.remove();
2673                        logCriticalInfo(Log.WARN, "System package " + ps.name
2674                                + " no longer exists; it's data will be wiped");
2675                        // Actual deletion of code and data will be handled by later
2676                        // reconciliation step
2677                    } else {
2678                        // we still have a disabled system package, but, it still might have
2679                        // been removed. check the code path still exists and check there's
2680                        // still a package. the latter can happen if an OTA keeps the same
2681                        // code path, but, changes the package name.
2682                        final PackageSetting disabledPs =
2683                                mSettings.getDisabledSystemPkgLPr(ps.name);
2684                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2685                                || disabledPs.pkg == null) {
2686                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2687                        }
2688                    }
2689                }
2690            }
2691
2692            //look for any incomplete package installations
2693            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2694            for (int i = 0; i < deletePkgsList.size(); i++) {
2695                // Actual deletion of code and data will be handled by later
2696                // reconciliation step
2697                final String packageName = deletePkgsList.get(i).name;
2698                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2699                synchronized (mPackages) {
2700                    mSettings.removePackageLPw(packageName);
2701                }
2702            }
2703
2704            //delete tmp files
2705            deleteTempPackageFiles();
2706
2707            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2708
2709            // Remove any shared userIDs that have no associated packages
2710            mSettings.pruneSharedUsersLPw();
2711            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2712            final int systemPackagesCount = mPackages.size();
2713            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2714                    + " ms, packageCount: " + systemPackagesCount
2715                    + " , timePerPackage: "
2716                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2717                    + " , cached: " + cachedSystemApps);
2718            if (mIsUpgrade && systemPackagesCount > 0) {
2719                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2720                        ((int) systemScanTime) / systemPackagesCount);
2721            }
2722            if (!mOnlyCore) {
2723                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2724                        SystemClock.uptimeMillis());
2725                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2726
2727                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2728                        | PackageParser.PARSE_FORWARD_LOCK,
2729                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2730
2731                // Remove disable package settings for updated system apps that were
2732                // removed via an OTA. If the update is no longer present, remove the
2733                // app completely. Otherwise, revoke their system privileges.
2734                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2735                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2736                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2737
2738                    final String msg;
2739                    if (deletedPkg == null) {
2740                        // should have found an update, but, we didn't; remove everything
2741                        msg = "Updated system package " + deletedAppName
2742                                + " no longer exists; removing its data";
2743                        // Actual deletion of code and data will be handled by later
2744                        // reconciliation step
2745                    } else {
2746                        // found an update; revoke system privileges
2747                        msg = "Updated system package + " + deletedAppName
2748                                + " no longer exists; revoking system privileges";
2749
2750                        // Don't do anything if a stub is removed from the system image. If
2751                        // we were to remove the uncompressed version from the /data partition,
2752                        // this is where it'd be done.
2753
2754                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2755                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2756                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2757                    }
2758                    logCriticalInfo(Log.WARN, msg);
2759                }
2760
2761                /*
2762                 * Make sure all system apps that we expected to appear on
2763                 * the userdata partition actually showed up. If they never
2764                 * appeared, crawl back and revive the system version.
2765                 */
2766                for (int i = 0; i < mExpectingBetter.size(); i++) {
2767                    final String packageName = mExpectingBetter.keyAt(i);
2768                    if (!mPackages.containsKey(packageName)) {
2769                        final File scanFile = mExpectingBetter.valueAt(i);
2770
2771                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2772                                + " but never showed up; reverting to system");
2773
2774                        int reparseFlags = mDefParseFlags;
2775                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2776                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2777                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2778                                    | PackageParser.PARSE_IS_PRIVILEGED;
2779                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2780                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2781                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2782                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2783                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2784                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2785                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2786                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2787                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2788                                    | PackageParser.PARSE_IS_OEM;
2789                        } else {
2790                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2791                            continue;
2792                        }
2793
2794                        mSettings.enableSystemPackageLPw(packageName);
2795
2796                        try {
2797                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2798                        } catch (PackageManagerException e) {
2799                            Slog.e(TAG, "Failed to parse original system package: "
2800                                    + e.getMessage());
2801                        }
2802                    }
2803                }
2804
2805                // Uncompress and install any stubbed system applications.
2806                // This must be done last to ensure all stubs are replaced or disabled.
2807                decompressSystemApplications(stubSystemApps, scanFlags);
2808
2809                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2810                                - cachedSystemApps;
2811
2812                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2813                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2814                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2815                        + " ms, packageCount: " + dataPackagesCount
2816                        + " , timePerPackage: "
2817                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2818                        + " , cached: " + cachedNonSystemApps);
2819                if (mIsUpgrade && dataPackagesCount > 0) {
2820                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2821                            ((int) dataScanTime) / dataPackagesCount);
2822                }
2823            }
2824            mExpectingBetter.clear();
2825
2826            // Resolve the storage manager.
2827            mStorageManagerPackage = getStorageManagerPackageName();
2828
2829            // Resolve protected action filters. Only the setup wizard is allowed to
2830            // have a high priority filter for these actions.
2831            mSetupWizardPackage = getSetupWizardPackageName();
2832            if (mProtectedFilters.size() > 0) {
2833                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2834                    Slog.i(TAG, "No setup wizard;"
2835                        + " All protected intents capped to priority 0");
2836                }
2837                for (ActivityIntentInfo filter : mProtectedFilters) {
2838                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2839                        if (DEBUG_FILTERS) {
2840                            Slog.i(TAG, "Found setup wizard;"
2841                                + " allow priority " + filter.getPriority() + ";"
2842                                + " package: " + filter.activity.info.packageName
2843                                + " activity: " + filter.activity.className
2844                                + " priority: " + filter.getPriority());
2845                        }
2846                        // skip setup wizard; allow it to keep the high priority filter
2847                        continue;
2848                    }
2849                    if (DEBUG_FILTERS) {
2850                        Slog.i(TAG, "Protected action; cap priority to 0;"
2851                                + " package: " + filter.activity.info.packageName
2852                                + " activity: " + filter.activity.className
2853                                + " origPrio: " + filter.getPriority());
2854                    }
2855                    filter.setPriority(0);
2856                }
2857            }
2858            mDeferProtectedFilters = false;
2859            mProtectedFilters.clear();
2860
2861            // Now that we know all of the shared libraries, update all clients to have
2862            // the correct library paths.
2863            updateAllSharedLibrariesLPw(null);
2864
2865            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2866                // NOTE: We ignore potential failures here during a system scan (like
2867                // the rest of the commands above) because there's precious little we
2868                // can do about it. A settings error is reported, though.
2869                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2870            }
2871
2872            // Now that we know all the packages we are keeping,
2873            // read and update their last usage times.
2874            mPackageUsage.read(mPackages);
2875            mCompilerStats.read();
2876
2877            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2878                    SystemClock.uptimeMillis());
2879            Slog.i(TAG, "Time to scan packages: "
2880                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2881                    + " seconds");
2882
2883            // If the platform SDK has changed since the last time we booted,
2884            // we need to re-grant app permission to catch any new ones that
2885            // appear.  This is really a hack, and means that apps can in some
2886            // cases get permissions that the user didn't initially explicitly
2887            // allow...  it would be nice to have some better way to handle
2888            // this situation.
2889            int updateFlags = UPDATE_PERMISSIONS_ALL;
2890            if (ver.sdkVersion != mSdkVersion) {
2891                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2892                        + mSdkVersion + "; regranting permissions for internal storage");
2893                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2894            }
2895            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2896            ver.sdkVersion = mSdkVersion;
2897
2898            // If this is the first boot or an update from pre-M, and it is a normal
2899            // boot, then we need to initialize the default preferred apps across
2900            // all defined users.
2901            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2902                for (UserInfo user : sUserManager.getUsers(true)) {
2903                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2904                    applyFactoryDefaultBrowserLPw(user.id);
2905                    primeDomainVerificationsLPw(user.id);
2906                }
2907            }
2908
2909            // Prepare storage for system user really early during boot,
2910            // since core system apps like SettingsProvider and SystemUI
2911            // can't wait for user to start
2912            final int storageFlags;
2913            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2914                storageFlags = StorageManager.FLAG_STORAGE_DE;
2915            } else {
2916                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2917            }
2918            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2919                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2920                    true /* onlyCoreApps */);
2921            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2922                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2923                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2924                traceLog.traceBegin("AppDataFixup");
2925                try {
2926                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2927                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2928                } catch (InstallerException e) {
2929                    Slog.w(TAG, "Trouble fixing GIDs", e);
2930                }
2931                traceLog.traceEnd();
2932
2933                traceLog.traceBegin("AppDataPrepare");
2934                if (deferPackages == null || deferPackages.isEmpty()) {
2935                    return;
2936                }
2937                int count = 0;
2938                for (String pkgName : deferPackages) {
2939                    PackageParser.Package pkg = null;
2940                    synchronized (mPackages) {
2941                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2942                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2943                            pkg = ps.pkg;
2944                        }
2945                    }
2946                    if (pkg != null) {
2947                        synchronized (mInstallLock) {
2948                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2949                                    true /* maybeMigrateAppData */);
2950                        }
2951                        count++;
2952                    }
2953                }
2954                traceLog.traceEnd();
2955                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2956            }, "prepareAppData");
2957
2958            // If this is first boot after an OTA, and a normal boot, then
2959            // we need to clear code cache directories.
2960            // Note that we do *not* clear the application profiles. These remain valid
2961            // across OTAs and are used to drive profile verification (post OTA) and
2962            // profile compilation (without waiting to collect a fresh set of profiles).
2963            if (mIsUpgrade && !onlyCore) {
2964                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2965                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2966                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2967                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2968                        // No apps are running this early, so no need to freeze
2969                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2970                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2971                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2972                    }
2973                }
2974                ver.fingerprint = Build.FINGERPRINT;
2975            }
2976
2977            checkDefaultBrowser();
2978
2979            // clear only after permissions and other defaults have been updated
2980            mExistingSystemPackages.clear();
2981            mPromoteSystemApps = false;
2982
2983            // All the changes are done during package scanning.
2984            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2985
2986            // can downgrade to reader
2987            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2988            mSettings.writeLPr();
2989            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2990            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2991                    SystemClock.uptimeMillis());
2992
2993            if (!mOnlyCore) {
2994                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2995                mRequiredInstallerPackage = getRequiredInstallerLPr();
2996                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2997                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2998                if (mIntentFilterVerifierComponent != null) {
2999                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3000                            mIntentFilterVerifierComponent);
3001                } else {
3002                    mIntentFilterVerifier = null;
3003                }
3004                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3005                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3006                        SharedLibraryInfo.VERSION_UNDEFINED);
3007                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3008                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3009                        SharedLibraryInfo.VERSION_UNDEFINED);
3010            } else {
3011                mRequiredVerifierPackage = null;
3012                mRequiredInstallerPackage = null;
3013                mRequiredUninstallerPackage = null;
3014                mIntentFilterVerifierComponent = null;
3015                mIntentFilterVerifier = null;
3016                mServicesSystemSharedLibraryPackageName = null;
3017                mSharedSystemSharedLibraryPackageName = null;
3018            }
3019
3020            mInstallerService = new PackageInstallerService(context, this);
3021            final Pair<ComponentName, String> instantAppResolverComponent =
3022                    getInstantAppResolverLPr();
3023            if (instantAppResolverComponent != null) {
3024                if (DEBUG_EPHEMERAL) {
3025                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3026                }
3027                mInstantAppResolverConnection = new EphemeralResolverConnection(
3028                        mContext, instantAppResolverComponent.first,
3029                        instantAppResolverComponent.second);
3030                mInstantAppResolverSettingsComponent =
3031                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3032            } else {
3033                mInstantAppResolverConnection = null;
3034                mInstantAppResolverSettingsComponent = null;
3035            }
3036            updateInstantAppInstallerLocked(null);
3037
3038            // Read and update the usage of dex files.
3039            // Do this at the end of PM init so that all the packages have their
3040            // data directory reconciled.
3041            // At this point we know the code paths of the packages, so we can validate
3042            // the disk file and build the internal cache.
3043            // The usage file is expected to be small so loading and verifying it
3044            // should take a fairly small time compare to the other activities (e.g. package
3045            // scanning).
3046            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3047            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3048            for (int userId : currentUserIds) {
3049                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3050            }
3051            mDexManager.load(userPackages);
3052            if (mIsUpgrade) {
3053                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3054                        (int) (SystemClock.uptimeMillis() - startTime));
3055            }
3056        } // synchronized (mPackages)
3057        } // synchronized (mInstallLock)
3058
3059        // Now after opening every single application zip, make sure they
3060        // are all flushed.  Not really needed, but keeps things nice and
3061        // tidy.
3062        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3063        Runtime.getRuntime().gc();
3064        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3065
3066        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3067        FallbackCategoryProvider.loadFallbacks();
3068        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3069
3070        // The initial scanning above does many calls into installd while
3071        // holding the mPackages lock, but we're mostly interested in yelling
3072        // once we have a booted system.
3073        mInstaller.setWarnIfHeld(mPackages);
3074
3075        // Expose private service for system components to use.
3076        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3077        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3078    }
3079
3080    /**
3081     * Uncompress and install stub applications.
3082     * <p>In order to save space on the system partition, some applications are shipped in a
3083     * compressed form. In addition the compressed bits for the full application, the
3084     * system image contains a tiny stub comprised of only the Android manifest.
3085     * <p>During the first boot, attempt to uncompress and install the full application. If
3086     * the application can't be installed for any reason, disable the stub and prevent
3087     * uncompressing the full application during future boots.
3088     * <p>In order to forcefully attempt an installation of a full application, go to app
3089     * settings and enable the application.
3090     */
3091    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3092        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3093            final String pkgName = stubSystemApps.get(i);
3094            // skip if the system package is already disabled
3095            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3096                stubSystemApps.remove(i);
3097                continue;
3098            }
3099            // skip if the package isn't installed (?!); this should never happen
3100            final PackageParser.Package pkg = mPackages.get(pkgName);
3101            if (pkg == null) {
3102                stubSystemApps.remove(i);
3103                continue;
3104            }
3105            // skip if the package has been disabled by the user
3106            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3107            if (ps != null) {
3108                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3109                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3110                    stubSystemApps.remove(i);
3111                    continue;
3112                }
3113            }
3114
3115            if (DEBUG_COMPRESSION) {
3116                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3117            }
3118
3119            // uncompress the binary to its eventual destination on /data
3120            final File scanFile = decompressPackage(pkg);
3121            if (scanFile == null) {
3122                continue;
3123            }
3124
3125            // install the package to replace the stub on /system
3126            try {
3127                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3128                removePackageLI(pkg, true /*chatty*/);
3129                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3130                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3131                        UserHandle.USER_SYSTEM, "android");
3132                stubSystemApps.remove(i);
3133                continue;
3134            } catch (PackageManagerException e) {
3135                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3136            }
3137
3138            // any failed attempt to install the package will be cleaned up later
3139        }
3140
3141        // disable any stub still left; these failed to install the full application
3142        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3143            final String pkgName = stubSystemApps.get(i);
3144            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3145            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3146                    UserHandle.USER_SYSTEM, "android");
3147            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3148        }
3149    }
3150
3151    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3152        if (DEBUG_COMPRESSION) {
3153            Slog.i(TAG, "Decompress file"
3154                    + "; src: " + srcFile.getAbsolutePath()
3155                    + ", dst: " + dstFile.getAbsolutePath());
3156        }
3157        try (
3158                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3159                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3160        ) {
3161            Streams.copy(fileIn, fileOut);
3162            Os.chmod(dstFile.getAbsolutePath(), 0644);
3163            return PackageManager.INSTALL_SUCCEEDED;
3164        } catch (IOException e) {
3165            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3166                    + "; src: " + srcFile.getAbsolutePath()
3167                    + ", dst: " + dstFile.getAbsolutePath());
3168        }
3169        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3170    }
3171
3172    private File[] getCompressedFiles(String codePath) {
3173        final File stubCodePath = new File(codePath);
3174        final String stubName = stubCodePath.getName();
3175
3176        // The layout of a compressed package on a given partition is as follows :
3177        //
3178        // Compressed artifacts:
3179        //
3180        // /partition/ModuleName/foo.gz
3181        // /partation/ModuleName/bar.gz
3182        //
3183        // Stub artifact:
3184        //
3185        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3186        //
3187        // In other words, stub is on the same partition as the compressed artifacts
3188        // and in a directory that's suffixed with "-Stub".
3189        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3190        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3191            return null;
3192        }
3193
3194        final File stubParentDir = stubCodePath.getParentFile();
3195        if (stubParentDir == null) {
3196            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3197            return null;
3198        }
3199
3200        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3201        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3202            @Override
3203            public boolean accept(File dir, String name) {
3204                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3205            }
3206        });
3207
3208        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3209            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3210        }
3211
3212        return files;
3213    }
3214
3215    private boolean compressedFileExists(String codePath) {
3216        final File[] compressedFiles = getCompressedFiles(codePath);
3217        return compressedFiles != null && compressedFiles.length > 0;
3218    }
3219
3220    /**
3221     * Decompresses the given package on the system image onto
3222     * the /data partition.
3223     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3224     */
3225    private File decompressPackage(PackageParser.Package pkg) {
3226        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3227        if (compressedFiles == null || compressedFiles.length == 0) {
3228            if (DEBUG_COMPRESSION) {
3229                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3230            }
3231            return null;
3232        }
3233        final File dstCodePath =
3234                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3235        int ret = PackageManager.INSTALL_SUCCEEDED;
3236        try {
3237            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3238            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3239            for (File srcFile : compressedFiles) {
3240                final String srcFileName = srcFile.getName();
3241                final String dstFileName = srcFileName.substring(
3242                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3243                final File dstFile = new File(dstCodePath, dstFileName);
3244                ret = decompressFile(srcFile, dstFile);
3245                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3246                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3247                            + "; pkg: " + pkg.packageName
3248                            + ", file: " + dstFileName);
3249                    break;
3250                }
3251            }
3252        } catch (ErrnoException e) {
3253            logCriticalInfo(Log.ERROR, "Failed to decompress"
3254                    + "; pkg: " + pkg.packageName
3255                    + ", err: " + e.errno);
3256        }
3257        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3258            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3259            NativeLibraryHelper.Handle handle = null;
3260            try {
3261                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3262                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3263                        null /*abiOverride*/);
3264            } catch (IOException e) {
3265                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3266                        + "; pkg: " + pkg.packageName);
3267                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3268            } finally {
3269                IoUtils.closeQuietly(handle);
3270            }
3271        }
3272        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3273            if (dstCodePath == null || !dstCodePath.exists()) {
3274                return null;
3275            }
3276            removeCodePathLI(dstCodePath);
3277            return null;
3278        }
3279
3280        // If we have a profile for a compressed APK, copy it to the reference location.
3281        // Since the package is the stub one, remove the stub suffix to get the normal package and
3282        // APK name.
3283        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3284        if (profileFile.exists()) {
3285            try {
3286                // We could also do this lazily before calling dexopt in
3287                // PackageDexOptimizer to prevent this happening on first boot. The issue
3288                // is that we don't have a good way to say "do this only once".
3289                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3290                        pkg.applicationInfo.uid, pkg.packageName)) {
3291                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3292                }
3293            } catch (Exception e) {
3294                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3295            }
3296        }
3297        return dstCodePath;
3298    }
3299
3300    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3301        // we're only interested in updating the installer appliction when 1) it's not
3302        // already set or 2) the modified package is the installer
3303        if (mInstantAppInstallerActivity != null
3304                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3305                        .equals(modifiedPackage)) {
3306            return;
3307        }
3308        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3309    }
3310
3311    private static File preparePackageParserCache(boolean isUpgrade) {
3312        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3313            return null;
3314        }
3315
3316        // Disable package parsing on eng builds to allow for faster incremental development.
3317        if (Build.IS_ENG) {
3318            return null;
3319        }
3320
3321        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3322            Slog.i(TAG, "Disabling package parser cache due to system property.");
3323            return null;
3324        }
3325
3326        // The base directory for the package parser cache lives under /data/system/.
3327        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3328                "package_cache");
3329        if (cacheBaseDir == null) {
3330            return null;
3331        }
3332
3333        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3334        // This also serves to "GC" unused entries when the package cache version changes (which
3335        // can only happen during upgrades).
3336        if (isUpgrade) {
3337            FileUtils.deleteContents(cacheBaseDir);
3338        }
3339
3340
3341        // Return the versioned package cache directory. This is something like
3342        // "/data/system/package_cache/1"
3343        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3344
3345        // The following is a workaround to aid development on non-numbered userdebug
3346        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3347        // the system partition is newer.
3348        //
3349        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3350        // that starts with "eng." to signify that this is an engineering build and not
3351        // destined for release.
3352        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3353            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3354
3355            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3356            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3357            // in general and should not be used for production changes. In this specific case,
3358            // we know that they will work.
3359            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3360            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3361                FileUtils.deleteContents(cacheBaseDir);
3362                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3363            }
3364        }
3365
3366        return cacheDir;
3367    }
3368
3369    @Override
3370    public boolean isFirstBoot() {
3371        // allow instant applications
3372        return mFirstBoot;
3373    }
3374
3375    @Override
3376    public boolean isOnlyCoreApps() {
3377        // allow instant applications
3378        return mOnlyCore;
3379    }
3380
3381    @Override
3382    public boolean isUpgrade() {
3383        // allow instant applications
3384        // The system property allows testing ota flow when upgraded to the same image.
3385        return mIsUpgrade || SystemProperties.getBoolean(
3386                "persist.pm.mock-upgrade", false /* default */);
3387    }
3388
3389    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3390        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3391
3392        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3393                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3394                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3395        if (matches.size() == 1) {
3396            return matches.get(0).getComponentInfo().packageName;
3397        } else if (matches.size() == 0) {
3398            Log.e(TAG, "There should probably be a verifier, but, none were found");
3399            return null;
3400        }
3401        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3402    }
3403
3404    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3405        synchronized (mPackages) {
3406            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3407            if (libraryEntry == null) {
3408                throw new IllegalStateException("Missing required shared library:" + name);
3409            }
3410            return libraryEntry.apk;
3411        }
3412    }
3413
3414    private @NonNull String getRequiredInstallerLPr() {
3415        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3416        intent.addCategory(Intent.CATEGORY_DEFAULT);
3417        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3418
3419        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM);
3422        if (matches.size() == 1) {
3423            ResolveInfo resolveInfo = matches.get(0);
3424            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3425                throw new RuntimeException("The installer must be a privileged app");
3426            }
3427            return matches.get(0).getComponentInfo().packageName;
3428        } else {
3429            throw new RuntimeException("There must be exactly one installer; found " + matches);
3430        }
3431    }
3432
3433    private @NonNull String getRequiredUninstallerLPr() {
3434        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3435        intent.addCategory(Intent.CATEGORY_DEFAULT);
3436        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3437
3438        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3439                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3440                UserHandle.USER_SYSTEM);
3441        if (resolveInfo == null ||
3442                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3443            throw new RuntimeException("There must be exactly one uninstaller; found "
3444                    + resolveInfo);
3445        }
3446        return resolveInfo.getComponentInfo().packageName;
3447    }
3448
3449    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3450        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3451
3452        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3453                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3454                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3455        ResolveInfo best = null;
3456        final int N = matches.size();
3457        for (int i = 0; i < N; i++) {
3458            final ResolveInfo cur = matches.get(i);
3459            final String packageName = cur.getComponentInfo().packageName;
3460            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3461                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3462                continue;
3463            }
3464
3465            if (best == null || cur.priority > best.priority) {
3466                best = cur;
3467            }
3468        }
3469
3470        if (best != null) {
3471            return best.getComponentInfo().getComponentName();
3472        }
3473        Slog.w(TAG, "Intent filter verifier not found");
3474        return null;
3475    }
3476
3477    @Override
3478    public @Nullable ComponentName getInstantAppResolverComponent() {
3479        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3480            return null;
3481        }
3482        synchronized (mPackages) {
3483            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3484            if (instantAppResolver == null) {
3485                return null;
3486            }
3487            return instantAppResolver.first;
3488        }
3489    }
3490
3491    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3492        final String[] packageArray =
3493                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3494        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3495            if (DEBUG_EPHEMERAL) {
3496                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3497            }
3498            return null;
3499        }
3500
3501        final int callingUid = Binder.getCallingUid();
3502        final int resolveFlags =
3503                MATCH_DIRECT_BOOT_AWARE
3504                | MATCH_DIRECT_BOOT_UNAWARE
3505                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3506        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3507        final Intent resolverIntent = new Intent(actionName);
3508        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3509                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3510        // temporarily look for the old action
3511        if (resolvers.size() == 0) {
3512            if (DEBUG_EPHEMERAL) {
3513                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3514            }
3515            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3516            resolverIntent.setAction(actionName);
3517            resolvers = queryIntentServicesInternal(resolverIntent, null,
3518                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3519        }
3520        final int N = resolvers.size();
3521        if (N == 0) {
3522            if (DEBUG_EPHEMERAL) {
3523                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3524            }
3525            return null;
3526        }
3527
3528        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3529        for (int i = 0; i < N; i++) {
3530            final ResolveInfo info = resolvers.get(i);
3531
3532            if (info.serviceInfo == null) {
3533                continue;
3534            }
3535
3536            final String packageName = info.serviceInfo.packageName;
3537            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3538                if (DEBUG_EPHEMERAL) {
3539                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3540                            + " pkg: " + packageName + ", info:" + info);
3541                }
3542                continue;
3543            }
3544
3545            if (DEBUG_EPHEMERAL) {
3546                Slog.v(TAG, "Ephemeral resolver found;"
3547                        + " pkg: " + packageName + ", info:" + info);
3548            }
3549            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3550        }
3551        if (DEBUG_EPHEMERAL) {
3552            Slog.v(TAG, "Ephemeral resolver NOT found");
3553        }
3554        return null;
3555    }
3556
3557    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3558        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3559        intent.addCategory(Intent.CATEGORY_DEFAULT);
3560        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3561
3562        final int resolveFlags =
3563                MATCH_DIRECT_BOOT_AWARE
3564                | MATCH_DIRECT_BOOT_UNAWARE
3565                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3566        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3567                resolveFlags, UserHandle.USER_SYSTEM);
3568        // temporarily look for the old action
3569        if (matches.isEmpty()) {
3570            if (DEBUG_EPHEMERAL) {
3571                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3572            }
3573            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3574            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3575                    resolveFlags, UserHandle.USER_SYSTEM);
3576        }
3577        Iterator<ResolveInfo> iter = matches.iterator();
3578        while (iter.hasNext()) {
3579            final ResolveInfo rInfo = iter.next();
3580            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3581            if (ps != null) {
3582                final PermissionsState permissionsState = ps.getPermissionsState();
3583                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3584                    continue;
3585                }
3586            }
3587            iter.remove();
3588        }
3589        if (matches.size() == 0) {
3590            return null;
3591        } else if (matches.size() == 1) {
3592            return (ActivityInfo) matches.get(0).getComponentInfo();
3593        } else {
3594            throw new RuntimeException(
3595                    "There must be at most one ephemeral installer; found " + matches);
3596        }
3597    }
3598
3599    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3600            @NonNull ComponentName resolver) {
3601        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3602                .addCategory(Intent.CATEGORY_DEFAULT)
3603                .setPackage(resolver.getPackageName());
3604        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3605        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3606                UserHandle.USER_SYSTEM);
3607        // temporarily look for the old action
3608        if (matches.isEmpty()) {
3609            if (DEBUG_EPHEMERAL) {
3610                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3611            }
3612            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3613            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3614                    UserHandle.USER_SYSTEM);
3615        }
3616        if (matches.isEmpty()) {
3617            return null;
3618        }
3619        return matches.get(0).getComponentInfo().getComponentName();
3620    }
3621
3622    private void primeDomainVerificationsLPw(int userId) {
3623        if (DEBUG_DOMAIN_VERIFICATION) {
3624            Slog.d(TAG, "Priming domain verifications in user " + userId);
3625        }
3626
3627        SystemConfig systemConfig = SystemConfig.getInstance();
3628        ArraySet<String> packages = systemConfig.getLinkedApps();
3629
3630        for (String packageName : packages) {
3631            PackageParser.Package pkg = mPackages.get(packageName);
3632            if (pkg != null) {
3633                if (!pkg.isSystemApp()) {
3634                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3635                    continue;
3636                }
3637
3638                ArraySet<String> domains = null;
3639                for (PackageParser.Activity a : pkg.activities) {
3640                    for (ActivityIntentInfo filter : a.intents) {
3641                        if (hasValidDomains(filter)) {
3642                            if (domains == null) {
3643                                domains = new ArraySet<String>();
3644                            }
3645                            domains.addAll(filter.getHostsList());
3646                        }
3647                    }
3648                }
3649
3650                if (domains != null && domains.size() > 0) {
3651                    if (DEBUG_DOMAIN_VERIFICATION) {
3652                        Slog.v(TAG, "      + " + packageName);
3653                    }
3654                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3655                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3656                    // and then 'always' in the per-user state actually used for intent resolution.
3657                    final IntentFilterVerificationInfo ivi;
3658                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3659                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3660                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3661                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3662                } else {
3663                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3664                            + "' does not handle web links");
3665                }
3666            } else {
3667                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3668            }
3669        }
3670
3671        scheduleWritePackageRestrictionsLocked(userId);
3672        scheduleWriteSettingsLocked();
3673    }
3674
3675    private void applyFactoryDefaultBrowserLPw(int userId) {
3676        // The default browser app's package name is stored in a string resource,
3677        // with a product-specific overlay used for vendor customization.
3678        String browserPkg = mContext.getResources().getString(
3679                com.android.internal.R.string.default_browser);
3680        if (!TextUtils.isEmpty(browserPkg)) {
3681            // non-empty string => required to be a known package
3682            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3683            if (ps == null) {
3684                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3685                browserPkg = null;
3686            } else {
3687                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3688            }
3689        }
3690
3691        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3692        // default.  If there's more than one, just leave everything alone.
3693        if (browserPkg == null) {
3694            calculateDefaultBrowserLPw(userId);
3695        }
3696    }
3697
3698    private void calculateDefaultBrowserLPw(int userId) {
3699        List<String> allBrowsers = resolveAllBrowserApps(userId);
3700        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3701        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3702    }
3703
3704    private List<String> resolveAllBrowserApps(int userId) {
3705        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3706        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3707                PackageManager.MATCH_ALL, userId);
3708
3709        final int count = list.size();
3710        List<String> result = new ArrayList<String>(count);
3711        for (int i=0; i<count; i++) {
3712            ResolveInfo info = list.get(i);
3713            if (info.activityInfo == null
3714                    || !info.handleAllWebDataURI
3715                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3716                    || result.contains(info.activityInfo.packageName)) {
3717                continue;
3718            }
3719            result.add(info.activityInfo.packageName);
3720        }
3721
3722        return result;
3723    }
3724
3725    private boolean packageIsBrowser(String packageName, int userId) {
3726        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3727                PackageManager.MATCH_ALL, userId);
3728        final int N = list.size();
3729        for (int i = 0; i < N; i++) {
3730            ResolveInfo info = list.get(i);
3731            if (packageName.equals(info.activityInfo.packageName)) {
3732                return true;
3733            }
3734        }
3735        return false;
3736    }
3737
3738    private void checkDefaultBrowser() {
3739        final int myUserId = UserHandle.myUserId();
3740        final String packageName = getDefaultBrowserPackageName(myUserId);
3741        if (packageName != null) {
3742            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3743            if (info == null) {
3744                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3745                synchronized (mPackages) {
3746                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3747                }
3748            }
3749        }
3750    }
3751
3752    @Override
3753    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3754            throws RemoteException {
3755        try {
3756            return super.onTransact(code, data, reply, flags);
3757        } catch (RuntimeException e) {
3758            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3759                Slog.wtf(TAG, "Package Manager Crash", e);
3760            }
3761            throw e;
3762        }
3763    }
3764
3765    static int[] appendInts(int[] cur, int[] add) {
3766        if (add == null) return cur;
3767        if (cur == null) return add;
3768        final int N = add.length;
3769        for (int i=0; i<N; i++) {
3770            cur = appendInt(cur, add[i]);
3771        }
3772        return cur;
3773    }
3774
3775    /**
3776     * Returns whether or not a full application can see an instant application.
3777     * <p>
3778     * Currently, there are three cases in which this can occur:
3779     * <ol>
3780     * <li>The calling application is a "special" process. The special
3781     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3782     *     and {@code 0}</li>
3783     * <li>The calling application has the permission
3784     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3785     * <li>The calling application is the default launcher on the
3786     *     system partition.</li>
3787     * </ol>
3788     */
3789    private boolean canViewInstantApps(int callingUid, int userId) {
3790        if (callingUid == Process.SYSTEM_UID
3791                || callingUid == Process.SHELL_UID
3792                || callingUid == Process.ROOT_UID) {
3793            return true;
3794        }
3795        if (mContext.checkCallingOrSelfPermission(
3796                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3797            return true;
3798        }
3799        if (mContext.checkCallingOrSelfPermission(
3800                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3801            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3802            if (homeComponent != null
3803                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3804                return true;
3805            }
3806        }
3807        return false;
3808    }
3809
3810    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3811        if (!sUserManager.exists(userId)) return null;
3812        if (ps == null) {
3813            return null;
3814        }
3815        PackageParser.Package p = ps.pkg;
3816        if (p == null) {
3817            return null;
3818        }
3819        final int callingUid = Binder.getCallingUid();
3820        // Filter out ephemeral app metadata:
3821        //   * The system/shell/root can see metadata for any app
3822        //   * An installed app can see metadata for 1) other installed apps
3823        //     and 2) ephemeral apps that have explicitly interacted with it
3824        //   * Ephemeral apps can only see their own data and exposed installed apps
3825        //   * Holding a signature permission allows seeing instant apps
3826        if (filterAppAccessLPr(ps, callingUid, userId)) {
3827            return null;
3828        }
3829
3830        final PermissionsState permissionsState = ps.getPermissionsState();
3831
3832        // Compute GIDs only if requested
3833        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3834                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3835        // Compute granted permissions only if package has requested permissions
3836        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3837                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3838        final PackageUserState state = ps.readUserState(userId);
3839
3840        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3841                && ps.isSystem()) {
3842            flags |= MATCH_ANY_USER;
3843        }
3844
3845        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3846                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3847
3848        if (packageInfo == null) {
3849            return null;
3850        }
3851
3852        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3853                resolveExternalPackageNameLPr(p);
3854
3855        return packageInfo;
3856    }
3857
3858    @Override
3859    public void checkPackageStartable(String packageName, int userId) {
3860        final int callingUid = Binder.getCallingUid();
3861        if (getInstantAppPackageName(callingUid) != null) {
3862            throw new SecurityException("Instant applications don't have access to this method");
3863        }
3864        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3865        synchronized (mPackages) {
3866            final PackageSetting ps = mSettings.mPackages.get(packageName);
3867            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3868                throw new SecurityException("Package " + packageName + " was not found!");
3869            }
3870
3871            if (!ps.getInstalled(userId)) {
3872                throw new SecurityException(
3873                        "Package " + packageName + " was not installed for user " + userId + "!");
3874            }
3875
3876            if (mSafeMode && !ps.isSystem()) {
3877                throw new SecurityException("Package " + packageName + " not a system app!");
3878            }
3879
3880            if (mFrozenPackages.contains(packageName)) {
3881                throw new SecurityException("Package " + packageName + " is currently frozen!");
3882            }
3883
3884            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3885                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3886            }
3887        }
3888    }
3889
3890    @Override
3891    public boolean isPackageAvailable(String packageName, int userId) {
3892        if (!sUserManager.exists(userId)) return false;
3893        final int callingUid = Binder.getCallingUid();
3894        enforceCrossUserPermission(callingUid, userId,
3895                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3896        synchronized (mPackages) {
3897            PackageParser.Package p = mPackages.get(packageName);
3898            if (p != null) {
3899                final PackageSetting ps = (PackageSetting) p.mExtras;
3900                if (filterAppAccessLPr(ps, callingUid, userId)) {
3901                    return false;
3902                }
3903                if (ps != null) {
3904                    final PackageUserState state = ps.readUserState(userId);
3905                    if (state != null) {
3906                        return PackageParser.isAvailable(state);
3907                    }
3908                }
3909            }
3910        }
3911        return false;
3912    }
3913
3914    @Override
3915    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3916        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3917                flags, Binder.getCallingUid(), userId);
3918    }
3919
3920    @Override
3921    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3922            int flags, int userId) {
3923        return getPackageInfoInternal(versionedPackage.getPackageName(),
3924                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3925    }
3926
3927    /**
3928     * Important: The provided filterCallingUid is used exclusively to filter out packages
3929     * that can be seen based on user state. It's typically the original caller uid prior
3930     * to clearing. Because it can only be provided by trusted code, it's value can be
3931     * trusted and will be used as-is; unlike userId which will be validated by this method.
3932     */
3933    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3934            int flags, int filterCallingUid, int userId) {
3935        if (!sUserManager.exists(userId)) return null;
3936        flags = updateFlagsForPackage(flags, userId, packageName);
3937        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3938                false /* requireFullPermission */, false /* checkShell */, "get package info");
3939
3940        // reader
3941        synchronized (mPackages) {
3942            // Normalize package name to handle renamed packages and static libs
3943            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3944
3945            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3946            if (matchFactoryOnly) {
3947                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3948                if (ps != null) {
3949                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3950                        return null;
3951                    }
3952                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3953                        return null;
3954                    }
3955                    return generatePackageInfo(ps, flags, userId);
3956                }
3957            }
3958
3959            PackageParser.Package p = mPackages.get(packageName);
3960            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3961                return null;
3962            }
3963            if (DEBUG_PACKAGE_INFO)
3964                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3965            if (p != null) {
3966                final PackageSetting ps = (PackageSetting) p.mExtras;
3967                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3968                    return null;
3969                }
3970                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3971                    return null;
3972                }
3973                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3974            }
3975            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3976                final PackageSetting ps = mSettings.mPackages.get(packageName);
3977                if (ps == null) return null;
3978                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3979                    return null;
3980                }
3981                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3982                    return null;
3983                }
3984                return generatePackageInfo(ps, flags, userId);
3985            }
3986        }
3987        return null;
3988    }
3989
3990    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3991        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3992            return true;
3993        }
3994        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3995            return true;
3996        }
3997        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3998            return true;
3999        }
4000        return false;
4001    }
4002
4003    private boolean isComponentVisibleToInstantApp(
4004            @Nullable ComponentName component, @ComponentType int type) {
4005        if (type == TYPE_ACTIVITY) {
4006            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4007            return activity != null
4008                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4009                    : false;
4010        } else if (type == TYPE_RECEIVER) {
4011            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4012            return activity != null
4013                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4014                    : false;
4015        } else if (type == TYPE_SERVICE) {
4016            final PackageParser.Service service = mServices.mServices.get(component);
4017            return service != null
4018                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4019                    : false;
4020        } else if (type == TYPE_PROVIDER) {
4021            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4022            return provider != null
4023                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4024                    : false;
4025        } else if (type == TYPE_UNKNOWN) {
4026            return isComponentVisibleToInstantApp(component);
4027        }
4028        return false;
4029    }
4030
4031    /**
4032     * Returns whether or not access to the application should be filtered.
4033     * <p>
4034     * Access may be limited based upon whether the calling or target applications
4035     * are instant applications.
4036     *
4037     * @see #canAccessInstantApps(int)
4038     */
4039    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4040            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4041        // if we're in an isolated process, get the real calling UID
4042        if (Process.isIsolated(callingUid)) {
4043            callingUid = mIsolatedOwners.get(callingUid);
4044        }
4045        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4046        final boolean callerIsInstantApp = instantAppPkgName != null;
4047        if (ps == null) {
4048            if (callerIsInstantApp) {
4049                // pretend the application exists, but, needs to be filtered
4050                return true;
4051            }
4052            return false;
4053        }
4054        // if the target and caller are the same application, don't filter
4055        if (isCallerSameApp(ps.name, callingUid)) {
4056            return false;
4057        }
4058        if (callerIsInstantApp) {
4059            // request for a specific component; if it hasn't been explicitly exposed, filter
4060            if (component != null) {
4061                return !isComponentVisibleToInstantApp(component, componentType);
4062            }
4063            // request for application; if no components have been explicitly exposed, filter
4064            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4065        }
4066        if (ps.getInstantApp(userId)) {
4067            // caller can see all components of all instant applications, don't filter
4068            if (canViewInstantApps(callingUid, userId)) {
4069                return false;
4070            }
4071            // request for a specific instant application component, filter
4072            if (component != null) {
4073                return true;
4074            }
4075            // request for an instant application; if the caller hasn't been granted access, filter
4076            return !mInstantAppRegistry.isInstantAccessGranted(
4077                    userId, UserHandle.getAppId(callingUid), ps.appId);
4078        }
4079        return false;
4080    }
4081
4082    /**
4083     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4084     */
4085    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4086        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4087    }
4088
4089    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4090            int flags) {
4091        // Callers can access only the libs they depend on, otherwise they need to explicitly
4092        // ask for the shared libraries given the caller is allowed to access all static libs.
4093        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4094            // System/shell/root get to see all static libs
4095            final int appId = UserHandle.getAppId(uid);
4096            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4097                    || appId == Process.ROOT_UID) {
4098                return false;
4099            }
4100        }
4101
4102        // No package means no static lib as it is always on internal storage
4103        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4104            return false;
4105        }
4106
4107        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4108                ps.pkg.staticSharedLibVersion);
4109        if (libEntry == null) {
4110            return false;
4111        }
4112
4113        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4114        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4115        if (uidPackageNames == null) {
4116            return true;
4117        }
4118
4119        for (String uidPackageName : uidPackageNames) {
4120            if (ps.name.equals(uidPackageName)) {
4121                return false;
4122            }
4123            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4124            if (uidPs != null) {
4125                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4126                        libEntry.info.getName());
4127                if (index < 0) {
4128                    continue;
4129                }
4130                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4131                    return false;
4132                }
4133            }
4134        }
4135        return true;
4136    }
4137
4138    @Override
4139    public String[] currentToCanonicalPackageNames(String[] names) {
4140        final int callingUid = Binder.getCallingUid();
4141        if (getInstantAppPackageName(callingUid) != null) {
4142            return names;
4143        }
4144        final String[] out = new String[names.length];
4145        // reader
4146        synchronized (mPackages) {
4147            final int callingUserId = UserHandle.getUserId(callingUid);
4148            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4149            for (int i=names.length-1; i>=0; i--) {
4150                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4151                boolean translateName = false;
4152                if (ps != null && ps.realName != null) {
4153                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4154                    translateName = !targetIsInstantApp
4155                            || canViewInstantApps
4156                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4157                                    UserHandle.getAppId(callingUid), ps.appId);
4158                }
4159                out[i] = translateName ? ps.realName : names[i];
4160            }
4161        }
4162        return out;
4163    }
4164
4165    @Override
4166    public String[] canonicalToCurrentPackageNames(String[] names) {
4167        final int callingUid = Binder.getCallingUid();
4168        if (getInstantAppPackageName(callingUid) != null) {
4169            return names;
4170        }
4171        final String[] out = new String[names.length];
4172        // reader
4173        synchronized (mPackages) {
4174            final int callingUserId = UserHandle.getUserId(callingUid);
4175            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4176            for (int i=names.length-1; i>=0; i--) {
4177                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4178                boolean translateName = false;
4179                if (cur != null) {
4180                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4181                    final boolean targetIsInstantApp =
4182                            ps != null && ps.getInstantApp(callingUserId);
4183                    translateName = !targetIsInstantApp
4184                            || canViewInstantApps
4185                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4186                                    UserHandle.getAppId(callingUid), ps.appId);
4187                }
4188                out[i] = translateName ? cur : names[i];
4189            }
4190        }
4191        return out;
4192    }
4193
4194    @Override
4195    public int getPackageUid(String packageName, int flags, int userId) {
4196        if (!sUserManager.exists(userId)) return -1;
4197        final int callingUid = Binder.getCallingUid();
4198        flags = updateFlagsForPackage(flags, userId, packageName);
4199        enforceCrossUserPermission(callingUid, userId,
4200                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4201
4202        // reader
4203        synchronized (mPackages) {
4204            final PackageParser.Package p = mPackages.get(packageName);
4205            if (p != null && p.isMatch(flags)) {
4206                PackageSetting ps = (PackageSetting) p.mExtras;
4207                if (filterAppAccessLPr(ps, callingUid, userId)) {
4208                    return -1;
4209                }
4210                return UserHandle.getUid(userId, p.applicationInfo.uid);
4211            }
4212            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4213                final PackageSetting ps = mSettings.mPackages.get(packageName);
4214                if (ps != null && ps.isMatch(flags)
4215                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4216                    return UserHandle.getUid(userId, ps.appId);
4217                }
4218            }
4219        }
4220
4221        return -1;
4222    }
4223
4224    @Override
4225    public int[] getPackageGids(String packageName, int flags, int userId) {
4226        if (!sUserManager.exists(userId)) return null;
4227        final int callingUid = Binder.getCallingUid();
4228        flags = updateFlagsForPackage(flags, userId, packageName);
4229        enforceCrossUserPermission(callingUid, userId,
4230                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4231
4232        // reader
4233        synchronized (mPackages) {
4234            final PackageParser.Package p = mPackages.get(packageName);
4235            if (p != null && p.isMatch(flags)) {
4236                PackageSetting ps = (PackageSetting) p.mExtras;
4237                if (filterAppAccessLPr(ps, callingUid, userId)) {
4238                    return null;
4239                }
4240                // TODO: Shouldn't this be checking for package installed state for userId and
4241                // return null?
4242                return ps.getPermissionsState().computeGids(userId);
4243            }
4244            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4245                final PackageSetting ps = mSettings.mPackages.get(packageName);
4246                if (ps != null && ps.isMatch(flags)
4247                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4248                    return ps.getPermissionsState().computeGids(userId);
4249                }
4250            }
4251        }
4252
4253        return null;
4254    }
4255
4256    @Override
4257    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4258        final int callingUid = Binder.getCallingUid();
4259        if (getInstantAppPackageName(callingUid) != null) {
4260            return null;
4261        }
4262        // reader
4263        synchronized (mPackages) {
4264            final BasePermission bp = mSettings.mPermissions.get(name);
4265            if (bp == null) {
4266                return null;
4267            }
4268            final int adjustedProtectionLevel = adjustPermissionProtectionFlagsLPr(
4269                    bp.getProtectionLevel(), packageName, callingUid);
4270            return bp.generatePermissionInfo(adjustedProtectionLevel, flags);
4271        }
4272    }
4273
4274    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4275            String packageName, int uid) {
4276        // Signature permission flags area always reported
4277        final int protectionLevelMasked = protectionLevel
4278                & (PermissionInfo.PROTECTION_NORMAL
4279                | PermissionInfo.PROTECTION_DANGEROUS
4280                | PermissionInfo.PROTECTION_SIGNATURE);
4281        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4282            return protectionLevel;
4283        }
4284
4285        // System sees all flags.
4286        final int appId = UserHandle.getAppId(uid);
4287        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4288                || appId == Process.SHELL_UID) {
4289            return protectionLevel;
4290        }
4291
4292        // Normalize package name to handle renamed packages and static libs
4293        packageName = resolveInternalPackageNameLPr(packageName,
4294                PackageManager.VERSION_CODE_HIGHEST);
4295
4296        // Apps that target O see flags for all protection levels.
4297        final PackageSetting ps = mSettings.mPackages.get(packageName);
4298        if (ps == null) {
4299            return protectionLevel;
4300        }
4301        if (ps.appId != appId) {
4302            return protectionLevel;
4303        }
4304
4305        final PackageParser.Package pkg = mPackages.get(packageName);
4306        if (pkg == null) {
4307            return protectionLevel;
4308        }
4309        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4310            return protectionLevelMasked;
4311        }
4312
4313        return protectionLevel;
4314    }
4315
4316    @Override
4317    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4318            int flags) {
4319        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4320            return null;
4321        }
4322        // reader
4323        synchronized (mPackages) {
4324            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4325                // This is thrown as NameNotFoundException
4326                return null;
4327            }
4328
4329            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4330            for (BasePermission bp : mSettings.mPermissions.values()) {
4331                final PermissionInfo pi = bp.generatePermissionInfo(groupName, flags);
4332                if (pi != null) {
4333                    out.add(pi);
4334                }
4335            }
4336            return new ParceledListSlice<>(out);
4337        }
4338    }
4339
4340    @Override
4341    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4342        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4343            return null;
4344        }
4345        // reader
4346        synchronized (mPackages) {
4347            return PackageParser.generatePermissionGroupInfo(
4348                    mPermissionGroups.get(name), flags);
4349        }
4350    }
4351
4352    @Override
4353    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4354        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4355            return ParceledListSlice.emptyList();
4356        }
4357        // reader
4358        synchronized (mPackages) {
4359            final int N = mPermissionGroups.size();
4360            ArrayList<PermissionGroupInfo> out
4361                    = new ArrayList<PermissionGroupInfo>(N);
4362            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4363                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4364            }
4365            return new ParceledListSlice<>(out);
4366        }
4367    }
4368
4369    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4370            int filterCallingUid, int userId) {
4371        if (!sUserManager.exists(userId)) return null;
4372        PackageSetting ps = mSettings.mPackages.get(packageName);
4373        if (ps != null) {
4374            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4375                return null;
4376            }
4377            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4378                return null;
4379            }
4380            if (ps.pkg == null) {
4381                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4382                if (pInfo != null) {
4383                    return pInfo.applicationInfo;
4384                }
4385                return null;
4386            }
4387            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4388                    ps.readUserState(userId), userId);
4389            if (ai != null) {
4390                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4391            }
4392            return ai;
4393        }
4394        return null;
4395    }
4396
4397    @Override
4398    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4399        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4400    }
4401
4402    /**
4403     * Important: The provided filterCallingUid is used exclusively to filter out applications
4404     * that can be seen based on user state. It's typically the original caller uid prior
4405     * to clearing. Because it can only be provided by trusted code, it's value can be
4406     * trusted and will be used as-is; unlike userId which will be validated by this method.
4407     */
4408    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4409            int filterCallingUid, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        flags = updateFlagsForApplication(flags, userId, packageName);
4412        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4413                false /* requireFullPermission */, false /* checkShell */, "get application info");
4414
4415        // writer
4416        synchronized (mPackages) {
4417            // Normalize package name to handle renamed packages and static libs
4418            packageName = resolveInternalPackageNameLPr(packageName,
4419                    PackageManager.VERSION_CODE_HIGHEST);
4420
4421            PackageParser.Package p = mPackages.get(packageName);
4422            if (DEBUG_PACKAGE_INFO) Log.v(
4423                    TAG, "getApplicationInfo " + packageName
4424                    + ": " + p);
4425            if (p != null) {
4426                PackageSetting ps = mSettings.mPackages.get(packageName);
4427                if (ps == null) return null;
4428                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4429                    return null;
4430                }
4431                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4432                    return null;
4433                }
4434                // Note: isEnabledLP() does not apply here - always return info
4435                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4436                        p, flags, ps.readUserState(userId), userId);
4437                if (ai != null) {
4438                    ai.packageName = resolveExternalPackageNameLPr(p);
4439                }
4440                return ai;
4441            }
4442            if ("android".equals(packageName)||"system".equals(packageName)) {
4443                return mAndroidApplication;
4444            }
4445            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4446                // Already generates the external package name
4447                return generateApplicationInfoFromSettingsLPw(packageName,
4448                        flags, filterCallingUid, userId);
4449            }
4450        }
4451        return null;
4452    }
4453
4454    private String normalizePackageNameLPr(String packageName) {
4455        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4456        return normalizedPackageName != null ? normalizedPackageName : packageName;
4457    }
4458
4459    @Override
4460    public void deletePreloadsFileCache() {
4461        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4462            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4463        }
4464        File dir = Environment.getDataPreloadsFileCacheDirectory();
4465        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4466        FileUtils.deleteContents(dir);
4467    }
4468
4469    @Override
4470    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4471            final int storageFlags, final IPackageDataObserver observer) {
4472        mContext.enforceCallingOrSelfPermission(
4473                android.Manifest.permission.CLEAR_APP_CACHE, null);
4474        mHandler.post(() -> {
4475            boolean success = false;
4476            try {
4477                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4478                success = true;
4479            } catch (IOException e) {
4480                Slog.w(TAG, e);
4481            }
4482            if (observer != null) {
4483                try {
4484                    observer.onRemoveCompleted(null, success);
4485                } catch (RemoteException e) {
4486                    Slog.w(TAG, e);
4487                }
4488            }
4489        });
4490    }
4491
4492    @Override
4493    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4494            final int storageFlags, final IntentSender pi) {
4495        mContext.enforceCallingOrSelfPermission(
4496                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4497        mHandler.post(() -> {
4498            boolean success = false;
4499            try {
4500                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4501                success = true;
4502            } catch (IOException e) {
4503                Slog.w(TAG, e);
4504            }
4505            if (pi != null) {
4506                try {
4507                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4508                } catch (SendIntentException e) {
4509                    Slog.w(TAG, e);
4510                }
4511            }
4512        });
4513    }
4514
4515    /**
4516     * Blocking call to clear various types of cached data across the system
4517     * until the requested bytes are available.
4518     */
4519    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4520        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4521        final File file = storage.findPathForUuid(volumeUuid);
4522        if (file.getUsableSpace() >= bytes) return;
4523
4524        if (ENABLE_FREE_CACHE_V2) {
4525            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4526                    volumeUuid);
4527            final boolean aggressive = (storageFlags
4528                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4529            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4530
4531            // 1. Pre-flight to determine if we have any chance to succeed
4532            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4533            if (internalVolume && (aggressive || SystemProperties
4534                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4535                deletePreloadsFileCache();
4536                if (file.getUsableSpace() >= bytes) return;
4537            }
4538
4539            // 3. Consider parsed APK data (aggressive only)
4540            if (internalVolume && aggressive) {
4541                FileUtils.deleteContents(mCacheDir);
4542                if (file.getUsableSpace() >= bytes) return;
4543            }
4544
4545            // 4. Consider cached app data (above quotas)
4546            try {
4547                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4548                        Installer.FLAG_FREE_CACHE_V2);
4549            } catch (InstallerException ignored) {
4550            }
4551            if (file.getUsableSpace() >= bytes) return;
4552
4553            // 5. Consider shared libraries with refcount=0 and age>min cache period
4554            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4555                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4556                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4557                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4558                return;
4559            }
4560
4561            // 6. Consider dexopt output (aggressive only)
4562            // TODO: Implement
4563
4564            // 7. Consider installed instant apps unused longer than min cache period
4565            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4566                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4567                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4568                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4569                return;
4570            }
4571
4572            // 8. Consider cached app data (below quotas)
4573            try {
4574                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4575                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4576            } catch (InstallerException ignored) {
4577            }
4578            if (file.getUsableSpace() >= bytes) return;
4579
4580            // 9. Consider DropBox entries
4581            // TODO: Implement
4582
4583            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4584            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4585                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4586                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4587                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4588                return;
4589            }
4590        } else {
4591            try {
4592                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4593            } catch (InstallerException ignored) {
4594            }
4595            if (file.getUsableSpace() >= bytes) return;
4596        }
4597
4598        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4599    }
4600
4601    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4602            throws IOException {
4603        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4604        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4605
4606        List<VersionedPackage> packagesToDelete = null;
4607        final long now = System.currentTimeMillis();
4608
4609        synchronized (mPackages) {
4610            final int[] allUsers = sUserManager.getUserIds();
4611            final int libCount = mSharedLibraries.size();
4612            for (int i = 0; i < libCount; i++) {
4613                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4614                if (versionedLib == null) {
4615                    continue;
4616                }
4617                final int versionCount = versionedLib.size();
4618                for (int j = 0; j < versionCount; j++) {
4619                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4620                    // Skip packages that are not static shared libs.
4621                    if (!libInfo.isStatic()) {
4622                        break;
4623                    }
4624                    // Important: We skip static shared libs used for some user since
4625                    // in such a case we need to keep the APK on the device. The check for
4626                    // a lib being used for any user is performed by the uninstall call.
4627                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4628                    // Resolve the package name - we use synthetic package names internally
4629                    final String internalPackageName = resolveInternalPackageNameLPr(
4630                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4631                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4632                    // Skip unused static shared libs cached less than the min period
4633                    // to prevent pruning a lib needed by a subsequently installed package.
4634                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4635                        continue;
4636                    }
4637                    if (packagesToDelete == null) {
4638                        packagesToDelete = new ArrayList<>();
4639                    }
4640                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4641                            declaringPackage.getVersionCode()));
4642                }
4643            }
4644        }
4645
4646        if (packagesToDelete != null) {
4647            final int packageCount = packagesToDelete.size();
4648            for (int i = 0; i < packageCount; i++) {
4649                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4650                // Delete the package synchronously (will fail of the lib used for any user).
4651                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4652                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4653                                == PackageManager.DELETE_SUCCEEDED) {
4654                    if (volume.getUsableSpace() >= neededSpace) {
4655                        return true;
4656                    }
4657                }
4658            }
4659        }
4660
4661        return false;
4662    }
4663
4664    /**
4665     * Update given flags based on encryption status of current user.
4666     */
4667    private int updateFlags(int flags, int userId) {
4668        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4669                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4670            // Caller expressed an explicit opinion about what encryption
4671            // aware/unaware components they want to see, so fall through and
4672            // give them what they want
4673        } else {
4674            // Caller expressed no opinion, so match based on user state
4675            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4676                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4677            } else {
4678                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4679            }
4680        }
4681        return flags;
4682    }
4683
4684    private UserManagerInternal getUserManagerInternal() {
4685        if (mUserManagerInternal == null) {
4686            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4687        }
4688        return mUserManagerInternal;
4689    }
4690
4691    private DeviceIdleController.LocalService getDeviceIdleController() {
4692        if (mDeviceIdleController == null) {
4693            mDeviceIdleController =
4694                    LocalServices.getService(DeviceIdleController.LocalService.class);
4695        }
4696        return mDeviceIdleController;
4697    }
4698
4699    /**
4700     * Update given flags when being used to request {@link PackageInfo}.
4701     */
4702    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4703        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4704        boolean triaged = true;
4705        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4706                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4707            // Caller is asking for component details, so they'd better be
4708            // asking for specific encryption matching behavior, or be triaged
4709            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4710                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4711                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4712                triaged = false;
4713            }
4714        }
4715        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4716                | PackageManager.MATCH_SYSTEM_ONLY
4717                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4718            triaged = false;
4719        }
4720        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4721            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4722                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4723                    + Debug.getCallers(5));
4724        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4725                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4726            // If the caller wants all packages and has a restricted profile associated with it,
4727            // then match all users. This is to make sure that launchers that need to access work
4728            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4729            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4730            flags |= PackageManager.MATCH_ANY_USER;
4731        }
4732        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4733            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4734                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4735        }
4736        return updateFlags(flags, userId);
4737    }
4738
4739    /**
4740     * Update given flags when being used to request {@link ApplicationInfo}.
4741     */
4742    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4743        return updateFlagsForPackage(flags, userId, cookie);
4744    }
4745
4746    /**
4747     * Update given flags when being used to request {@link ComponentInfo}.
4748     */
4749    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4750        if (cookie instanceof Intent) {
4751            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4752                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4753            }
4754        }
4755
4756        boolean triaged = true;
4757        // Caller is asking for component details, so they'd better be
4758        // asking for specific encryption matching behavior, or be triaged
4759        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4760                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4761                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4762            triaged = false;
4763        }
4764        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4765            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4766                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4767        }
4768
4769        return updateFlags(flags, userId);
4770    }
4771
4772    /**
4773     * Update given intent when being used to request {@link ResolveInfo}.
4774     */
4775    private Intent updateIntentForResolve(Intent intent) {
4776        if (intent.getSelector() != null) {
4777            intent = intent.getSelector();
4778        }
4779        if (DEBUG_PREFERRED) {
4780            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4781        }
4782        return intent;
4783    }
4784
4785    /**
4786     * Update given flags when being used to request {@link ResolveInfo}.
4787     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4788     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4789     * flag set. However, this flag is only honoured in three circumstances:
4790     * <ul>
4791     * <li>when called from a system process</li>
4792     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4793     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4794     * action and a {@code android.intent.category.BROWSABLE} category</li>
4795     * </ul>
4796     */
4797    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4798        return updateFlagsForResolve(flags, userId, intent, callingUid,
4799                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4800    }
4801    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4802            boolean wantInstantApps) {
4803        return updateFlagsForResolve(flags, userId, intent, callingUid,
4804                wantInstantApps, false /*onlyExposedExplicitly*/);
4805    }
4806    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4807            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4808        // Safe mode means we shouldn't match any third-party components
4809        if (mSafeMode) {
4810            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4811        }
4812        if (getInstantAppPackageName(callingUid) != null) {
4813            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4814            if (onlyExposedExplicitly) {
4815                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4816            }
4817            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4818            flags |= PackageManager.MATCH_INSTANT;
4819        } else {
4820            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4821            final boolean allowMatchInstant =
4822                    (wantInstantApps
4823                            && Intent.ACTION_VIEW.equals(intent.getAction())
4824                            && hasWebURI(intent))
4825                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4826            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4827                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4828            if (!allowMatchInstant) {
4829                flags &= ~PackageManager.MATCH_INSTANT;
4830            }
4831        }
4832        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4833    }
4834
4835    @Override
4836    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4837        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4838    }
4839
4840    /**
4841     * Important: The provided filterCallingUid is used exclusively to filter out activities
4842     * that can be seen based on user state. It's typically the original caller uid prior
4843     * to clearing. Because it can only be provided by trusted code, it's value can be
4844     * trusted and will be used as-is; unlike userId which will be validated by this method.
4845     */
4846    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4847            int filterCallingUid, int userId) {
4848        if (!sUserManager.exists(userId)) return null;
4849        flags = updateFlagsForComponent(flags, userId, component);
4850        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4851                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4852        synchronized (mPackages) {
4853            PackageParser.Activity a = mActivities.mActivities.get(component);
4854
4855            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4856            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4857                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4858                if (ps == null) return null;
4859                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4860                    return null;
4861                }
4862                return PackageParser.generateActivityInfo(
4863                        a, flags, ps.readUserState(userId), userId);
4864            }
4865            if (mResolveComponentName.equals(component)) {
4866                return PackageParser.generateActivityInfo(
4867                        mResolveActivity, flags, new PackageUserState(), userId);
4868            }
4869        }
4870        return null;
4871    }
4872
4873    @Override
4874    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4875            String resolvedType) {
4876        synchronized (mPackages) {
4877            if (component.equals(mResolveComponentName)) {
4878                // The resolver supports EVERYTHING!
4879                return true;
4880            }
4881            final int callingUid = Binder.getCallingUid();
4882            final int callingUserId = UserHandle.getUserId(callingUid);
4883            PackageParser.Activity a = mActivities.mActivities.get(component);
4884            if (a == null) {
4885                return false;
4886            }
4887            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4888            if (ps == null) {
4889                return false;
4890            }
4891            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4892                return false;
4893            }
4894            for (int i=0; i<a.intents.size(); i++) {
4895                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4896                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4897                    return true;
4898                }
4899            }
4900            return false;
4901        }
4902    }
4903
4904    @Override
4905    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4906        if (!sUserManager.exists(userId)) return null;
4907        final int callingUid = Binder.getCallingUid();
4908        flags = updateFlagsForComponent(flags, userId, component);
4909        enforceCrossUserPermission(callingUid, userId,
4910                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4911        synchronized (mPackages) {
4912            PackageParser.Activity a = mReceivers.mActivities.get(component);
4913            if (DEBUG_PACKAGE_INFO) Log.v(
4914                TAG, "getReceiverInfo " + component + ": " + a);
4915            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4916                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4917                if (ps == null) return null;
4918                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4919                    return null;
4920                }
4921                return PackageParser.generateActivityInfo(
4922                        a, flags, ps.readUserState(userId), userId);
4923            }
4924        }
4925        return null;
4926    }
4927
4928    @Override
4929    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4930            int flags, int userId) {
4931        if (!sUserManager.exists(userId)) return null;
4932        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4933        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4934            return null;
4935        }
4936
4937        flags = updateFlagsForPackage(flags, userId, null);
4938
4939        final boolean canSeeStaticLibraries =
4940                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4941                        == PERMISSION_GRANTED
4942                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4943                        == PERMISSION_GRANTED
4944                || canRequestPackageInstallsInternal(packageName,
4945                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4946                        false  /* throwIfPermNotDeclared*/)
4947                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4948                        == PERMISSION_GRANTED;
4949
4950        synchronized (mPackages) {
4951            List<SharedLibraryInfo> result = null;
4952
4953            final int libCount = mSharedLibraries.size();
4954            for (int i = 0; i < libCount; i++) {
4955                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4956                if (versionedLib == null) {
4957                    continue;
4958                }
4959
4960                final int versionCount = versionedLib.size();
4961                for (int j = 0; j < versionCount; j++) {
4962                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4963                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4964                        break;
4965                    }
4966                    final long identity = Binder.clearCallingIdentity();
4967                    try {
4968                        PackageInfo packageInfo = getPackageInfoVersioned(
4969                                libInfo.getDeclaringPackage(), flags
4970                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4971                        if (packageInfo == null) {
4972                            continue;
4973                        }
4974                    } finally {
4975                        Binder.restoreCallingIdentity(identity);
4976                    }
4977
4978                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4979                            libInfo.getVersion(), libInfo.getType(),
4980                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4981                            flags, userId));
4982
4983                    if (result == null) {
4984                        result = new ArrayList<>();
4985                    }
4986                    result.add(resLibInfo);
4987                }
4988            }
4989
4990            return result != null ? new ParceledListSlice<>(result) : null;
4991        }
4992    }
4993
4994    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4995            SharedLibraryInfo libInfo, int flags, int userId) {
4996        List<VersionedPackage> versionedPackages = null;
4997        final int packageCount = mSettings.mPackages.size();
4998        for (int i = 0; i < packageCount; i++) {
4999            PackageSetting ps = mSettings.mPackages.valueAt(i);
5000
5001            if (ps == null) {
5002                continue;
5003            }
5004
5005            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5006                continue;
5007            }
5008
5009            final String libName = libInfo.getName();
5010            if (libInfo.isStatic()) {
5011                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5012                if (libIdx < 0) {
5013                    continue;
5014                }
5015                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5016                    continue;
5017                }
5018                if (versionedPackages == null) {
5019                    versionedPackages = new ArrayList<>();
5020                }
5021                // If the dependent is a static shared lib, use the public package name
5022                String dependentPackageName = ps.name;
5023                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5024                    dependentPackageName = ps.pkg.manifestPackageName;
5025                }
5026                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5027            } else if (ps.pkg != null) {
5028                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5029                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5030                    if (versionedPackages == null) {
5031                        versionedPackages = new ArrayList<>();
5032                    }
5033                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5034                }
5035            }
5036        }
5037
5038        return versionedPackages;
5039    }
5040
5041    @Override
5042    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5043        if (!sUserManager.exists(userId)) return null;
5044        final int callingUid = Binder.getCallingUid();
5045        flags = updateFlagsForComponent(flags, userId, component);
5046        enforceCrossUserPermission(callingUid, userId,
5047                false /* requireFullPermission */, false /* checkShell */, "get service info");
5048        synchronized (mPackages) {
5049            PackageParser.Service s = mServices.mServices.get(component);
5050            if (DEBUG_PACKAGE_INFO) Log.v(
5051                TAG, "getServiceInfo " + component + ": " + s);
5052            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5053                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5054                if (ps == null) return null;
5055                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5056                    return null;
5057                }
5058                return PackageParser.generateServiceInfo(
5059                        s, flags, ps.readUserState(userId), userId);
5060            }
5061        }
5062        return null;
5063    }
5064
5065    @Override
5066    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5067        if (!sUserManager.exists(userId)) return null;
5068        final int callingUid = Binder.getCallingUid();
5069        flags = updateFlagsForComponent(flags, userId, component);
5070        enforceCrossUserPermission(callingUid, userId,
5071                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5072        synchronized (mPackages) {
5073            PackageParser.Provider p = mProviders.mProviders.get(component);
5074            if (DEBUG_PACKAGE_INFO) Log.v(
5075                TAG, "getProviderInfo " + component + ": " + p);
5076            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5077                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5078                if (ps == null) return null;
5079                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5080                    return null;
5081                }
5082                return PackageParser.generateProviderInfo(
5083                        p, flags, ps.readUserState(userId), userId);
5084            }
5085        }
5086        return null;
5087    }
5088
5089    @Override
5090    public String[] getSystemSharedLibraryNames() {
5091        // allow instant applications
5092        synchronized (mPackages) {
5093            Set<String> libs = null;
5094            final int libCount = mSharedLibraries.size();
5095            for (int i = 0; i < libCount; i++) {
5096                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5097                if (versionedLib == null) {
5098                    continue;
5099                }
5100                final int versionCount = versionedLib.size();
5101                for (int j = 0; j < versionCount; j++) {
5102                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5103                    if (!libEntry.info.isStatic()) {
5104                        if (libs == null) {
5105                            libs = new ArraySet<>();
5106                        }
5107                        libs.add(libEntry.info.getName());
5108                        break;
5109                    }
5110                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5111                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5112                            UserHandle.getUserId(Binder.getCallingUid()),
5113                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5114                        if (libs == null) {
5115                            libs = new ArraySet<>();
5116                        }
5117                        libs.add(libEntry.info.getName());
5118                        break;
5119                    }
5120                }
5121            }
5122
5123            if (libs != null) {
5124                String[] libsArray = new String[libs.size()];
5125                libs.toArray(libsArray);
5126                return libsArray;
5127            }
5128
5129            return null;
5130        }
5131    }
5132
5133    @Override
5134    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5135        // allow instant applications
5136        synchronized (mPackages) {
5137            return mServicesSystemSharedLibraryPackageName;
5138        }
5139    }
5140
5141    @Override
5142    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5143        // allow instant applications
5144        synchronized (mPackages) {
5145            return mSharedSystemSharedLibraryPackageName;
5146        }
5147    }
5148
5149    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5150        for (int i = userList.length - 1; i >= 0; --i) {
5151            final int userId = userList[i];
5152            // don't add instant app to the list of updates
5153            if (pkgSetting.getInstantApp(userId)) {
5154                continue;
5155            }
5156            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5157            if (changedPackages == null) {
5158                changedPackages = new SparseArray<>();
5159                mChangedPackages.put(userId, changedPackages);
5160            }
5161            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5162            if (sequenceNumbers == null) {
5163                sequenceNumbers = new HashMap<>();
5164                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5165            }
5166            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5167            if (sequenceNumber != null) {
5168                changedPackages.remove(sequenceNumber);
5169            }
5170            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5171            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5172        }
5173        mChangedPackagesSequenceNumber++;
5174    }
5175
5176    @Override
5177    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5178        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5179            return null;
5180        }
5181        synchronized (mPackages) {
5182            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5183                return null;
5184            }
5185            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5186            if (changedPackages == null) {
5187                return null;
5188            }
5189            final List<String> packageNames =
5190                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5191            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5192                final String packageName = changedPackages.get(i);
5193                if (packageName != null) {
5194                    packageNames.add(packageName);
5195                }
5196            }
5197            return packageNames.isEmpty()
5198                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5199        }
5200    }
5201
5202    @Override
5203    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5204        // allow instant applications
5205        ArrayList<FeatureInfo> res;
5206        synchronized (mAvailableFeatures) {
5207            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5208            res.addAll(mAvailableFeatures.values());
5209        }
5210        final FeatureInfo fi = new FeatureInfo();
5211        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5212                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5213        res.add(fi);
5214
5215        return new ParceledListSlice<>(res);
5216    }
5217
5218    @Override
5219    public boolean hasSystemFeature(String name, int version) {
5220        // allow instant applications
5221        synchronized (mAvailableFeatures) {
5222            final FeatureInfo feat = mAvailableFeatures.get(name);
5223            if (feat == null) {
5224                return false;
5225            } else {
5226                return feat.version >= version;
5227            }
5228        }
5229    }
5230
5231    @Override
5232    public int checkPermission(String permName, String pkgName, int userId) {
5233        if (!sUserManager.exists(userId)) {
5234            return PackageManager.PERMISSION_DENIED;
5235        }
5236        final int callingUid = Binder.getCallingUid();
5237
5238        synchronized (mPackages) {
5239            final PackageParser.Package p = mPackages.get(pkgName);
5240            if (p != null && p.mExtras != null) {
5241                final PackageSetting ps = (PackageSetting) p.mExtras;
5242                if (filterAppAccessLPr(ps, callingUid, userId)) {
5243                    return PackageManager.PERMISSION_DENIED;
5244                }
5245                final boolean instantApp = ps.getInstantApp(userId);
5246                final PermissionsState permissionsState = ps.getPermissionsState();
5247                if (permissionsState.hasPermission(permName, userId)) {
5248                    if (instantApp) {
5249                        BasePermission bp = mSettings.mPermissions.get(permName);
5250                        if (bp != null && bp.isInstant()) {
5251                            return PackageManager.PERMISSION_GRANTED;
5252                        }
5253                    } else {
5254                        return PackageManager.PERMISSION_GRANTED;
5255                    }
5256                }
5257                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5258                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5259                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5260                    return PackageManager.PERMISSION_GRANTED;
5261                }
5262            }
5263        }
5264
5265        return PackageManager.PERMISSION_DENIED;
5266    }
5267
5268    @Override
5269    public int checkUidPermission(String permName, int uid) {
5270        final int callingUid = Binder.getCallingUid();
5271        final int callingUserId = UserHandle.getUserId(callingUid);
5272        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5273        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5274        final int userId = UserHandle.getUserId(uid);
5275        if (!sUserManager.exists(userId)) {
5276            return PackageManager.PERMISSION_DENIED;
5277        }
5278
5279        synchronized (mPackages) {
5280            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5281            if (obj != null) {
5282                if (obj instanceof SharedUserSetting) {
5283                    if (isCallerInstantApp) {
5284                        return PackageManager.PERMISSION_DENIED;
5285                    }
5286                } else if (obj instanceof PackageSetting) {
5287                    final PackageSetting ps = (PackageSetting) obj;
5288                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5289                        return PackageManager.PERMISSION_DENIED;
5290                    }
5291                }
5292                final SettingBase settingBase = (SettingBase) obj;
5293                final PermissionsState permissionsState = settingBase.getPermissionsState();
5294                if (permissionsState.hasPermission(permName, userId)) {
5295                    if (isUidInstantApp) {
5296                        BasePermission bp = mSettings.mPermissions.get(permName);
5297                        if (bp != null && bp.isInstant()) {
5298                            return PackageManager.PERMISSION_GRANTED;
5299                        }
5300                    } else {
5301                        return PackageManager.PERMISSION_GRANTED;
5302                    }
5303                }
5304                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5305                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5306                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5307                    return PackageManager.PERMISSION_GRANTED;
5308                }
5309            } else {
5310                ArraySet<String> perms = mSystemPermissions.get(uid);
5311                if (perms != null) {
5312                    if (perms.contains(permName)) {
5313                        return PackageManager.PERMISSION_GRANTED;
5314                    }
5315                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5316                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5317                        return PackageManager.PERMISSION_GRANTED;
5318                    }
5319                }
5320            }
5321        }
5322
5323        return PackageManager.PERMISSION_DENIED;
5324    }
5325
5326    @Override
5327    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5328        if (UserHandle.getCallingUserId() != userId) {
5329            mContext.enforceCallingPermission(
5330                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5331                    "isPermissionRevokedByPolicy for user " + userId);
5332        }
5333
5334        if (checkPermission(permission, packageName, userId)
5335                == PackageManager.PERMISSION_GRANTED) {
5336            return false;
5337        }
5338
5339        final int callingUid = Binder.getCallingUid();
5340        if (getInstantAppPackageName(callingUid) != null) {
5341            if (!isCallerSameApp(packageName, callingUid)) {
5342                return false;
5343            }
5344        } else {
5345            if (isInstantApp(packageName, userId)) {
5346                return false;
5347            }
5348        }
5349
5350        final long identity = Binder.clearCallingIdentity();
5351        try {
5352            final int flags = getPermissionFlags(permission, packageName, userId);
5353            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5354        } finally {
5355            Binder.restoreCallingIdentity(identity);
5356        }
5357    }
5358
5359    @Override
5360    public String getPermissionControllerPackageName() {
5361        synchronized (mPackages) {
5362            return mRequiredInstallerPackage;
5363        }
5364    }
5365
5366    /**
5367     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5368     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5369     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5370     * @param message the message to log on security exception
5371     */
5372    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5373            boolean checkShell, String message) {
5374        if (userId < 0) {
5375            throw new IllegalArgumentException("Invalid userId " + userId);
5376        }
5377        if (checkShell) {
5378            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5379        }
5380        if (userId == UserHandle.getUserId(callingUid)) return;
5381        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5382            if (requireFullPermission) {
5383                mContext.enforceCallingOrSelfPermission(
5384                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5385            } else {
5386                try {
5387                    mContext.enforceCallingOrSelfPermission(
5388                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5389                } catch (SecurityException se) {
5390                    mContext.enforceCallingOrSelfPermission(
5391                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5392                }
5393            }
5394        }
5395    }
5396
5397    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5398        if (callingUid == Process.SHELL_UID) {
5399            if (userHandle >= 0
5400                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5401                throw new SecurityException("Shell does not have permission to access user "
5402                        + userHandle);
5403            } else if (userHandle < 0) {
5404                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5405                        + Debug.getCallers(3));
5406            }
5407        }
5408    }
5409
5410    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5411        int size = 0;
5412        for (BasePermission perm : mSettings.mPermissions.values()) {
5413            size += tree.calculateFootprint(perm);
5414        }
5415        return size;
5416    }
5417
5418    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5419        // We calculate the max size of permissions defined by this uid and throw
5420        // if that plus the size of 'info' would exceed our stated maximum.
5421        if (tree.getUid() != Process.SYSTEM_UID) {
5422            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5423            if (curTreeSize + info.calculateFootprint() > MAX_PERMISSION_TREE_FOOTPRINT) {
5424                throw new SecurityException("Permission tree size cap exceeded");
5425            }
5426        }
5427    }
5428
5429    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5430        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5431            throw new SecurityException("Instant apps can't add permissions");
5432        }
5433        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5434            throw new SecurityException("Label must be specified in permission");
5435        }
5436        BasePermission tree = BasePermission.enforcePermissionTreeLP(
5437                mSettings.mPermissionTrees, info.name, Binder.getCallingUid());
5438        BasePermission bp = mSettings.mPermissions.get(info.name);
5439        boolean added = bp == null;
5440        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5441        if (added) {
5442            enforcePermissionCapLocked(info, tree);
5443            bp = new BasePermission(info.name, tree.getSourcePackageName(),
5444                    BasePermission.TYPE_DYNAMIC);
5445        } else if (bp.isDynamic()) {
5446            throw new SecurityException(
5447                    "Not allowed to modify non-dynamic permission "
5448                    + info.name);
5449        }
5450        final boolean changed = bp.addToTree(fixedLevel, info, tree);
5451        if (added) {
5452            mSettings.mPermissions.put(info.name, bp);
5453        }
5454        if (changed) {
5455            if (!async) {
5456                mSettings.writeLPr();
5457            } else {
5458                scheduleWriteSettingsLocked();
5459            }
5460        }
5461        return added;
5462    }
5463
5464    @Override
5465    public boolean addPermission(PermissionInfo info) {
5466        synchronized (mPackages) {
5467            return addPermissionLocked(info, false);
5468        }
5469    }
5470
5471    @Override
5472    public boolean addPermissionAsync(PermissionInfo info) {
5473        synchronized (mPackages) {
5474            return addPermissionLocked(info, true);
5475        }
5476    }
5477
5478    @Override
5479    public void removePermission(String name) {
5480        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5481            throw new SecurityException("Instant applications don't have access to this method");
5482        }
5483        synchronized (mPackages) {
5484            BasePermission.enforcePermissionTreeLP(
5485                    mSettings.mPermissionTrees, name, Binder.getCallingUid());
5486            BasePermission bp = mSettings.mPermissions.get(name);
5487            if (bp != null) {
5488                if (bp.isDynamic()) {
5489                    throw new SecurityException(
5490                            "Not allowed to modify non-dynamic permission "
5491                            + name);
5492                }
5493                mSettings.mPermissions.remove(name);
5494                mSettings.writeLPr();
5495            }
5496        }
5497    }
5498
5499    @Override
5500    public void grantRuntimePermission(String packageName, String name, final int userId) {
5501        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5502    }
5503
5504    private void grantRuntimePermission(String packageName, String name, final int userId,
5505            boolean overridePolicy) {
5506        if (!sUserManager.exists(userId)) {
5507            Log.e(TAG, "No such user:" + userId);
5508            return;
5509        }
5510        final int callingUid = Binder.getCallingUid();
5511
5512        mContext.enforceCallingOrSelfPermission(
5513                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5514                "grantRuntimePermission");
5515
5516        enforceCrossUserPermission(callingUid, userId,
5517                true /* requireFullPermission */, true /* checkShell */,
5518                "grantRuntimePermission");
5519
5520        final int uid;
5521        final PackageSetting ps;
5522
5523        synchronized (mPackages) {
5524            final PackageParser.Package pkg = mPackages.get(packageName);
5525            if (pkg == null) {
5526                throw new IllegalArgumentException("Unknown package: " + packageName);
5527            }
5528            final BasePermission bp = mSettings.mPermissions.get(name);
5529            if (bp == null) {
5530                throw new IllegalArgumentException("Unknown permission: " + name);
5531            }
5532            ps = (PackageSetting) pkg.mExtras;
5533            if (ps == null
5534                    || filterAppAccessLPr(ps, callingUid, userId)) {
5535                throw new IllegalArgumentException("Unknown package: " + packageName);
5536            }
5537
5538            bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
5539
5540            // If a permission review is required for legacy apps we represent
5541            // their permissions as always granted runtime ones since we need
5542            // to keep the review required permission flag per user while an
5543            // install permission's state is shared across all users.
5544            if (mPermissionReviewRequired
5545                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5546                    && bp.isRuntime()) {
5547                return;
5548            }
5549
5550            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5551
5552            final PermissionsState permissionsState = ps.getPermissionsState();
5553
5554            final int flags = permissionsState.getPermissionFlags(name, userId);
5555            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5556                throw new SecurityException("Cannot grant system fixed permission "
5557                        + name + " for package " + packageName);
5558            }
5559            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5560                throw new SecurityException("Cannot grant policy fixed permission "
5561                        + name + " for package " + packageName);
5562            }
5563
5564            if (bp.isDevelopment()) {
5565                // Development permissions must be handled specially, since they are not
5566                // normal runtime permissions.  For now they apply to all users.
5567                if (permissionsState.grantInstallPermission(bp) !=
5568                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5569                    scheduleWriteSettingsLocked();
5570                }
5571                return;
5572            }
5573
5574            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5575                throw new SecurityException("Cannot grant non-ephemeral permission"
5576                        + name + " for package " + packageName);
5577            }
5578
5579            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5580                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5581                return;
5582            }
5583
5584            final int result = permissionsState.grantRuntimePermission(bp, userId);
5585            switch (result) {
5586                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5587                    return;
5588                }
5589
5590                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5591                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5592                    mHandler.post(new Runnable() {
5593                        @Override
5594                        public void run() {
5595                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5596                        }
5597                    });
5598                }
5599                break;
5600            }
5601
5602            if (bp.isRuntime()) {
5603                logPermissionGranted(mContext, name, packageName);
5604            }
5605
5606            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5607
5608            // Not critical if that is lost - app has to request again.
5609            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5610        }
5611
5612        // Only need to do this if user is initialized. Otherwise it's a new user
5613        // and there are no processes running as the user yet and there's no need
5614        // to make an expensive call to remount processes for the changed permissions.
5615        if (READ_EXTERNAL_STORAGE.equals(name)
5616                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5617            final long token = Binder.clearCallingIdentity();
5618            try {
5619                if (sUserManager.isInitialized(userId)) {
5620                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5621                            StorageManagerInternal.class);
5622                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5623                }
5624            } finally {
5625                Binder.restoreCallingIdentity(token);
5626            }
5627        }
5628    }
5629
5630    @Override
5631    public void revokeRuntimePermission(String packageName, String name, int userId) {
5632        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5633    }
5634
5635    private void revokeRuntimePermission(String packageName, String name, int userId,
5636            boolean overridePolicy) {
5637        if (!sUserManager.exists(userId)) {
5638            Log.e(TAG, "No such user:" + userId);
5639            return;
5640        }
5641
5642        mContext.enforceCallingOrSelfPermission(
5643                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5644                "revokeRuntimePermission");
5645
5646        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5647                true /* requireFullPermission */, true /* checkShell */,
5648                "revokeRuntimePermission");
5649
5650        final int appId;
5651
5652        synchronized (mPackages) {
5653            final PackageParser.Package pkg = mPackages.get(packageName);
5654            if (pkg == null) {
5655                throw new IllegalArgumentException("Unknown package: " + packageName);
5656            }
5657            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5658            if (ps == null
5659                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5660                throw new IllegalArgumentException("Unknown package: " + packageName);
5661            }
5662            final BasePermission bp = mSettings.mPermissions.get(name);
5663            if (bp == null) {
5664                throw new IllegalArgumentException("Unknown permission: " + name);
5665            }
5666
5667            bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
5668
5669            // If a permission review is required for legacy apps we represent
5670            // their permissions as always granted runtime ones since we need
5671            // to keep the review required permission flag per user while an
5672            // install permission's state is shared across all users.
5673            if (mPermissionReviewRequired
5674                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5675                    && bp.isRuntime()) {
5676                return;
5677            }
5678
5679            final PermissionsState permissionsState = ps.getPermissionsState();
5680
5681            final int flags = permissionsState.getPermissionFlags(name, userId);
5682            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5683                throw new SecurityException("Cannot revoke system fixed permission "
5684                        + name + " for package " + packageName);
5685            }
5686            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5687                throw new SecurityException("Cannot revoke policy fixed permission "
5688                        + name + " for package " + packageName);
5689            }
5690
5691            if (bp.isDevelopment()) {
5692                // Development permissions must be handled specially, since they are not
5693                // normal runtime permissions.  For now they apply to all users.
5694                if (permissionsState.revokeInstallPermission(bp) !=
5695                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5696                    scheduleWriteSettingsLocked();
5697                }
5698                return;
5699            }
5700
5701            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5702                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5703                return;
5704            }
5705
5706            if (bp.isRuntime()) {
5707                logPermissionRevoked(mContext, name, packageName);
5708            }
5709
5710            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5711
5712            // Critical, after this call app should never have the permission.
5713            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5714
5715            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5716        }
5717
5718        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5719    }
5720
5721    /**
5722     * Get the first event id for the permission.
5723     *
5724     * <p>There are four events for each permission: <ul>
5725     *     <li>Request permission: first id + 0</li>
5726     *     <li>Grant permission: first id + 1</li>
5727     *     <li>Request for permission denied: first id + 2</li>
5728     *     <li>Revoke permission: first id + 3</li>
5729     * </ul></p>
5730     *
5731     * @param name name of the permission
5732     *
5733     * @return The first event id for the permission
5734     */
5735    private static int getBaseEventId(@NonNull String name) {
5736        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5737
5738        if (eventIdIndex == -1) {
5739            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5740                    || Build.IS_USER) {
5741                Log.i(TAG, "Unknown permission " + name);
5742
5743                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5744            } else {
5745                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5746                //
5747                // Also update
5748                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5749                // - metrics_constants.proto
5750                throw new IllegalStateException("Unknown permission " + name);
5751            }
5752        }
5753
5754        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5755    }
5756
5757    /**
5758     * Log that a permission was revoked.
5759     *
5760     * @param context Context of the caller
5761     * @param name name of the permission
5762     * @param packageName package permission if for
5763     */
5764    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5765            @NonNull String packageName) {
5766        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5767    }
5768
5769    /**
5770     * Log that a permission request was granted.
5771     *
5772     * @param context Context of the caller
5773     * @param name name of the permission
5774     * @param packageName package permission if for
5775     */
5776    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5777            @NonNull String packageName) {
5778        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5779    }
5780
5781    @Override
5782    public void resetRuntimePermissions() {
5783        mContext.enforceCallingOrSelfPermission(
5784                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5785                "revokeRuntimePermission");
5786
5787        int callingUid = Binder.getCallingUid();
5788        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5789            mContext.enforceCallingOrSelfPermission(
5790                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5791                    "resetRuntimePermissions");
5792        }
5793
5794        synchronized (mPackages) {
5795            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5796            for (int userId : UserManagerService.getInstance().getUserIds()) {
5797                final int packageCount = mPackages.size();
5798                for (int i = 0; i < packageCount; i++) {
5799                    PackageParser.Package pkg = mPackages.valueAt(i);
5800                    if (!(pkg.mExtras instanceof PackageSetting)) {
5801                        continue;
5802                    }
5803                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5804                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5805                }
5806            }
5807        }
5808    }
5809
5810    @Override
5811    public int getPermissionFlags(String name, String packageName, int userId) {
5812        if (!sUserManager.exists(userId)) {
5813            return 0;
5814        }
5815
5816        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5817
5818        final int callingUid = Binder.getCallingUid();
5819        enforceCrossUserPermission(callingUid, userId,
5820                true /* requireFullPermission */, false /* checkShell */,
5821                "getPermissionFlags");
5822
5823        synchronized (mPackages) {
5824            final PackageParser.Package pkg = mPackages.get(packageName);
5825            if (pkg == null) {
5826                return 0;
5827            }
5828            final BasePermission bp = mSettings.mPermissions.get(name);
5829            if (bp == null) {
5830                return 0;
5831            }
5832            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5833            if (ps == null
5834                    || filterAppAccessLPr(ps, callingUid, userId)) {
5835                return 0;
5836            }
5837            PermissionsState permissionsState = ps.getPermissionsState();
5838            return permissionsState.getPermissionFlags(name, userId);
5839        }
5840    }
5841
5842    @Override
5843    public void updatePermissionFlags(String name, String packageName, int flagMask,
5844            int flagValues, int userId) {
5845        if (!sUserManager.exists(userId)) {
5846            return;
5847        }
5848
5849        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5850
5851        final int callingUid = Binder.getCallingUid();
5852        enforceCrossUserPermission(callingUid, userId,
5853                true /* requireFullPermission */, true /* checkShell */,
5854                "updatePermissionFlags");
5855
5856        // Only the system can change these flags and nothing else.
5857        if (getCallingUid() != Process.SYSTEM_UID) {
5858            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5859            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5860            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5861            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5862            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5863        }
5864
5865        synchronized (mPackages) {
5866            final PackageParser.Package pkg = mPackages.get(packageName);
5867            if (pkg == null) {
5868                throw new IllegalArgumentException("Unknown package: " + packageName);
5869            }
5870            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5871            if (ps == null
5872                    || filterAppAccessLPr(ps, callingUid, userId)) {
5873                throw new IllegalArgumentException("Unknown package: " + packageName);
5874            }
5875
5876            final BasePermission bp = mSettings.mPermissions.get(name);
5877            if (bp == null) {
5878                throw new IllegalArgumentException("Unknown permission: " + name);
5879            }
5880
5881            PermissionsState permissionsState = ps.getPermissionsState();
5882
5883            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5884
5885            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5886                // Install and runtime permissions are stored in different places,
5887                // so figure out what permission changed and persist the change.
5888                if (permissionsState.getInstallPermissionState(name) != null) {
5889                    scheduleWriteSettingsLocked();
5890                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5891                        || hadState) {
5892                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5893                }
5894            }
5895        }
5896    }
5897
5898    /**
5899     * Update the permission flags for all packages and runtime permissions of a user in order
5900     * to allow device or profile owner to remove POLICY_FIXED.
5901     */
5902    @Override
5903    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5904        if (!sUserManager.exists(userId)) {
5905            return;
5906        }
5907
5908        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5909
5910        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5911                true /* requireFullPermission */, true /* checkShell */,
5912                "updatePermissionFlagsForAllApps");
5913
5914        // Only the system can change system fixed flags.
5915        if (getCallingUid() != Process.SYSTEM_UID) {
5916            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5917            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5918        }
5919
5920        synchronized (mPackages) {
5921            boolean changed = false;
5922            final int packageCount = mPackages.size();
5923            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5924                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5925                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5926                if (ps == null) {
5927                    continue;
5928                }
5929                PermissionsState permissionsState = ps.getPermissionsState();
5930                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5931                        userId, flagMask, flagValues);
5932            }
5933            if (changed) {
5934                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5935            }
5936        }
5937    }
5938
5939    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5940        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5941                != PackageManager.PERMISSION_GRANTED
5942            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5943                != PackageManager.PERMISSION_GRANTED) {
5944            throw new SecurityException(message + " requires "
5945                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5946                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5947        }
5948    }
5949
5950    @Override
5951    public boolean shouldShowRequestPermissionRationale(String permissionName,
5952            String packageName, int userId) {
5953        if (UserHandle.getCallingUserId() != userId) {
5954            mContext.enforceCallingPermission(
5955                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5956                    "canShowRequestPermissionRationale for user " + userId);
5957        }
5958
5959        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5960        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5961            return false;
5962        }
5963
5964        if (checkPermission(permissionName, packageName, userId)
5965                == PackageManager.PERMISSION_GRANTED) {
5966            return false;
5967        }
5968
5969        final int flags;
5970
5971        final long identity = Binder.clearCallingIdentity();
5972        try {
5973            flags = getPermissionFlags(permissionName,
5974                    packageName, userId);
5975        } finally {
5976            Binder.restoreCallingIdentity(identity);
5977        }
5978
5979        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5980                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5981                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5982
5983        if ((flags & fixedFlags) != 0) {
5984            return false;
5985        }
5986
5987        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5988    }
5989
5990    @Override
5991    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5992        mContext.enforceCallingOrSelfPermission(
5993                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5994                "addOnPermissionsChangeListener");
5995
5996        synchronized (mPackages) {
5997            mOnPermissionChangeListeners.addListenerLocked(listener);
5998        }
5999    }
6000
6001    @Override
6002    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6003        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6004            throw new SecurityException("Instant applications don't have access to this method");
6005        }
6006        synchronized (mPackages) {
6007            mOnPermissionChangeListeners.removeListenerLocked(listener);
6008        }
6009    }
6010
6011    @Override
6012    public boolean isProtectedBroadcast(String actionName) {
6013        // allow instant applications
6014        synchronized (mProtectedBroadcasts) {
6015            if (mProtectedBroadcasts.contains(actionName)) {
6016                return true;
6017            } else if (actionName != null) {
6018                // TODO: remove these terrible hacks
6019                if (actionName.startsWith("android.net.netmon.lingerExpired")
6020                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6021                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6022                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6023                    return true;
6024                }
6025            }
6026        }
6027        return false;
6028    }
6029
6030    @Override
6031    public int checkSignatures(String pkg1, String pkg2) {
6032        synchronized (mPackages) {
6033            final PackageParser.Package p1 = mPackages.get(pkg1);
6034            final PackageParser.Package p2 = mPackages.get(pkg2);
6035            if (p1 == null || p1.mExtras == null
6036                    || p2 == null || p2.mExtras == null) {
6037                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6038            }
6039            final int callingUid = Binder.getCallingUid();
6040            final int callingUserId = UserHandle.getUserId(callingUid);
6041            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6042            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6043            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6044                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6045                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6046            }
6047            return compareSignatures(p1.mSignatures, p2.mSignatures);
6048        }
6049    }
6050
6051    @Override
6052    public int checkUidSignatures(int uid1, int uid2) {
6053        final int callingUid = Binder.getCallingUid();
6054        final int callingUserId = UserHandle.getUserId(callingUid);
6055        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6056        // Map to base uids.
6057        uid1 = UserHandle.getAppId(uid1);
6058        uid2 = UserHandle.getAppId(uid2);
6059        // reader
6060        synchronized (mPackages) {
6061            Signature[] s1;
6062            Signature[] s2;
6063            Object obj = mSettings.getUserIdLPr(uid1);
6064            if (obj != null) {
6065                if (obj instanceof SharedUserSetting) {
6066                    if (isCallerInstantApp) {
6067                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6068                    }
6069                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6070                } else if (obj instanceof PackageSetting) {
6071                    final PackageSetting ps = (PackageSetting) obj;
6072                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6073                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6074                    }
6075                    s1 = ps.signatures.mSignatures;
6076                } else {
6077                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6078                }
6079            } else {
6080                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6081            }
6082            obj = mSettings.getUserIdLPr(uid2);
6083            if (obj != null) {
6084                if (obj instanceof SharedUserSetting) {
6085                    if (isCallerInstantApp) {
6086                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6087                    }
6088                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6089                } else if (obj instanceof PackageSetting) {
6090                    final PackageSetting ps = (PackageSetting) obj;
6091                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6092                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6093                    }
6094                    s2 = ps.signatures.mSignatures;
6095                } else {
6096                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6097                }
6098            } else {
6099                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6100            }
6101            return compareSignatures(s1, s2);
6102        }
6103    }
6104
6105    /**
6106     * This method should typically only be used when granting or revoking
6107     * permissions, since the app may immediately restart after this call.
6108     * <p>
6109     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6110     * guard your work against the app being relaunched.
6111     */
6112    private void killUid(int appId, int userId, String reason) {
6113        final long identity = Binder.clearCallingIdentity();
6114        try {
6115            IActivityManager am = ActivityManager.getService();
6116            if (am != null) {
6117                try {
6118                    am.killUid(appId, userId, reason);
6119                } catch (RemoteException e) {
6120                    /* ignore - same process */
6121                }
6122            }
6123        } finally {
6124            Binder.restoreCallingIdentity(identity);
6125        }
6126    }
6127
6128    /**
6129     * Compares two sets of signatures. Returns:
6130     * <br />
6131     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6132     * <br />
6133     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6134     * <br />
6135     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6136     * <br />
6137     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6138     * <br />
6139     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6140     */
6141    static int compareSignatures(Signature[] s1, Signature[] s2) {
6142        if (s1 == null) {
6143            return s2 == null
6144                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6145                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6146        }
6147
6148        if (s2 == null) {
6149            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6150        }
6151
6152        if (s1.length != s2.length) {
6153            return PackageManager.SIGNATURE_NO_MATCH;
6154        }
6155
6156        // Since both signature sets are of size 1, we can compare without HashSets.
6157        if (s1.length == 1) {
6158            return s1[0].equals(s2[0]) ?
6159                    PackageManager.SIGNATURE_MATCH :
6160                    PackageManager.SIGNATURE_NO_MATCH;
6161        }
6162
6163        ArraySet<Signature> set1 = new ArraySet<Signature>();
6164        for (Signature sig : s1) {
6165            set1.add(sig);
6166        }
6167        ArraySet<Signature> set2 = new ArraySet<Signature>();
6168        for (Signature sig : s2) {
6169            set2.add(sig);
6170        }
6171        // Make sure s2 contains all signatures in s1.
6172        if (set1.equals(set2)) {
6173            return PackageManager.SIGNATURE_MATCH;
6174        }
6175        return PackageManager.SIGNATURE_NO_MATCH;
6176    }
6177
6178    /**
6179     * If the database version for this type of package (internal storage or
6180     * external storage) is less than the version where package signatures
6181     * were updated, return true.
6182     */
6183    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6184        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6185        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6186    }
6187
6188    /**
6189     * Used for backward compatibility to make sure any packages with
6190     * certificate chains get upgraded to the new style. {@code existingSigs}
6191     * will be in the old format (since they were stored on disk from before the
6192     * system upgrade) and {@code scannedSigs} will be in the newer format.
6193     */
6194    private int compareSignaturesCompat(PackageSignatures existingSigs,
6195            PackageParser.Package scannedPkg) {
6196        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6197            return PackageManager.SIGNATURE_NO_MATCH;
6198        }
6199
6200        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6201        for (Signature sig : existingSigs.mSignatures) {
6202            existingSet.add(sig);
6203        }
6204        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6205        for (Signature sig : scannedPkg.mSignatures) {
6206            try {
6207                Signature[] chainSignatures = sig.getChainSignatures();
6208                for (Signature chainSig : chainSignatures) {
6209                    scannedCompatSet.add(chainSig);
6210                }
6211            } catch (CertificateEncodingException e) {
6212                scannedCompatSet.add(sig);
6213            }
6214        }
6215        /*
6216         * Make sure the expanded scanned set contains all signatures in the
6217         * existing one.
6218         */
6219        if (scannedCompatSet.equals(existingSet)) {
6220            // Migrate the old signatures to the new scheme.
6221            existingSigs.assignSignatures(scannedPkg.mSignatures);
6222            // The new KeySets will be re-added later in the scanning process.
6223            synchronized (mPackages) {
6224                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6225            }
6226            return PackageManager.SIGNATURE_MATCH;
6227        }
6228        return PackageManager.SIGNATURE_NO_MATCH;
6229    }
6230
6231    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6232        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6233        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6234    }
6235
6236    private int compareSignaturesRecover(PackageSignatures existingSigs,
6237            PackageParser.Package scannedPkg) {
6238        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6239            return PackageManager.SIGNATURE_NO_MATCH;
6240        }
6241
6242        String msg = null;
6243        try {
6244            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6245                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6246                        + scannedPkg.packageName);
6247                return PackageManager.SIGNATURE_MATCH;
6248            }
6249        } catch (CertificateException e) {
6250            msg = e.getMessage();
6251        }
6252
6253        logCriticalInfo(Log.INFO,
6254                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6255        return PackageManager.SIGNATURE_NO_MATCH;
6256    }
6257
6258    @Override
6259    public List<String> getAllPackages() {
6260        final int callingUid = Binder.getCallingUid();
6261        final int callingUserId = UserHandle.getUserId(callingUid);
6262        synchronized (mPackages) {
6263            if (canViewInstantApps(callingUid, callingUserId)) {
6264                return new ArrayList<String>(mPackages.keySet());
6265            }
6266            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6267            final List<String> result = new ArrayList<>();
6268            if (instantAppPkgName != null) {
6269                // caller is an instant application; filter unexposed applications
6270                for (PackageParser.Package pkg : mPackages.values()) {
6271                    if (!pkg.visibleToInstantApps) {
6272                        continue;
6273                    }
6274                    result.add(pkg.packageName);
6275                }
6276            } else {
6277                // caller is a normal application; filter instant applications
6278                for (PackageParser.Package pkg : mPackages.values()) {
6279                    final PackageSetting ps =
6280                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6281                    if (ps != null
6282                            && ps.getInstantApp(callingUserId)
6283                            && !mInstantAppRegistry.isInstantAccessGranted(
6284                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6285                        continue;
6286                    }
6287                    result.add(pkg.packageName);
6288                }
6289            }
6290            return result;
6291        }
6292    }
6293
6294    @Override
6295    public String[] getPackagesForUid(int uid) {
6296        final int callingUid = Binder.getCallingUid();
6297        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6298        final int userId = UserHandle.getUserId(uid);
6299        uid = UserHandle.getAppId(uid);
6300        // reader
6301        synchronized (mPackages) {
6302            Object obj = mSettings.getUserIdLPr(uid);
6303            if (obj instanceof SharedUserSetting) {
6304                if (isCallerInstantApp) {
6305                    return null;
6306                }
6307                final SharedUserSetting sus = (SharedUserSetting) obj;
6308                final int N = sus.packages.size();
6309                String[] res = new String[N];
6310                final Iterator<PackageSetting> it = sus.packages.iterator();
6311                int i = 0;
6312                while (it.hasNext()) {
6313                    PackageSetting ps = it.next();
6314                    if (ps.getInstalled(userId)) {
6315                        res[i++] = ps.name;
6316                    } else {
6317                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6318                    }
6319                }
6320                return res;
6321            } else if (obj instanceof PackageSetting) {
6322                final PackageSetting ps = (PackageSetting) obj;
6323                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6324                    return new String[]{ps.name};
6325                }
6326            }
6327        }
6328        return null;
6329    }
6330
6331    @Override
6332    public String getNameForUid(int uid) {
6333        final int callingUid = Binder.getCallingUid();
6334        if (getInstantAppPackageName(callingUid) != null) {
6335            return null;
6336        }
6337        synchronized (mPackages) {
6338            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6339            if (obj instanceof SharedUserSetting) {
6340                final SharedUserSetting sus = (SharedUserSetting) obj;
6341                return sus.name + ":" + sus.userId;
6342            } else if (obj instanceof PackageSetting) {
6343                final PackageSetting ps = (PackageSetting) obj;
6344                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6345                    return null;
6346                }
6347                return ps.name;
6348            }
6349            return null;
6350        }
6351    }
6352
6353    @Override
6354    public String[] getNamesForUids(int[] uids) {
6355        if (uids == null || uids.length == 0) {
6356            return null;
6357        }
6358        final int callingUid = Binder.getCallingUid();
6359        if (getInstantAppPackageName(callingUid) != null) {
6360            return null;
6361        }
6362        final String[] names = new String[uids.length];
6363        synchronized (mPackages) {
6364            for (int i = uids.length - 1; i >= 0; i--) {
6365                final int uid = uids[i];
6366                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6367                if (obj instanceof SharedUserSetting) {
6368                    final SharedUserSetting sus = (SharedUserSetting) obj;
6369                    names[i] = "shared:" + sus.name;
6370                } else if (obj instanceof PackageSetting) {
6371                    final PackageSetting ps = (PackageSetting) obj;
6372                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6373                        names[i] = null;
6374                    } else {
6375                        names[i] = ps.name;
6376                    }
6377                } else {
6378                    names[i] = null;
6379                }
6380            }
6381        }
6382        return names;
6383    }
6384
6385    @Override
6386    public int getUidForSharedUser(String sharedUserName) {
6387        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6388            return -1;
6389        }
6390        if (sharedUserName == null) {
6391            return -1;
6392        }
6393        // reader
6394        synchronized (mPackages) {
6395            SharedUserSetting suid;
6396            try {
6397                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6398                if (suid != null) {
6399                    return suid.userId;
6400                }
6401            } catch (PackageManagerException ignore) {
6402                // can't happen, but, still need to catch it
6403            }
6404            return -1;
6405        }
6406    }
6407
6408    @Override
6409    public int getFlagsForUid(int uid) {
6410        final int callingUid = Binder.getCallingUid();
6411        if (getInstantAppPackageName(callingUid) != null) {
6412            return 0;
6413        }
6414        synchronized (mPackages) {
6415            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6416            if (obj instanceof SharedUserSetting) {
6417                final SharedUserSetting sus = (SharedUserSetting) obj;
6418                return sus.pkgFlags;
6419            } else if (obj instanceof PackageSetting) {
6420                final PackageSetting ps = (PackageSetting) obj;
6421                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6422                    return 0;
6423                }
6424                return ps.pkgFlags;
6425            }
6426        }
6427        return 0;
6428    }
6429
6430    @Override
6431    public int getPrivateFlagsForUid(int uid) {
6432        final int callingUid = Binder.getCallingUid();
6433        if (getInstantAppPackageName(callingUid) != null) {
6434            return 0;
6435        }
6436        synchronized (mPackages) {
6437            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6438            if (obj instanceof SharedUserSetting) {
6439                final SharedUserSetting sus = (SharedUserSetting) obj;
6440                return sus.pkgPrivateFlags;
6441            } else if (obj instanceof PackageSetting) {
6442                final PackageSetting ps = (PackageSetting) obj;
6443                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6444                    return 0;
6445                }
6446                return ps.pkgPrivateFlags;
6447            }
6448        }
6449        return 0;
6450    }
6451
6452    @Override
6453    public boolean isUidPrivileged(int uid) {
6454        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6455            return false;
6456        }
6457        uid = UserHandle.getAppId(uid);
6458        // reader
6459        synchronized (mPackages) {
6460            Object obj = mSettings.getUserIdLPr(uid);
6461            if (obj instanceof SharedUserSetting) {
6462                final SharedUserSetting sus = (SharedUserSetting) obj;
6463                final Iterator<PackageSetting> it = sus.packages.iterator();
6464                while (it.hasNext()) {
6465                    if (it.next().isPrivileged()) {
6466                        return true;
6467                    }
6468                }
6469            } else if (obj instanceof PackageSetting) {
6470                final PackageSetting ps = (PackageSetting) obj;
6471                return ps.isPrivileged();
6472            }
6473        }
6474        return false;
6475    }
6476
6477    @Override
6478    public String[] getAppOpPermissionPackages(String permissionName) {
6479        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6480            return null;
6481        }
6482        synchronized (mPackages) {
6483            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6484            if (pkgs == null) {
6485                return null;
6486            }
6487            return pkgs.toArray(new String[pkgs.size()]);
6488        }
6489    }
6490
6491    @Override
6492    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6493            int flags, int userId) {
6494        return resolveIntentInternal(
6495                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6496    }
6497
6498    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6499            int flags, int userId, boolean resolveForStart) {
6500        try {
6501            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6502
6503            if (!sUserManager.exists(userId)) return null;
6504            final int callingUid = Binder.getCallingUid();
6505            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6506            enforceCrossUserPermission(callingUid, userId,
6507                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6508
6509            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6510            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6511                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6513
6514            final ResolveInfo bestChoice =
6515                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6516            return bestChoice;
6517        } finally {
6518            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6519        }
6520    }
6521
6522    @Override
6523    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6524        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6525            throw new SecurityException(
6526                    "findPersistentPreferredActivity can only be run by the system");
6527        }
6528        if (!sUserManager.exists(userId)) {
6529            return null;
6530        }
6531        final int callingUid = Binder.getCallingUid();
6532        intent = updateIntentForResolve(intent);
6533        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6534        final int flags = updateFlagsForResolve(
6535                0, userId, intent, callingUid, false /*includeInstantApps*/);
6536        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6537                userId);
6538        synchronized (mPackages) {
6539            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6540                    userId);
6541        }
6542    }
6543
6544    @Override
6545    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6546            IntentFilter filter, int match, ComponentName activity) {
6547        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6548            return;
6549        }
6550        final int userId = UserHandle.getCallingUserId();
6551        if (DEBUG_PREFERRED) {
6552            Log.v(TAG, "setLastChosenActivity intent=" + intent
6553                + " resolvedType=" + resolvedType
6554                + " flags=" + flags
6555                + " filter=" + filter
6556                + " match=" + match
6557                + " activity=" + activity);
6558            filter.dump(new PrintStreamPrinter(System.out), "    ");
6559        }
6560        intent.setComponent(null);
6561        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6562                userId);
6563        // Find any earlier preferred or last chosen entries and nuke them
6564        findPreferredActivity(intent, resolvedType,
6565                flags, query, 0, false, true, false, userId);
6566        // Add the new activity as the last chosen for this filter
6567        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6568                "Setting last chosen");
6569    }
6570
6571    @Override
6572    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6573        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6574            return null;
6575        }
6576        final int userId = UserHandle.getCallingUserId();
6577        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6578        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6579                userId);
6580        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6581                false, false, false, userId);
6582    }
6583
6584    /**
6585     * Returns whether or not instant apps have been disabled remotely.
6586     */
6587    private boolean isEphemeralDisabled() {
6588        return mEphemeralAppsDisabled;
6589    }
6590
6591    private boolean isInstantAppAllowed(
6592            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6593            boolean skipPackageCheck) {
6594        if (mInstantAppResolverConnection == null) {
6595            return false;
6596        }
6597        if (mInstantAppInstallerActivity == null) {
6598            return false;
6599        }
6600        if (intent.getComponent() != null) {
6601            return false;
6602        }
6603        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6604            return false;
6605        }
6606        if (!skipPackageCheck && intent.getPackage() != null) {
6607            return false;
6608        }
6609        final boolean isWebUri = hasWebURI(intent);
6610        if (!isWebUri || intent.getData().getHost() == null) {
6611            return false;
6612        }
6613        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6614        // Or if there's already an ephemeral app installed that handles the action
6615        synchronized (mPackages) {
6616            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6617            for (int n = 0; n < count; n++) {
6618                final ResolveInfo info = resolvedActivities.get(n);
6619                final String packageName = info.activityInfo.packageName;
6620                final PackageSetting ps = mSettings.mPackages.get(packageName);
6621                if (ps != null) {
6622                    // only check domain verification status if the app is not a browser
6623                    if (!info.handleAllWebDataURI) {
6624                        // Try to get the status from User settings first
6625                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6626                        final int status = (int) (packedStatus >> 32);
6627                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6628                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6629                            if (DEBUG_EPHEMERAL) {
6630                                Slog.v(TAG, "DENY instant app;"
6631                                    + " pkg: " + packageName + ", status: " + status);
6632                            }
6633                            return false;
6634                        }
6635                    }
6636                    if (ps.getInstantApp(userId)) {
6637                        if (DEBUG_EPHEMERAL) {
6638                            Slog.v(TAG, "DENY instant app installed;"
6639                                    + " pkg: " + packageName);
6640                        }
6641                        return false;
6642                    }
6643                }
6644            }
6645        }
6646        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6647        return true;
6648    }
6649
6650    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6651            Intent origIntent, String resolvedType, String callingPackage,
6652            Bundle verificationBundle, int userId) {
6653        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6654                new InstantAppRequest(responseObj, origIntent, resolvedType,
6655                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6656        mHandler.sendMessage(msg);
6657    }
6658
6659    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6660            int flags, List<ResolveInfo> query, int userId) {
6661        if (query != null) {
6662            final int N = query.size();
6663            if (N == 1) {
6664                return query.get(0);
6665            } else if (N > 1) {
6666                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6667                // If there is more than one activity with the same priority,
6668                // then let the user decide between them.
6669                ResolveInfo r0 = query.get(0);
6670                ResolveInfo r1 = query.get(1);
6671                if (DEBUG_INTENT_MATCHING || debug) {
6672                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6673                            + r1.activityInfo.name + "=" + r1.priority);
6674                }
6675                // If the first activity has a higher priority, or a different
6676                // default, then it is always desirable to pick it.
6677                if (r0.priority != r1.priority
6678                        || r0.preferredOrder != r1.preferredOrder
6679                        || r0.isDefault != r1.isDefault) {
6680                    return query.get(0);
6681                }
6682                // If we have saved a preference for a preferred activity for
6683                // this Intent, use that.
6684                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6685                        flags, query, r0.priority, true, false, debug, userId);
6686                if (ri != null) {
6687                    return ri;
6688                }
6689                // If we have an ephemeral app, use it
6690                for (int i = 0; i < N; i++) {
6691                    ri = query.get(i);
6692                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6693                        final String packageName = ri.activityInfo.packageName;
6694                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6695                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6696                        final int status = (int)(packedStatus >> 32);
6697                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6698                            return ri;
6699                        }
6700                    }
6701                }
6702                ri = new ResolveInfo(mResolveInfo);
6703                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6704                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6705                // If all of the options come from the same package, show the application's
6706                // label and icon instead of the generic resolver's.
6707                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6708                // and then throw away the ResolveInfo itself, meaning that the caller loses
6709                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6710                // a fallback for this case; we only set the target package's resources on
6711                // the ResolveInfo, not the ActivityInfo.
6712                final String intentPackage = intent.getPackage();
6713                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6714                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6715                    ri.resolvePackageName = intentPackage;
6716                    if (userNeedsBadging(userId)) {
6717                        ri.noResourceId = true;
6718                    } else {
6719                        ri.icon = appi.icon;
6720                    }
6721                    ri.iconResourceId = appi.icon;
6722                    ri.labelRes = appi.labelRes;
6723                }
6724                ri.activityInfo.applicationInfo = new ApplicationInfo(
6725                        ri.activityInfo.applicationInfo);
6726                if (userId != 0) {
6727                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6728                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6729                }
6730                // Make sure that the resolver is displayable in car mode
6731                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6732                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6733                return ri;
6734            }
6735        }
6736        return null;
6737    }
6738
6739    /**
6740     * Return true if the given list is not empty and all of its contents have
6741     * an activityInfo with the given package name.
6742     */
6743    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6744        if (ArrayUtils.isEmpty(list)) {
6745            return false;
6746        }
6747        for (int i = 0, N = list.size(); i < N; i++) {
6748            final ResolveInfo ri = list.get(i);
6749            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6750            if (ai == null || !packageName.equals(ai.packageName)) {
6751                return false;
6752            }
6753        }
6754        return true;
6755    }
6756
6757    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6758            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6759        final int N = query.size();
6760        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6761                .get(userId);
6762        // Get the list of persistent preferred activities that handle the intent
6763        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6764        List<PersistentPreferredActivity> pprefs = ppir != null
6765                ? ppir.queryIntent(intent, resolvedType,
6766                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6767                        userId)
6768                : null;
6769        if (pprefs != null && pprefs.size() > 0) {
6770            final int M = pprefs.size();
6771            for (int i=0; i<M; i++) {
6772                final PersistentPreferredActivity ppa = pprefs.get(i);
6773                if (DEBUG_PREFERRED || debug) {
6774                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6775                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6776                            + "\n  component=" + ppa.mComponent);
6777                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6778                }
6779                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6780                        flags | MATCH_DISABLED_COMPONENTS, userId);
6781                if (DEBUG_PREFERRED || debug) {
6782                    Slog.v(TAG, "Found persistent preferred activity:");
6783                    if (ai != null) {
6784                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6785                    } else {
6786                        Slog.v(TAG, "  null");
6787                    }
6788                }
6789                if (ai == null) {
6790                    // This previously registered persistent preferred activity
6791                    // component is no longer known. Ignore it and do NOT remove it.
6792                    continue;
6793                }
6794                for (int j=0; j<N; j++) {
6795                    final ResolveInfo ri = query.get(j);
6796                    if (!ri.activityInfo.applicationInfo.packageName
6797                            .equals(ai.applicationInfo.packageName)) {
6798                        continue;
6799                    }
6800                    if (!ri.activityInfo.name.equals(ai.name)) {
6801                        continue;
6802                    }
6803                    //  Found a persistent preference that can handle the intent.
6804                    if (DEBUG_PREFERRED || debug) {
6805                        Slog.v(TAG, "Returning persistent preferred activity: " +
6806                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6807                    }
6808                    return ri;
6809                }
6810            }
6811        }
6812        return null;
6813    }
6814
6815    // TODO: handle preferred activities missing while user has amnesia
6816    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6817            List<ResolveInfo> query, int priority, boolean always,
6818            boolean removeMatches, boolean debug, int userId) {
6819        if (!sUserManager.exists(userId)) return null;
6820        final int callingUid = Binder.getCallingUid();
6821        flags = updateFlagsForResolve(
6822                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6823        intent = updateIntentForResolve(intent);
6824        // writer
6825        synchronized (mPackages) {
6826            // Try to find a matching persistent preferred activity.
6827            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6828                    debug, userId);
6829
6830            // If a persistent preferred activity matched, use it.
6831            if (pri != null) {
6832                return pri;
6833            }
6834
6835            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6836            // Get the list of preferred activities that handle the intent
6837            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6838            List<PreferredActivity> prefs = pir != null
6839                    ? pir.queryIntent(intent, resolvedType,
6840                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6841                            userId)
6842                    : null;
6843            if (prefs != null && prefs.size() > 0) {
6844                boolean changed = false;
6845                try {
6846                    // First figure out how good the original match set is.
6847                    // We will only allow preferred activities that came
6848                    // from the same match quality.
6849                    int match = 0;
6850
6851                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6852
6853                    final int N = query.size();
6854                    for (int j=0; j<N; j++) {
6855                        final ResolveInfo ri = query.get(j);
6856                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6857                                + ": 0x" + Integer.toHexString(match));
6858                        if (ri.match > match) {
6859                            match = ri.match;
6860                        }
6861                    }
6862
6863                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6864                            + Integer.toHexString(match));
6865
6866                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6867                    final int M = prefs.size();
6868                    for (int i=0; i<M; i++) {
6869                        final PreferredActivity pa = prefs.get(i);
6870                        if (DEBUG_PREFERRED || debug) {
6871                            Slog.v(TAG, "Checking PreferredActivity ds="
6872                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6873                                    + "\n  component=" + pa.mPref.mComponent);
6874                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6875                        }
6876                        if (pa.mPref.mMatch != match) {
6877                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6878                                    + Integer.toHexString(pa.mPref.mMatch));
6879                            continue;
6880                        }
6881                        // If it's not an "always" type preferred activity and that's what we're
6882                        // looking for, skip it.
6883                        if (always && !pa.mPref.mAlways) {
6884                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6885                            continue;
6886                        }
6887                        final ActivityInfo ai = getActivityInfo(
6888                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6889                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6890                                userId);
6891                        if (DEBUG_PREFERRED || debug) {
6892                            Slog.v(TAG, "Found preferred activity:");
6893                            if (ai != null) {
6894                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6895                            } else {
6896                                Slog.v(TAG, "  null");
6897                            }
6898                        }
6899                        if (ai == null) {
6900                            // This previously registered preferred activity
6901                            // component is no longer known.  Most likely an update
6902                            // to the app was installed and in the new version this
6903                            // component no longer exists.  Clean it up by removing
6904                            // it from the preferred activities list, and skip it.
6905                            Slog.w(TAG, "Removing dangling preferred activity: "
6906                                    + pa.mPref.mComponent);
6907                            pir.removeFilter(pa);
6908                            changed = true;
6909                            continue;
6910                        }
6911                        for (int j=0; j<N; j++) {
6912                            final ResolveInfo ri = query.get(j);
6913                            if (!ri.activityInfo.applicationInfo.packageName
6914                                    .equals(ai.applicationInfo.packageName)) {
6915                                continue;
6916                            }
6917                            if (!ri.activityInfo.name.equals(ai.name)) {
6918                                continue;
6919                            }
6920
6921                            if (removeMatches) {
6922                                pir.removeFilter(pa);
6923                                changed = true;
6924                                if (DEBUG_PREFERRED) {
6925                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6926                                }
6927                                break;
6928                            }
6929
6930                            // Okay we found a previously set preferred or last chosen app.
6931                            // If the result set is different from when this
6932                            // was created, and is not a subset of the preferred set, we need to
6933                            // clear it and re-ask the user their preference, if we're looking for
6934                            // an "always" type entry.
6935                            if (always && !pa.mPref.sameSet(query)) {
6936                                if (pa.mPref.isSuperset(query)) {
6937                                    // some components of the set are no longer present in
6938                                    // the query, but the preferred activity can still be reused
6939                                    if (DEBUG_PREFERRED) {
6940                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6941                                                + " still valid as only non-preferred components"
6942                                                + " were removed for " + intent + " type "
6943                                                + resolvedType);
6944                                    }
6945                                    // remove obsolete components and re-add the up-to-date filter
6946                                    PreferredActivity freshPa = new PreferredActivity(pa,
6947                                            pa.mPref.mMatch,
6948                                            pa.mPref.discardObsoleteComponents(query),
6949                                            pa.mPref.mComponent,
6950                                            pa.mPref.mAlways);
6951                                    pir.removeFilter(pa);
6952                                    pir.addFilter(freshPa);
6953                                    changed = true;
6954                                } else {
6955                                    Slog.i(TAG,
6956                                            "Result set changed, dropping preferred activity for "
6957                                                    + intent + " type " + resolvedType);
6958                                    if (DEBUG_PREFERRED) {
6959                                        Slog.v(TAG, "Removing preferred activity since set changed "
6960                                                + pa.mPref.mComponent);
6961                                    }
6962                                    pir.removeFilter(pa);
6963                                    // Re-add the filter as a "last chosen" entry (!always)
6964                                    PreferredActivity lastChosen = new PreferredActivity(
6965                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6966                                    pir.addFilter(lastChosen);
6967                                    changed = true;
6968                                    return null;
6969                                }
6970                            }
6971
6972                            // Yay! Either the set matched or we're looking for the last chosen
6973                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6974                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6975                            return ri;
6976                        }
6977                    }
6978                } finally {
6979                    if (changed) {
6980                        if (DEBUG_PREFERRED) {
6981                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6982                        }
6983                        scheduleWritePackageRestrictionsLocked(userId);
6984                    }
6985                }
6986            }
6987        }
6988        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6989        return null;
6990    }
6991
6992    /*
6993     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6994     */
6995    @Override
6996    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6997            int targetUserId) {
6998        mContext.enforceCallingOrSelfPermission(
6999                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7000        List<CrossProfileIntentFilter> matches =
7001                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7002        if (matches != null) {
7003            int size = matches.size();
7004            for (int i = 0; i < size; i++) {
7005                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7006            }
7007        }
7008        if (hasWebURI(intent)) {
7009            // cross-profile app linking works only towards the parent.
7010            final int callingUid = Binder.getCallingUid();
7011            final UserInfo parent = getProfileParent(sourceUserId);
7012            synchronized(mPackages) {
7013                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7014                        false /*includeInstantApps*/);
7015                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7016                        intent, resolvedType, flags, sourceUserId, parent.id);
7017                return xpDomainInfo != null;
7018            }
7019        }
7020        return false;
7021    }
7022
7023    private UserInfo getProfileParent(int userId) {
7024        final long identity = Binder.clearCallingIdentity();
7025        try {
7026            return sUserManager.getProfileParent(userId);
7027        } finally {
7028            Binder.restoreCallingIdentity(identity);
7029        }
7030    }
7031
7032    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7033            String resolvedType, int userId) {
7034        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7035        if (resolver != null) {
7036            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7037        }
7038        return null;
7039    }
7040
7041    @Override
7042    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7043            String resolvedType, int flags, int userId) {
7044        try {
7045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7046
7047            return new ParceledListSlice<>(
7048                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7049        } finally {
7050            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7051        }
7052    }
7053
7054    /**
7055     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7056     * instant, returns {@code null}.
7057     */
7058    private String getInstantAppPackageName(int callingUid) {
7059        synchronized (mPackages) {
7060            // If the caller is an isolated app use the owner's uid for the lookup.
7061            if (Process.isIsolated(callingUid)) {
7062                callingUid = mIsolatedOwners.get(callingUid);
7063            }
7064            final int appId = UserHandle.getAppId(callingUid);
7065            final Object obj = mSettings.getUserIdLPr(appId);
7066            if (obj instanceof PackageSetting) {
7067                final PackageSetting ps = (PackageSetting) obj;
7068                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7069                return isInstantApp ? ps.pkg.packageName : null;
7070            }
7071        }
7072        return null;
7073    }
7074
7075    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7076            String resolvedType, int flags, int userId) {
7077        return queryIntentActivitiesInternal(
7078                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7079                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7080    }
7081
7082    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7083            String resolvedType, int flags, int filterCallingUid, int userId,
7084            boolean resolveForStart, boolean allowDynamicSplits) {
7085        if (!sUserManager.exists(userId)) return Collections.emptyList();
7086        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7087        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7088                false /* requireFullPermission */, false /* checkShell */,
7089                "query intent activities");
7090        final String pkgName = intent.getPackage();
7091        ComponentName comp = intent.getComponent();
7092        if (comp == null) {
7093            if (intent.getSelector() != null) {
7094                intent = intent.getSelector();
7095                comp = intent.getComponent();
7096            }
7097        }
7098
7099        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7100                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7101        if (comp != null) {
7102            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7103            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7104            if (ai != null) {
7105                // When specifying an explicit component, we prevent the activity from being
7106                // used when either 1) the calling package is normal and the activity is within
7107                // an ephemeral application or 2) the calling package is ephemeral and the
7108                // activity is not visible to ephemeral applications.
7109                final boolean matchInstantApp =
7110                        (flags & PackageManager.MATCH_INSTANT) != 0;
7111                final boolean matchVisibleToInstantAppOnly =
7112                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7113                final boolean matchExplicitlyVisibleOnly =
7114                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7115                final boolean isCallerInstantApp =
7116                        instantAppPkgName != null;
7117                final boolean isTargetSameInstantApp =
7118                        comp.getPackageName().equals(instantAppPkgName);
7119                final boolean isTargetInstantApp =
7120                        (ai.applicationInfo.privateFlags
7121                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7122                final boolean isTargetVisibleToInstantApp =
7123                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7124                final boolean isTargetExplicitlyVisibleToInstantApp =
7125                        isTargetVisibleToInstantApp
7126                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7127                final boolean isTargetHiddenFromInstantApp =
7128                        !isTargetVisibleToInstantApp
7129                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7130                final boolean blockResolution =
7131                        !isTargetSameInstantApp
7132                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7133                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7134                                        && isTargetHiddenFromInstantApp));
7135                if (!blockResolution) {
7136                    final ResolveInfo ri = new ResolveInfo();
7137                    ri.activityInfo = ai;
7138                    list.add(ri);
7139                }
7140            }
7141            return applyPostResolutionFilter(
7142                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7143        }
7144
7145        // reader
7146        boolean sortResult = false;
7147        boolean addEphemeral = false;
7148        List<ResolveInfo> result;
7149        final boolean ephemeralDisabled = isEphemeralDisabled();
7150        synchronized (mPackages) {
7151            if (pkgName == null) {
7152                List<CrossProfileIntentFilter> matchingFilters =
7153                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7154                // Check for results that need to skip the current profile.
7155                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7156                        resolvedType, flags, userId);
7157                if (xpResolveInfo != null) {
7158                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7159                    xpResult.add(xpResolveInfo);
7160                    return applyPostResolutionFilter(
7161                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7162                            allowDynamicSplits, filterCallingUid, userId);
7163                }
7164
7165                // Check for results in the current profile.
7166                result = filterIfNotSystemUser(mActivities.queryIntent(
7167                        intent, resolvedType, flags, userId), userId);
7168                addEphemeral = !ephemeralDisabled
7169                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7170                // Check for cross profile results.
7171                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7172                xpResolveInfo = queryCrossProfileIntents(
7173                        matchingFilters, intent, resolvedType, flags, userId,
7174                        hasNonNegativePriorityResult);
7175                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7176                    boolean isVisibleToUser = filterIfNotSystemUser(
7177                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7178                    if (isVisibleToUser) {
7179                        result.add(xpResolveInfo);
7180                        sortResult = true;
7181                    }
7182                }
7183                if (hasWebURI(intent)) {
7184                    CrossProfileDomainInfo xpDomainInfo = null;
7185                    final UserInfo parent = getProfileParent(userId);
7186                    if (parent != null) {
7187                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7188                                flags, userId, parent.id);
7189                    }
7190                    if (xpDomainInfo != null) {
7191                        if (xpResolveInfo != null) {
7192                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7193                            // in the result.
7194                            result.remove(xpResolveInfo);
7195                        }
7196                        if (result.size() == 0 && !addEphemeral) {
7197                            // No result in current profile, but found candidate in parent user.
7198                            // And we are not going to add emphemeral app, so we can return the
7199                            // result straight away.
7200                            result.add(xpDomainInfo.resolveInfo);
7201                            return applyPostResolutionFilter(result, instantAppPkgName,
7202                                    allowDynamicSplits, filterCallingUid, userId);
7203                        }
7204                    } else if (result.size() <= 1 && !addEphemeral) {
7205                        // No result in parent user and <= 1 result in current profile, and we
7206                        // are not going to add emphemeral app, so we can return the result without
7207                        // further processing.
7208                        return applyPostResolutionFilter(result, instantAppPkgName,
7209                                allowDynamicSplits, filterCallingUid, userId);
7210                    }
7211                    // We have more than one candidate (combining results from current and parent
7212                    // profile), so we need filtering and sorting.
7213                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7214                            intent, flags, result, xpDomainInfo, userId);
7215                    sortResult = true;
7216                }
7217            } else {
7218                final PackageParser.Package pkg = mPackages.get(pkgName);
7219                result = null;
7220                if (pkg != null) {
7221                    result = filterIfNotSystemUser(
7222                            mActivities.queryIntentForPackage(
7223                                    intent, resolvedType, flags, pkg.activities, userId),
7224                            userId);
7225                }
7226                if (result == null || result.size() == 0) {
7227                    // the caller wants to resolve for a particular package; however, there
7228                    // were no installed results, so, try to find an ephemeral result
7229                    addEphemeral = !ephemeralDisabled
7230                            && isInstantAppAllowed(
7231                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7232                    if (result == null) {
7233                        result = new ArrayList<>();
7234                    }
7235                }
7236            }
7237        }
7238        if (addEphemeral) {
7239            result = maybeAddInstantAppInstaller(
7240                    result, intent, resolvedType, flags, userId, resolveForStart);
7241        }
7242        if (sortResult) {
7243            Collections.sort(result, mResolvePrioritySorter);
7244        }
7245        return applyPostResolutionFilter(
7246                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7247    }
7248
7249    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7250            String resolvedType, int flags, int userId, boolean resolveForStart) {
7251        // first, check to see if we've got an instant app already installed
7252        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7253        ResolveInfo localInstantApp = null;
7254        boolean blockResolution = false;
7255        if (!alreadyResolvedLocally) {
7256            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7257                    flags
7258                        | PackageManager.GET_RESOLVED_FILTER
7259                        | PackageManager.MATCH_INSTANT
7260                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7261                    userId);
7262            for (int i = instantApps.size() - 1; i >= 0; --i) {
7263                final ResolveInfo info = instantApps.get(i);
7264                final String packageName = info.activityInfo.packageName;
7265                final PackageSetting ps = mSettings.mPackages.get(packageName);
7266                if (ps.getInstantApp(userId)) {
7267                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7268                    final int status = (int)(packedStatus >> 32);
7269                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7270                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7271                        // there's a local instant application installed, but, the user has
7272                        // chosen to never use it; skip resolution and don't acknowledge
7273                        // an instant application is even available
7274                        if (DEBUG_EPHEMERAL) {
7275                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7276                        }
7277                        blockResolution = true;
7278                        break;
7279                    } else {
7280                        // we have a locally installed instant application; skip resolution
7281                        // but acknowledge there's an instant application available
7282                        if (DEBUG_EPHEMERAL) {
7283                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7284                        }
7285                        localInstantApp = info;
7286                        break;
7287                    }
7288                }
7289            }
7290        }
7291        // no app installed, let's see if one's available
7292        AuxiliaryResolveInfo auxiliaryResponse = null;
7293        if (!blockResolution) {
7294            if (localInstantApp == null) {
7295                // we don't have an instant app locally, resolve externally
7296                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7297                final InstantAppRequest requestObject = new InstantAppRequest(
7298                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7299                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7300                        resolveForStart);
7301                auxiliaryResponse =
7302                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7303                                mContext, mInstantAppResolverConnection, requestObject);
7304                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7305            } else {
7306                // we have an instant application locally, but, we can't admit that since
7307                // callers shouldn't be able to determine prior browsing. create a dummy
7308                // auxiliary response so the downstream code behaves as if there's an
7309                // instant application available externally. when it comes time to start
7310                // the instant application, we'll do the right thing.
7311                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7312                auxiliaryResponse = new AuxiliaryResolveInfo(
7313                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7314                        ai.versionCode, null /*failureIntent*/);
7315            }
7316        }
7317        if (auxiliaryResponse != null) {
7318            if (DEBUG_EPHEMERAL) {
7319                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7320            }
7321            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7322            final PackageSetting ps =
7323                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7324            if (ps != null) {
7325                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7326                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7327                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7328                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7329                // make sure this resolver is the default
7330                ephemeralInstaller.isDefault = true;
7331                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7332                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7333                // add a non-generic filter
7334                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7335                ephemeralInstaller.filter.addDataPath(
7336                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7337                ephemeralInstaller.isInstantAppAvailable = true;
7338                result.add(ephemeralInstaller);
7339            }
7340        }
7341        return result;
7342    }
7343
7344    private static class CrossProfileDomainInfo {
7345        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7346        ResolveInfo resolveInfo;
7347        /* Best domain verification status of the activities found in the other profile */
7348        int bestDomainVerificationStatus;
7349    }
7350
7351    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7352            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7353        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7354                sourceUserId)) {
7355            return null;
7356        }
7357        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7358                resolvedType, flags, parentUserId);
7359
7360        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7361            return null;
7362        }
7363        CrossProfileDomainInfo result = null;
7364        int size = resultTargetUser.size();
7365        for (int i = 0; i < size; i++) {
7366            ResolveInfo riTargetUser = resultTargetUser.get(i);
7367            // Intent filter verification is only for filters that specify a host. So don't return
7368            // those that handle all web uris.
7369            if (riTargetUser.handleAllWebDataURI) {
7370                continue;
7371            }
7372            String packageName = riTargetUser.activityInfo.packageName;
7373            PackageSetting ps = mSettings.mPackages.get(packageName);
7374            if (ps == null) {
7375                continue;
7376            }
7377            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7378            int status = (int)(verificationState >> 32);
7379            if (result == null) {
7380                result = new CrossProfileDomainInfo();
7381                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7382                        sourceUserId, parentUserId);
7383                result.bestDomainVerificationStatus = status;
7384            } else {
7385                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7386                        result.bestDomainVerificationStatus);
7387            }
7388        }
7389        // Don't consider matches with status NEVER across profiles.
7390        if (result != null && result.bestDomainVerificationStatus
7391                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7392            return null;
7393        }
7394        return result;
7395    }
7396
7397    /**
7398     * Verification statuses are ordered from the worse to the best, except for
7399     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7400     */
7401    private int bestDomainVerificationStatus(int status1, int status2) {
7402        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7403            return status2;
7404        }
7405        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7406            return status1;
7407        }
7408        return (int) MathUtils.max(status1, status2);
7409    }
7410
7411    private boolean isUserEnabled(int userId) {
7412        long callingId = Binder.clearCallingIdentity();
7413        try {
7414            UserInfo userInfo = sUserManager.getUserInfo(userId);
7415            return userInfo != null && userInfo.isEnabled();
7416        } finally {
7417            Binder.restoreCallingIdentity(callingId);
7418        }
7419    }
7420
7421    /**
7422     * Filter out activities with systemUserOnly flag set, when current user is not System.
7423     *
7424     * @return filtered list
7425     */
7426    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7427        if (userId == UserHandle.USER_SYSTEM) {
7428            return resolveInfos;
7429        }
7430        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7431            ResolveInfo info = resolveInfos.get(i);
7432            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7433                resolveInfos.remove(i);
7434            }
7435        }
7436        return resolveInfos;
7437    }
7438
7439    /**
7440     * Filters out ephemeral activities.
7441     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7442     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7443     *
7444     * @param resolveInfos The pre-filtered list of resolved activities
7445     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7446     *          is performed.
7447     * @return A filtered list of resolved activities.
7448     */
7449    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7450            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7451        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7452            final ResolveInfo info = resolveInfos.get(i);
7453            // allow activities that are defined in the provided package
7454            if (allowDynamicSplits
7455                    && info.activityInfo.splitName != null
7456                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7457                            info.activityInfo.splitName)) {
7458                // requested activity is defined in a split that hasn't been installed yet.
7459                // add the installer to the resolve list
7460                if (DEBUG_INSTALL) {
7461                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7462                }
7463                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7464                final ComponentName installFailureActivity = findInstallFailureActivity(
7465                        info.activityInfo.packageName,  filterCallingUid, userId);
7466                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7467                        info.activityInfo.packageName, info.activityInfo.splitName,
7468                        installFailureActivity,
7469                        info.activityInfo.applicationInfo.versionCode,
7470                        null /*failureIntent*/);
7471                // make sure this resolver is the default
7472                installerInfo.isDefault = true;
7473                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7474                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7475                // add a non-generic filter
7476                installerInfo.filter = new IntentFilter();
7477                // load resources from the correct package
7478                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7479                resolveInfos.set(i, installerInfo);
7480                continue;
7481            }
7482            // caller is a full app, don't need to apply any other filtering
7483            if (ephemeralPkgName == null) {
7484                continue;
7485            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7486                // caller is same app; don't need to apply any other filtering
7487                continue;
7488            }
7489            // allow activities that have been explicitly exposed to ephemeral apps
7490            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7491            if (!isEphemeralApp
7492                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7493                continue;
7494            }
7495            resolveInfos.remove(i);
7496        }
7497        return resolveInfos;
7498    }
7499
7500    /**
7501     * Returns the activity component that can handle install failures.
7502     * <p>By default, the instant application installer handles failures. However, an
7503     * application may want to handle failures on its own. Applications do this by
7504     * creating an activity with an intent filter that handles the action
7505     * {@link Intent#ACTION_INSTALL_FAILURE}.
7506     */
7507    private @Nullable ComponentName findInstallFailureActivity(
7508            String packageName, int filterCallingUid, int userId) {
7509        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7510        failureActivityIntent.setPackage(packageName);
7511        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7512        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7513                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7514                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7515        final int NR = result.size();
7516        if (NR > 0) {
7517            for (int i = 0; i < NR; i++) {
7518                final ResolveInfo info = result.get(i);
7519                if (info.activityInfo.splitName != null) {
7520                    continue;
7521                }
7522                return new ComponentName(packageName, info.activityInfo.name);
7523            }
7524        }
7525        return null;
7526    }
7527
7528    /**
7529     * @param resolveInfos list of resolve infos in descending priority order
7530     * @return if the list contains a resolve info with non-negative priority
7531     */
7532    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7533        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7534    }
7535
7536    private static boolean hasWebURI(Intent intent) {
7537        if (intent.getData() == null) {
7538            return false;
7539        }
7540        final String scheme = intent.getScheme();
7541        if (TextUtils.isEmpty(scheme)) {
7542            return false;
7543        }
7544        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7545    }
7546
7547    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7548            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7549            int userId) {
7550        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7551
7552        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7553            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7554                    candidates.size());
7555        }
7556
7557        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7558        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7559        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7560        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7561        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7562        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7563
7564        synchronized (mPackages) {
7565            final int count = candidates.size();
7566            // First, try to use linked apps. Partition the candidates into four lists:
7567            // one for the final results, one for the "do not use ever", one for "undefined status"
7568            // and finally one for "browser app type".
7569            for (int n=0; n<count; n++) {
7570                ResolveInfo info = candidates.get(n);
7571                String packageName = info.activityInfo.packageName;
7572                PackageSetting ps = mSettings.mPackages.get(packageName);
7573                if (ps != null) {
7574                    // Add to the special match all list (Browser use case)
7575                    if (info.handleAllWebDataURI) {
7576                        matchAllList.add(info);
7577                        continue;
7578                    }
7579                    // Try to get the status from User settings first
7580                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7581                    int status = (int)(packedStatus >> 32);
7582                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7583                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7584                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7585                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7586                                    + " : linkgen=" + linkGeneration);
7587                        }
7588                        // Use link-enabled generation as preferredOrder, i.e.
7589                        // prefer newly-enabled over earlier-enabled.
7590                        info.preferredOrder = linkGeneration;
7591                        alwaysList.add(info);
7592                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7593                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7594                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7595                        }
7596                        neverList.add(info);
7597                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7598                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7599                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7600                        }
7601                        alwaysAskList.add(info);
7602                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7603                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7604                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7605                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7606                        }
7607                        undefinedList.add(info);
7608                    }
7609                }
7610            }
7611
7612            // We'll want to include browser possibilities in a few cases
7613            boolean includeBrowser = false;
7614
7615            // First try to add the "always" resolution(s) for the current user, if any
7616            if (alwaysList.size() > 0) {
7617                result.addAll(alwaysList);
7618            } else {
7619                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7620                result.addAll(undefinedList);
7621                // Maybe add one for the other profile.
7622                if (xpDomainInfo != null && (
7623                        xpDomainInfo.bestDomainVerificationStatus
7624                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7625                    result.add(xpDomainInfo.resolveInfo);
7626                }
7627                includeBrowser = true;
7628            }
7629
7630            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7631            // If there were 'always' entries their preferred order has been set, so we also
7632            // back that off to make the alternatives equivalent
7633            if (alwaysAskList.size() > 0) {
7634                for (ResolveInfo i : result) {
7635                    i.preferredOrder = 0;
7636                }
7637                result.addAll(alwaysAskList);
7638                includeBrowser = true;
7639            }
7640
7641            if (includeBrowser) {
7642                // Also add browsers (all of them or only the default one)
7643                if (DEBUG_DOMAIN_VERIFICATION) {
7644                    Slog.v(TAG, "   ...including browsers in candidate set");
7645                }
7646                if ((matchFlags & MATCH_ALL) != 0) {
7647                    result.addAll(matchAllList);
7648                } else {
7649                    // Browser/generic handling case.  If there's a default browser, go straight
7650                    // to that (but only if there is no other higher-priority match).
7651                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7652                    int maxMatchPrio = 0;
7653                    ResolveInfo defaultBrowserMatch = null;
7654                    final int numCandidates = matchAllList.size();
7655                    for (int n = 0; n < numCandidates; n++) {
7656                        ResolveInfo info = matchAllList.get(n);
7657                        // track the highest overall match priority...
7658                        if (info.priority > maxMatchPrio) {
7659                            maxMatchPrio = info.priority;
7660                        }
7661                        // ...and the highest-priority default browser match
7662                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7663                            if (defaultBrowserMatch == null
7664                                    || (defaultBrowserMatch.priority < info.priority)) {
7665                                if (debug) {
7666                                    Slog.v(TAG, "Considering default browser match " + info);
7667                                }
7668                                defaultBrowserMatch = info;
7669                            }
7670                        }
7671                    }
7672                    if (defaultBrowserMatch != null
7673                            && defaultBrowserMatch.priority >= maxMatchPrio
7674                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7675                    {
7676                        if (debug) {
7677                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7678                        }
7679                        result.add(defaultBrowserMatch);
7680                    } else {
7681                        result.addAll(matchAllList);
7682                    }
7683                }
7684
7685                // If there is nothing selected, add all candidates and remove the ones that the user
7686                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7687                if (result.size() == 0) {
7688                    result.addAll(candidates);
7689                    result.removeAll(neverList);
7690                }
7691            }
7692        }
7693        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7694            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7695                    result.size());
7696            for (ResolveInfo info : result) {
7697                Slog.v(TAG, "  + " + info.activityInfo);
7698            }
7699        }
7700        return result;
7701    }
7702
7703    // Returns a packed value as a long:
7704    //
7705    // high 'int'-sized word: link status: undefined/ask/never/always.
7706    // low 'int'-sized word: relative priority among 'always' results.
7707    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7708        long result = ps.getDomainVerificationStatusForUser(userId);
7709        // if none available, get the master status
7710        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7711            if (ps.getIntentFilterVerificationInfo() != null) {
7712                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7713            }
7714        }
7715        return result;
7716    }
7717
7718    private ResolveInfo querySkipCurrentProfileIntents(
7719            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7720            int flags, int sourceUserId) {
7721        if (matchingFilters != null) {
7722            int size = matchingFilters.size();
7723            for (int i = 0; i < size; i ++) {
7724                CrossProfileIntentFilter filter = matchingFilters.get(i);
7725                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7726                    // Checking if there are activities in the target user that can handle the
7727                    // intent.
7728                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7729                            resolvedType, flags, sourceUserId);
7730                    if (resolveInfo != null) {
7731                        return resolveInfo;
7732                    }
7733                }
7734            }
7735        }
7736        return null;
7737    }
7738
7739    // Return matching ResolveInfo in target user if any.
7740    private ResolveInfo queryCrossProfileIntents(
7741            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7742            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7743        if (matchingFilters != null) {
7744            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7745            // match the same intent. For performance reasons, it is better not to
7746            // run queryIntent twice for the same userId
7747            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7748            int size = matchingFilters.size();
7749            for (int i = 0; i < size; i++) {
7750                CrossProfileIntentFilter filter = matchingFilters.get(i);
7751                int targetUserId = filter.getTargetUserId();
7752                boolean skipCurrentProfile =
7753                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7754                boolean skipCurrentProfileIfNoMatchFound =
7755                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7756                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7757                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7758                    // Checking if there are activities in the target user that can handle the
7759                    // intent.
7760                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7761                            resolvedType, flags, sourceUserId);
7762                    if (resolveInfo != null) return resolveInfo;
7763                    alreadyTriedUserIds.put(targetUserId, true);
7764                }
7765            }
7766        }
7767        return null;
7768    }
7769
7770    /**
7771     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7772     * will forward the intent to the filter's target user.
7773     * Otherwise, returns null.
7774     */
7775    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7776            String resolvedType, int flags, int sourceUserId) {
7777        int targetUserId = filter.getTargetUserId();
7778        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7779                resolvedType, flags, targetUserId);
7780        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7781            // If all the matches in the target profile are suspended, return null.
7782            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7783                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7784                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7785                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7786                            targetUserId);
7787                }
7788            }
7789        }
7790        return null;
7791    }
7792
7793    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7794            int sourceUserId, int targetUserId) {
7795        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7796        long ident = Binder.clearCallingIdentity();
7797        boolean targetIsProfile;
7798        try {
7799            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7800        } finally {
7801            Binder.restoreCallingIdentity(ident);
7802        }
7803        String className;
7804        if (targetIsProfile) {
7805            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7806        } else {
7807            className = FORWARD_INTENT_TO_PARENT;
7808        }
7809        ComponentName forwardingActivityComponentName = new ComponentName(
7810                mAndroidApplication.packageName, className);
7811        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7812                sourceUserId);
7813        if (!targetIsProfile) {
7814            forwardingActivityInfo.showUserIcon = targetUserId;
7815            forwardingResolveInfo.noResourceId = true;
7816        }
7817        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7818        forwardingResolveInfo.priority = 0;
7819        forwardingResolveInfo.preferredOrder = 0;
7820        forwardingResolveInfo.match = 0;
7821        forwardingResolveInfo.isDefault = true;
7822        forwardingResolveInfo.filter = filter;
7823        forwardingResolveInfo.targetUserId = targetUserId;
7824        return forwardingResolveInfo;
7825    }
7826
7827    @Override
7828    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7829            Intent[] specifics, String[] specificTypes, Intent intent,
7830            String resolvedType, int flags, int userId) {
7831        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7832                specificTypes, intent, resolvedType, flags, userId));
7833    }
7834
7835    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7836            Intent[] specifics, String[] specificTypes, Intent intent,
7837            String resolvedType, int flags, int userId) {
7838        if (!sUserManager.exists(userId)) return Collections.emptyList();
7839        final int callingUid = Binder.getCallingUid();
7840        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7841                false /*includeInstantApps*/);
7842        enforceCrossUserPermission(callingUid, userId,
7843                false /*requireFullPermission*/, false /*checkShell*/,
7844                "query intent activity options");
7845        final String resultsAction = intent.getAction();
7846
7847        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7848                | PackageManager.GET_RESOLVED_FILTER, userId);
7849
7850        if (DEBUG_INTENT_MATCHING) {
7851            Log.v(TAG, "Query " + intent + ": " + results);
7852        }
7853
7854        int specificsPos = 0;
7855        int N;
7856
7857        // todo: note that the algorithm used here is O(N^2).  This
7858        // isn't a problem in our current environment, but if we start running
7859        // into situations where we have more than 5 or 10 matches then this
7860        // should probably be changed to something smarter...
7861
7862        // First we go through and resolve each of the specific items
7863        // that were supplied, taking care of removing any corresponding
7864        // duplicate items in the generic resolve list.
7865        if (specifics != null) {
7866            for (int i=0; i<specifics.length; i++) {
7867                final Intent sintent = specifics[i];
7868                if (sintent == null) {
7869                    continue;
7870                }
7871
7872                if (DEBUG_INTENT_MATCHING) {
7873                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7874                }
7875
7876                String action = sintent.getAction();
7877                if (resultsAction != null && resultsAction.equals(action)) {
7878                    // If this action was explicitly requested, then don't
7879                    // remove things that have it.
7880                    action = null;
7881                }
7882
7883                ResolveInfo ri = null;
7884                ActivityInfo ai = null;
7885
7886                ComponentName comp = sintent.getComponent();
7887                if (comp == null) {
7888                    ri = resolveIntent(
7889                        sintent,
7890                        specificTypes != null ? specificTypes[i] : null,
7891                            flags, userId);
7892                    if (ri == null) {
7893                        continue;
7894                    }
7895                    if (ri == mResolveInfo) {
7896                        // ACK!  Must do something better with this.
7897                    }
7898                    ai = ri.activityInfo;
7899                    comp = new ComponentName(ai.applicationInfo.packageName,
7900                            ai.name);
7901                } else {
7902                    ai = getActivityInfo(comp, flags, userId);
7903                    if (ai == null) {
7904                        continue;
7905                    }
7906                }
7907
7908                // Look for any generic query activities that are duplicates
7909                // of this specific one, and remove them from the results.
7910                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7911                N = results.size();
7912                int j;
7913                for (j=specificsPos; j<N; j++) {
7914                    ResolveInfo sri = results.get(j);
7915                    if ((sri.activityInfo.name.equals(comp.getClassName())
7916                            && sri.activityInfo.applicationInfo.packageName.equals(
7917                                    comp.getPackageName()))
7918                        || (action != null && sri.filter.matchAction(action))) {
7919                        results.remove(j);
7920                        if (DEBUG_INTENT_MATCHING) Log.v(
7921                            TAG, "Removing duplicate item from " + j
7922                            + " due to specific " + specificsPos);
7923                        if (ri == null) {
7924                            ri = sri;
7925                        }
7926                        j--;
7927                        N--;
7928                    }
7929                }
7930
7931                // Add this specific item to its proper place.
7932                if (ri == null) {
7933                    ri = new ResolveInfo();
7934                    ri.activityInfo = ai;
7935                }
7936                results.add(specificsPos, ri);
7937                ri.specificIndex = i;
7938                specificsPos++;
7939            }
7940        }
7941
7942        // Now we go through the remaining generic results and remove any
7943        // duplicate actions that are found here.
7944        N = results.size();
7945        for (int i=specificsPos; i<N-1; i++) {
7946            final ResolveInfo rii = results.get(i);
7947            if (rii.filter == null) {
7948                continue;
7949            }
7950
7951            // Iterate over all of the actions of this result's intent
7952            // filter...  typically this should be just one.
7953            final Iterator<String> it = rii.filter.actionsIterator();
7954            if (it == null) {
7955                continue;
7956            }
7957            while (it.hasNext()) {
7958                final String action = it.next();
7959                if (resultsAction != null && resultsAction.equals(action)) {
7960                    // If this action was explicitly requested, then don't
7961                    // remove things that have it.
7962                    continue;
7963                }
7964                for (int j=i+1; j<N; j++) {
7965                    final ResolveInfo rij = results.get(j);
7966                    if (rij.filter != null && rij.filter.hasAction(action)) {
7967                        results.remove(j);
7968                        if (DEBUG_INTENT_MATCHING) Log.v(
7969                            TAG, "Removing duplicate item from " + j
7970                            + " due to action " + action + " at " + i);
7971                        j--;
7972                        N--;
7973                    }
7974                }
7975            }
7976
7977            // If the caller didn't request filter information, drop it now
7978            // so we don't have to marshall/unmarshall it.
7979            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7980                rii.filter = null;
7981            }
7982        }
7983
7984        // Filter out the caller activity if so requested.
7985        if (caller != null) {
7986            N = results.size();
7987            for (int i=0; i<N; i++) {
7988                ActivityInfo ainfo = results.get(i).activityInfo;
7989                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7990                        && caller.getClassName().equals(ainfo.name)) {
7991                    results.remove(i);
7992                    break;
7993                }
7994            }
7995        }
7996
7997        // If the caller didn't request filter information,
7998        // drop them now so we don't have to
7999        // marshall/unmarshall it.
8000        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8001            N = results.size();
8002            for (int i=0; i<N; i++) {
8003                results.get(i).filter = null;
8004            }
8005        }
8006
8007        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8008        return results;
8009    }
8010
8011    @Override
8012    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8013            String resolvedType, int flags, int userId) {
8014        return new ParceledListSlice<>(
8015                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8016                        false /*allowDynamicSplits*/));
8017    }
8018
8019    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8020            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8021        if (!sUserManager.exists(userId)) return Collections.emptyList();
8022        final int callingUid = Binder.getCallingUid();
8023        enforceCrossUserPermission(callingUid, userId,
8024                false /*requireFullPermission*/, false /*checkShell*/,
8025                "query intent receivers");
8026        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8027        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8028                false /*includeInstantApps*/);
8029        ComponentName comp = intent.getComponent();
8030        if (comp == null) {
8031            if (intent.getSelector() != null) {
8032                intent = intent.getSelector();
8033                comp = intent.getComponent();
8034            }
8035        }
8036        if (comp != null) {
8037            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8038            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8039            if (ai != null) {
8040                // When specifying an explicit component, we prevent the activity from being
8041                // used when either 1) the calling package is normal and the activity is within
8042                // an instant application or 2) the calling package is ephemeral and the
8043                // activity is not visible to instant applications.
8044                final boolean matchInstantApp =
8045                        (flags & PackageManager.MATCH_INSTANT) != 0;
8046                final boolean matchVisibleToInstantAppOnly =
8047                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8048                final boolean matchExplicitlyVisibleOnly =
8049                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8050                final boolean isCallerInstantApp =
8051                        instantAppPkgName != null;
8052                final boolean isTargetSameInstantApp =
8053                        comp.getPackageName().equals(instantAppPkgName);
8054                final boolean isTargetInstantApp =
8055                        (ai.applicationInfo.privateFlags
8056                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8057                final boolean isTargetVisibleToInstantApp =
8058                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8059                final boolean isTargetExplicitlyVisibleToInstantApp =
8060                        isTargetVisibleToInstantApp
8061                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8062                final boolean isTargetHiddenFromInstantApp =
8063                        !isTargetVisibleToInstantApp
8064                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8065                final boolean blockResolution =
8066                        !isTargetSameInstantApp
8067                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8068                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8069                                        && isTargetHiddenFromInstantApp));
8070                if (!blockResolution) {
8071                    ResolveInfo ri = new ResolveInfo();
8072                    ri.activityInfo = ai;
8073                    list.add(ri);
8074                }
8075            }
8076            return applyPostResolutionFilter(
8077                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8078        }
8079
8080        // reader
8081        synchronized (mPackages) {
8082            String pkgName = intent.getPackage();
8083            if (pkgName == null) {
8084                final List<ResolveInfo> result =
8085                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8086                return applyPostResolutionFilter(
8087                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8088            }
8089            final PackageParser.Package pkg = mPackages.get(pkgName);
8090            if (pkg != null) {
8091                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8092                        intent, resolvedType, flags, pkg.receivers, userId);
8093                return applyPostResolutionFilter(
8094                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8095            }
8096            return Collections.emptyList();
8097        }
8098    }
8099
8100    @Override
8101    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8102        final int callingUid = Binder.getCallingUid();
8103        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8104    }
8105
8106    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8107            int userId, int callingUid) {
8108        if (!sUserManager.exists(userId)) return null;
8109        flags = updateFlagsForResolve(
8110                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8111        List<ResolveInfo> query = queryIntentServicesInternal(
8112                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8113        if (query != null) {
8114            if (query.size() >= 1) {
8115                // If there is more than one service with the same priority,
8116                // just arbitrarily pick the first one.
8117                return query.get(0);
8118            }
8119        }
8120        return null;
8121    }
8122
8123    @Override
8124    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8125            String resolvedType, int flags, int userId) {
8126        final int callingUid = Binder.getCallingUid();
8127        return new ParceledListSlice<>(queryIntentServicesInternal(
8128                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8129    }
8130
8131    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8132            String resolvedType, int flags, int userId, int callingUid,
8133            boolean includeInstantApps) {
8134        if (!sUserManager.exists(userId)) return Collections.emptyList();
8135        enforceCrossUserPermission(callingUid, userId,
8136                false /*requireFullPermission*/, false /*checkShell*/,
8137                "query intent receivers");
8138        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8139        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8140        ComponentName comp = intent.getComponent();
8141        if (comp == null) {
8142            if (intent.getSelector() != null) {
8143                intent = intent.getSelector();
8144                comp = intent.getComponent();
8145            }
8146        }
8147        if (comp != null) {
8148            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8149            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8150            if (si != null) {
8151                // When specifying an explicit component, we prevent the service from being
8152                // used when either 1) the service is in an instant application and the
8153                // caller is not the same instant application or 2) the calling package is
8154                // ephemeral and the activity is not visible to ephemeral applications.
8155                final boolean matchInstantApp =
8156                        (flags & PackageManager.MATCH_INSTANT) != 0;
8157                final boolean matchVisibleToInstantAppOnly =
8158                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8159                final boolean isCallerInstantApp =
8160                        instantAppPkgName != null;
8161                final boolean isTargetSameInstantApp =
8162                        comp.getPackageName().equals(instantAppPkgName);
8163                final boolean isTargetInstantApp =
8164                        (si.applicationInfo.privateFlags
8165                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8166                final boolean isTargetHiddenFromInstantApp =
8167                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8168                final boolean blockResolution =
8169                        !isTargetSameInstantApp
8170                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8171                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8172                                        && isTargetHiddenFromInstantApp));
8173                if (!blockResolution) {
8174                    final ResolveInfo ri = new ResolveInfo();
8175                    ri.serviceInfo = si;
8176                    list.add(ri);
8177                }
8178            }
8179            return list;
8180        }
8181
8182        // reader
8183        synchronized (mPackages) {
8184            String pkgName = intent.getPackage();
8185            if (pkgName == null) {
8186                return applyPostServiceResolutionFilter(
8187                        mServices.queryIntent(intent, resolvedType, flags, userId),
8188                        instantAppPkgName);
8189            }
8190            final PackageParser.Package pkg = mPackages.get(pkgName);
8191            if (pkg != null) {
8192                return applyPostServiceResolutionFilter(
8193                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8194                                userId),
8195                        instantAppPkgName);
8196            }
8197            return Collections.emptyList();
8198        }
8199    }
8200
8201    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8202            String instantAppPkgName) {
8203        if (instantAppPkgName == null) {
8204            return resolveInfos;
8205        }
8206        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8207            final ResolveInfo info = resolveInfos.get(i);
8208            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8209            // allow services that are defined in the provided package
8210            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8211                if (info.serviceInfo.splitName != null
8212                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8213                                info.serviceInfo.splitName)) {
8214                    // requested service is defined in a split that hasn't been installed yet.
8215                    // add the installer to the resolve list
8216                    if (DEBUG_EPHEMERAL) {
8217                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8218                    }
8219                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8220                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8221                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8222                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8223                            null /*failureIntent*/);
8224                    // make sure this resolver is the default
8225                    installerInfo.isDefault = true;
8226                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8227                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8228                    // add a non-generic filter
8229                    installerInfo.filter = new IntentFilter();
8230                    // load resources from the correct package
8231                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8232                    resolveInfos.set(i, installerInfo);
8233                }
8234                continue;
8235            }
8236            // allow services that have been explicitly exposed to ephemeral apps
8237            if (!isEphemeralApp
8238                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8239                continue;
8240            }
8241            resolveInfos.remove(i);
8242        }
8243        return resolveInfos;
8244    }
8245
8246    @Override
8247    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8248            String resolvedType, int flags, int userId) {
8249        return new ParceledListSlice<>(
8250                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8251    }
8252
8253    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8254            Intent intent, String resolvedType, int flags, int userId) {
8255        if (!sUserManager.exists(userId)) return Collections.emptyList();
8256        final int callingUid = Binder.getCallingUid();
8257        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8258        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8259                false /*includeInstantApps*/);
8260        ComponentName comp = intent.getComponent();
8261        if (comp == null) {
8262            if (intent.getSelector() != null) {
8263                intent = intent.getSelector();
8264                comp = intent.getComponent();
8265            }
8266        }
8267        if (comp != null) {
8268            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8269            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8270            if (pi != null) {
8271                // When specifying an explicit component, we prevent the provider from being
8272                // used when either 1) the provider is in an instant application and the
8273                // caller is not the same instant application or 2) the calling package is an
8274                // instant application and the provider is not visible to instant applications.
8275                final boolean matchInstantApp =
8276                        (flags & PackageManager.MATCH_INSTANT) != 0;
8277                final boolean matchVisibleToInstantAppOnly =
8278                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8279                final boolean isCallerInstantApp =
8280                        instantAppPkgName != null;
8281                final boolean isTargetSameInstantApp =
8282                        comp.getPackageName().equals(instantAppPkgName);
8283                final boolean isTargetInstantApp =
8284                        (pi.applicationInfo.privateFlags
8285                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8286                final boolean isTargetHiddenFromInstantApp =
8287                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8288                final boolean blockResolution =
8289                        !isTargetSameInstantApp
8290                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8291                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8292                                        && isTargetHiddenFromInstantApp));
8293                if (!blockResolution) {
8294                    final ResolveInfo ri = new ResolveInfo();
8295                    ri.providerInfo = pi;
8296                    list.add(ri);
8297                }
8298            }
8299            return list;
8300        }
8301
8302        // reader
8303        synchronized (mPackages) {
8304            String pkgName = intent.getPackage();
8305            if (pkgName == null) {
8306                return applyPostContentProviderResolutionFilter(
8307                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8308                        instantAppPkgName);
8309            }
8310            final PackageParser.Package pkg = mPackages.get(pkgName);
8311            if (pkg != null) {
8312                return applyPostContentProviderResolutionFilter(
8313                        mProviders.queryIntentForPackage(
8314                        intent, resolvedType, flags, pkg.providers, userId),
8315                        instantAppPkgName);
8316            }
8317            return Collections.emptyList();
8318        }
8319    }
8320
8321    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8322            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8323        if (instantAppPkgName == null) {
8324            return resolveInfos;
8325        }
8326        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8327            final ResolveInfo info = resolveInfos.get(i);
8328            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8329            // allow providers that are defined in the provided package
8330            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8331                if (info.providerInfo.splitName != null
8332                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8333                                info.providerInfo.splitName)) {
8334                    // requested provider is defined in a split that hasn't been installed yet.
8335                    // add the installer to the resolve list
8336                    if (DEBUG_EPHEMERAL) {
8337                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8338                    }
8339                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8340                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8341                            info.providerInfo.packageName, info.providerInfo.splitName,
8342                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8343                            null /*failureIntent*/);
8344                    // make sure this resolver is the default
8345                    installerInfo.isDefault = true;
8346                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8347                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8348                    // add a non-generic filter
8349                    installerInfo.filter = new IntentFilter();
8350                    // load resources from the correct package
8351                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8352                    resolveInfos.set(i, installerInfo);
8353                }
8354                continue;
8355            }
8356            // allow providers that have been explicitly exposed to instant applications
8357            if (!isEphemeralApp
8358                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8359                continue;
8360            }
8361            resolveInfos.remove(i);
8362        }
8363        return resolveInfos;
8364    }
8365
8366    @Override
8367    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8368        final int callingUid = Binder.getCallingUid();
8369        if (getInstantAppPackageName(callingUid) != null) {
8370            return ParceledListSlice.emptyList();
8371        }
8372        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8373        flags = updateFlagsForPackage(flags, userId, null);
8374        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8375        enforceCrossUserPermission(callingUid, userId,
8376                true /* requireFullPermission */, false /* checkShell */,
8377                "get installed packages");
8378
8379        // writer
8380        synchronized (mPackages) {
8381            ArrayList<PackageInfo> list;
8382            if (listUninstalled) {
8383                list = new ArrayList<>(mSettings.mPackages.size());
8384                for (PackageSetting ps : mSettings.mPackages.values()) {
8385                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8386                        continue;
8387                    }
8388                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8389                        continue;
8390                    }
8391                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8392                    if (pi != null) {
8393                        list.add(pi);
8394                    }
8395                }
8396            } else {
8397                list = new ArrayList<>(mPackages.size());
8398                for (PackageParser.Package p : mPackages.values()) {
8399                    final PackageSetting ps = (PackageSetting) p.mExtras;
8400                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8401                        continue;
8402                    }
8403                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8404                        continue;
8405                    }
8406                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8407                            p.mExtras, flags, userId);
8408                    if (pi != null) {
8409                        list.add(pi);
8410                    }
8411                }
8412            }
8413
8414            return new ParceledListSlice<>(list);
8415        }
8416    }
8417
8418    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8419            String[] permissions, boolean[] tmp, int flags, int userId) {
8420        int numMatch = 0;
8421        final PermissionsState permissionsState = ps.getPermissionsState();
8422        for (int i=0; i<permissions.length; i++) {
8423            final String permission = permissions[i];
8424            if (permissionsState.hasPermission(permission, userId)) {
8425                tmp[i] = true;
8426                numMatch++;
8427            } else {
8428                tmp[i] = false;
8429            }
8430        }
8431        if (numMatch == 0) {
8432            return;
8433        }
8434        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8435
8436        // The above might return null in cases of uninstalled apps or install-state
8437        // skew across users/profiles.
8438        if (pi != null) {
8439            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8440                if (numMatch == permissions.length) {
8441                    pi.requestedPermissions = permissions;
8442                } else {
8443                    pi.requestedPermissions = new String[numMatch];
8444                    numMatch = 0;
8445                    for (int i=0; i<permissions.length; i++) {
8446                        if (tmp[i]) {
8447                            pi.requestedPermissions[numMatch] = permissions[i];
8448                            numMatch++;
8449                        }
8450                    }
8451                }
8452            }
8453            list.add(pi);
8454        }
8455    }
8456
8457    @Override
8458    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8459            String[] permissions, int flags, int userId) {
8460        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8461        flags = updateFlagsForPackage(flags, userId, permissions);
8462        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8463                true /* requireFullPermission */, false /* checkShell */,
8464                "get packages holding permissions");
8465        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8466
8467        // writer
8468        synchronized (mPackages) {
8469            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8470            boolean[] tmpBools = new boolean[permissions.length];
8471            if (listUninstalled) {
8472                for (PackageSetting ps : mSettings.mPackages.values()) {
8473                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8474                            userId);
8475                }
8476            } else {
8477                for (PackageParser.Package pkg : mPackages.values()) {
8478                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8479                    if (ps != null) {
8480                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8481                                userId);
8482                    }
8483                }
8484            }
8485
8486            return new ParceledListSlice<PackageInfo>(list);
8487        }
8488    }
8489
8490    @Override
8491    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8492        final int callingUid = Binder.getCallingUid();
8493        if (getInstantAppPackageName(callingUid) != null) {
8494            return ParceledListSlice.emptyList();
8495        }
8496        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8497        flags = updateFlagsForApplication(flags, userId, null);
8498        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8499
8500        // writer
8501        synchronized (mPackages) {
8502            ArrayList<ApplicationInfo> list;
8503            if (listUninstalled) {
8504                list = new ArrayList<>(mSettings.mPackages.size());
8505                for (PackageSetting ps : mSettings.mPackages.values()) {
8506                    ApplicationInfo ai;
8507                    int effectiveFlags = flags;
8508                    if (ps.isSystem()) {
8509                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8510                    }
8511                    if (ps.pkg != null) {
8512                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8513                            continue;
8514                        }
8515                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8516                            continue;
8517                        }
8518                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8519                                ps.readUserState(userId), userId);
8520                        if (ai != null) {
8521                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8522                        }
8523                    } else {
8524                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8525                        // and already converts to externally visible package name
8526                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8527                                callingUid, effectiveFlags, userId);
8528                    }
8529                    if (ai != null) {
8530                        list.add(ai);
8531                    }
8532                }
8533            } else {
8534                list = new ArrayList<>(mPackages.size());
8535                for (PackageParser.Package p : mPackages.values()) {
8536                    if (p.mExtras != null) {
8537                        PackageSetting ps = (PackageSetting) p.mExtras;
8538                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8539                            continue;
8540                        }
8541                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8542                            continue;
8543                        }
8544                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8545                                ps.readUserState(userId), userId);
8546                        if (ai != null) {
8547                            ai.packageName = resolveExternalPackageNameLPr(p);
8548                            list.add(ai);
8549                        }
8550                    }
8551                }
8552            }
8553
8554            return new ParceledListSlice<>(list);
8555        }
8556    }
8557
8558    @Override
8559    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8560        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8561            return null;
8562        }
8563        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8564            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8565                    "getEphemeralApplications");
8566        }
8567        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8568                true /* requireFullPermission */, false /* checkShell */,
8569                "getEphemeralApplications");
8570        synchronized (mPackages) {
8571            List<InstantAppInfo> instantApps = mInstantAppRegistry
8572                    .getInstantAppsLPr(userId);
8573            if (instantApps != null) {
8574                return new ParceledListSlice<>(instantApps);
8575            }
8576        }
8577        return null;
8578    }
8579
8580    @Override
8581    public boolean isInstantApp(String packageName, int userId) {
8582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8583                true /* requireFullPermission */, false /* checkShell */,
8584                "isInstantApp");
8585        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8586            return false;
8587        }
8588
8589        synchronized (mPackages) {
8590            int callingUid = Binder.getCallingUid();
8591            if (Process.isIsolated(callingUid)) {
8592                callingUid = mIsolatedOwners.get(callingUid);
8593            }
8594            final PackageSetting ps = mSettings.mPackages.get(packageName);
8595            PackageParser.Package pkg = mPackages.get(packageName);
8596            final boolean returnAllowed =
8597                    ps != null
8598                    && (isCallerSameApp(packageName, callingUid)
8599                            || canViewInstantApps(callingUid, userId)
8600                            || mInstantAppRegistry.isInstantAccessGranted(
8601                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8602            if (returnAllowed) {
8603                return ps.getInstantApp(userId);
8604            }
8605        }
8606        return false;
8607    }
8608
8609    @Override
8610    public byte[] getInstantAppCookie(String packageName, int userId) {
8611        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8612            return null;
8613        }
8614
8615        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8616                true /* requireFullPermission */, false /* checkShell */,
8617                "getInstantAppCookie");
8618        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8619            return null;
8620        }
8621        synchronized (mPackages) {
8622            return mInstantAppRegistry.getInstantAppCookieLPw(
8623                    packageName, userId);
8624        }
8625    }
8626
8627    @Override
8628    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8629        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8630            return true;
8631        }
8632
8633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8634                true /* requireFullPermission */, true /* checkShell */,
8635                "setInstantAppCookie");
8636        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8637            return false;
8638        }
8639        synchronized (mPackages) {
8640            return mInstantAppRegistry.setInstantAppCookieLPw(
8641                    packageName, cookie, userId);
8642        }
8643    }
8644
8645    @Override
8646    public Bitmap getInstantAppIcon(String packageName, int userId) {
8647        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8648            return null;
8649        }
8650
8651        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8652            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8653                    "getInstantAppIcon");
8654        }
8655        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8656                true /* requireFullPermission */, false /* checkShell */,
8657                "getInstantAppIcon");
8658
8659        synchronized (mPackages) {
8660            return mInstantAppRegistry.getInstantAppIconLPw(
8661                    packageName, userId);
8662        }
8663    }
8664
8665    private boolean isCallerSameApp(String packageName, int uid) {
8666        PackageParser.Package pkg = mPackages.get(packageName);
8667        return pkg != null
8668                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8669    }
8670
8671    @Override
8672    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8673        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8674            return ParceledListSlice.emptyList();
8675        }
8676        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8677    }
8678
8679    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8680        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8681
8682        // reader
8683        synchronized (mPackages) {
8684            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8685            final int userId = UserHandle.getCallingUserId();
8686            while (i.hasNext()) {
8687                final PackageParser.Package p = i.next();
8688                if (p.applicationInfo == null) continue;
8689
8690                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8691                        && !p.applicationInfo.isDirectBootAware();
8692                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8693                        && p.applicationInfo.isDirectBootAware();
8694
8695                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8696                        && (!mSafeMode || isSystemApp(p))
8697                        && (matchesUnaware || matchesAware)) {
8698                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8699                    if (ps != null) {
8700                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8701                                ps.readUserState(userId), userId);
8702                        if (ai != null) {
8703                            finalList.add(ai);
8704                        }
8705                    }
8706                }
8707            }
8708        }
8709
8710        return finalList;
8711    }
8712
8713    @Override
8714    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8715        if (!sUserManager.exists(userId)) return null;
8716        flags = updateFlagsForComponent(flags, userId, name);
8717        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8718        // reader
8719        synchronized (mPackages) {
8720            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8721            PackageSetting ps = provider != null
8722                    ? mSettings.mPackages.get(provider.owner.packageName)
8723                    : null;
8724            if (ps != null) {
8725                final boolean isInstantApp = ps.getInstantApp(userId);
8726                // normal application; filter out instant application provider
8727                if (instantAppPkgName == null && isInstantApp) {
8728                    return null;
8729                }
8730                // instant application; filter out other instant applications
8731                if (instantAppPkgName != null
8732                        && isInstantApp
8733                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8734                    return null;
8735                }
8736                // instant application; filter out non-exposed provider
8737                if (instantAppPkgName != null
8738                        && !isInstantApp
8739                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8740                    return null;
8741                }
8742                // provider not enabled
8743                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8744                    return null;
8745                }
8746                return PackageParser.generateProviderInfo(
8747                        provider, flags, ps.readUserState(userId), userId);
8748            }
8749            return null;
8750        }
8751    }
8752
8753    /**
8754     * @deprecated
8755     */
8756    @Deprecated
8757    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8758        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8759            return;
8760        }
8761        // reader
8762        synchronized (mPackages) {
8763            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8764                    .entrySet().iterator();
8765            final int userId = UserHandle.getCallingUserId();
8766            while (i.hasNext()) {
8767                Map.Entry<String, PackageParser.Provider> entry = i.next();
8768                PackageParser.Provider p = entry.getValue();
8769                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8770
8771                if (ps != null && p.syncable
8772                        && (!mSafeMode || (p.info.applicationInfo.flags
8773                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8774                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8775                            ps.readUserState(userId), userId);
8776                    if (info != null) {
8777                        outNames.add(entry.getKey());
8778                        outInfo.add(info);
8779                    }
8780                }
8781            }
8782        }
8783    }
8784
8785    @Override
8786    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8787            int uid, int flags, String metaDataKey) {
8788        final int callingUid = Binder.getCallingUid();
8789        final int userId = processName != null ? UserHandle.getUserId(uid)
8790                : UserHandle.getCallingUserId();
8791        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8792        flags = updateFlagsForComponent(flags, userId, processName);
8793        ArrayList<ProviderInfo> finalList = null;
8794        // reader
8795        synchronized (mPackages) {
8796            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8797            while (i.hasNext()) {
8798                final PackageParser.Provider p = i.next();
8799                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8800                if (ps != null && p.info.authority != null
8801                        && (processName == null
8802                                || (p.info.processName.equals(processName)
8803                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8804                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8805
8806                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8807                    // parameter.
8808                    if (metaDataKey != null
8809                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8810                        continue;
8811                    }
8812                    final ComponentName component =
8813                            new ComponentName(p.info.packageName, p.info.name);
8814                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8815                        continue;
8816                    }
8817                    if (finalList == null) {
8818                        finalList = new ArrayList<ProviderInfo>(3);
8819                    }
8820                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8821                            ps.readUserState(userId), userId);
8822                    if (info != null) {
8823                        finalList.add(info);
8824                    }
8825                }
8826            }
8827        }
8828
8829        if (finalList != null) {
8830            Collections.sort(finalList, mProviderInitOrderSorter);
8831            return new ParceledListSlice<ProviderInfo>(finalList);
8832        }
8833
8834        return ParceledListSlice.emptyList();
8835    }
8836
8837    @Override
8838    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8839        // reader
8840        synchronized (mPackages) {
8841            final int callingUid = Binder.getCallingUid();
8842            final int callingUserId = UserHandle.getUserId(callingUid);
8843            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8844            if (ps == null) return null;
8845            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8846                return null;
8847            }
8848            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8849            return PackageParser.generateInstrumentationInfo(i, flags);
8850        }
8851    }
8852
8853    @Override
8854    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8855            String targetPackage, int flags) {
8856        final int callingUid = Binder.getCallingUid();
8857        final int callingUserId = UserHandle.getUserId(callingUid);
8858        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8859        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8860            return ParceledListSlice.emptyList();
8861        }
8862        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8863    }
8864
8865    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8866            int flags) {
8867        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8868
8869        // reader
8870        synchronized (mPackages) {
8871            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8872            while (i.hasNext()) {
8873                final PackageParser.Instrumentation p = i.next();
8874                if (targetPackage == null
8875                        || targetPackage.equals(p.info.targetPackage)) {
8876                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8877                            flags);
8878                    if (ii != null) {
8879                        finalList.add(ii);
8880                    }
8881                }
8882            }
8883        }
8884
8885        return finalList;
8886    }
8887
8888    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8889        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8890        try {
8891            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8892        } finally {
8893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8894        }
8895    }
8896
8897    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8898        final File[] files = dir.listFiles();
8899        if (ArrayUtils.isEmpty(files)) {
8900            Log.d(TAG, "No files in app dir " + dir);
8901            return;
8902        }
8903
8904        if (DEBUG_PACKAGE_SCANNING) {
8905            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8906                    + " flags=0x" + Integer.toHexString(parseFlags));
8907        }
8908        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8909                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8910                mParallelPackageParserCallback);
8911
8912        // Submit files for parsing in parallel
8913        int fileCount = 0;
8914        for (File file : files) {
8915            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8916                    && !PackageInstallerService.isStageName(file.getName());
8917            if (!isPackage) {
8918                // Ignore entries which are not packages
8919                continue;
8920            }
8921            parallelPackageParser.submit(file, parseFlags);
8922            fileCount++;
8923        }
8924
8925        // Process results one by one
8926        for (; fileCount > 0; fileCount--) {
8927            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8928            Throwable throwable = parseResult.throwable;
8929            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8930
8931            if (throwable == null) {
8932                // Static shared libraries have synthetic package names
8933                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8934                    renameStaticSharedLibraryPackage(parseResult.pkg);
8935                }
8936                try {
8937                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8938                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8939                                currentTime, null);
8940                    }
8941                } catch (PackageManagerException e) {
8942                    errorCode = e.error;
8943                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8944                }
8945            } else if (throwable instanceof PackageParser.PackageParserException) {
8946                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8947                        throwable;
8948                errorCode = e.error;
8949                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8950            } else {
8951                throw new IllegalStateException("Unexpected exception occurred while parsing "
8952                        + parseResult.scanFile, throwable);
8953            }
8954
8955            // Delete invalid userdata apps
8956            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8957                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8958                logCriticalInfo(Log.WARN,
8959                        "Deleting invalid package at " + parseResult.scanFile);
8960                removeCodePathLI(parseResult.scanFile);
8961            }
8962        }
8963        parallelPackageParser.close();
8964    }
8965
8966    private static File getSettingsProblemFile() {
8967        File dataDir = Environment.getDataDirectory();
8968        File systemDir = new File(dataDir, "system");
8969        File fname = new File(systemDir, "uiderrors.txt");
8970        return fname;
8971    }
8972
8973    public static void reportSettingsProblem(int priority, String msg) {
8974        logCriticalInfo(priority, msg);
8975    }
8976
8977    public static void logCriticalInfo(int priority, String msg) {
8978        Slog.println(priority, TAG, msg);
8979        EventLogTags.writePmCriticalInfo(msg);
8980        try {
8981            File fname = getSettingsProblemFile();
8982            FileOutputStream out = new FileOutputStream(fname, true);
8983            PrintWriter pw = new FastPrintWriter(out);
8984            SimpleDateFormat formatter = new SimpleDateFormat();
8985            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8986            pw.println(dateString + ": " + msg);
8987            pw.close();
8988            FileUtils.setPermissions(
8989                    fname.toString(),
8990                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8991                    -1, -1);
8992        } catch (java.io.IOException e) {
8993        }
8994    }
8995
8996    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8997        if (srcFile.isDirectory()) {
8998            final File baseFile = new File(pkg.baseCodePath);
8999            long maxModifiedTime = baseFile.lastModified();
9000            if (pkg.splitCodePaths != null) {
9001                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9002                    final File splitFile = new File(pkg.splitCodePaths[i]);
9003                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9004                }
9005            }
9006            return maxModifiedTime;
9007        }
9008        return srcFile.lastModified();
9009    }
9010
9011    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9012            final int policyFlags) throws PackageManagerException {
9013        // When upgrading from pre-N MR1, verify the package time stamp using the package
9014        // directory and not the APK file.
9015        final long lastModifiedTime = mIsPreNMR1Upgrade
9016                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9017        if (ps != null
9018                && ps.codePath.equals(srcFile)
9019                && ps.timeStamp == lastModifiedTime
9020                && !isCompatSignatureUpdateNeeded(pkg)
9021                && !isRecoverSignatureUpdateNeeded(pkg)) {
9022            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9023            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9024            ArraySet<PublicKey> signingKs;
9025            synchronized (mPackages) {
9026                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9027            }
9028            if (ps.signatures.mSignatures != null
9029                    && ps.signatures.mSignatures.length != 0
9030                    && signingKs != null) {
9031                // Optimization: reuse the existing cached certificates
9032                // if the package appears to be unchanged.
9033                pkg.mSignatures = ps.signatures.mSignatures;
9034                pkg.mSigningKeys = signingKs;
9035                return;
9036            }
9037
9038            Slog.w(TAG, "PackageSetting for " + ps.name
9039                    + " is missing signatures.  Collecting certs again to recover them.");
9040        } else {
9041            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9042        }
9043
9044        try {
9045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9046            PackageParser.collectCertificates(pkg, policyFlags);
9047        } catch (PackageParserException e) {
9048            throw PackageManagerException.from(e);
9049        } finally {
9050            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9051        }
9052    }
9053
9054    /**
9055     *  Traces a package scan.
9056     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9057     */
9058    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9059            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9060        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9061        try {
9062            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9063        } finally {
9064            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9065        }
9066    }
9067
9068    /**
9069     *  Scans a package and returns the newly parsed package.
9070     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9071     */
9072    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9073            long currentTime, UserHandle user) throws PackageManagerException {
9074        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9075        PackageParser pp = new PackageParser();
9076        pp.setSeparateProcesses(mSeparateProcesses);
9077        pp.setOnlyCoreApps(mOnlyCore);
9078        pp.setDisplayMetrics(mMetrics);
9079        pp.setCallback(mPackageParserCallback);
9080
9081        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9082            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9083        }
9084
9085        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9086        final PackageParser.Package pkg;
9087        try {
9088            pkg = pp.parsePackage(scanFile, parseFlags);
9089        } catch (PackageParserException e) {
9090            throw PackageManagerException.from(e);
9091        } finally {
9092            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9093        }
9094
9095        // Static shared libraries have synthetic package names
9096        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9097            renameStaticSharedLibraryPackage(pkg);
9098        }
9099
9100        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9101    }
9102
9103    /**
9104     *  Scans a package and returns the newly parsed package.
9105     *  @throws PackageManagerException on a parse error.
9106     */
9107    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9108            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9109            throws PackageManagerException {
9110        // If the package has children and this is the first dive in the function
9111        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9112        // packages (parent and children) would be successfully scanned before the
9113        // actual scan since scanning mutates internal state and we want to atomically
9114        // install the package and its children.
9115        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9116            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9117                scanFlags |= SCAN_CHECK_ONLY;
9118            }
9119        } else {
9120            scanFlags &= ~SCAN_CHECK_ONLY;
9121        }
9122
9123        // Scan the parent
9124        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9125                scanFlags, currentTime, user);
9126
9127        // Scan the children
9128        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9129        for (int i = 0; i < childCount; i++) {
9130            PackageParser.Package childPackage = pkg.childPackages.get(i);
9131            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9132                    currentTime, user);
9133        }
9134
9135
9136        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9137            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9138        }
9139
9140        return scannedPkg;
9141    }
9142
9143    /**
9144     *  Scans a package and returns the newly parsed package.
9145     *  @throws PackageManagerException on a parse error.
9146     */
9147    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9148            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9149            throws PackageManagerException {
9150        PackageSetting ps = null;
9151        PackageSetting updatedPkg;
9152        // reader
9153        synchronized (mPackages) {
9154            // Look to see if we already know about this package.
9155            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9156            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9157                // This package has been renamed to its original name.  Let's
9158                // use that.
9159                ps = mSettings.getPackageLPr(oldName);
9160            }
9161            // If there was no original package, see one for the real package name.
9162            if (ps == null) {
9163                ps = mSettings.getPackageLPr(pkg.packageName);
9164            }
9165            // Check to see if this package could be hiding/updating a system
9166            // package.  Must look for it either under the original or real
9167            // package name depending on our state.
9168            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9169            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9170
9171            // If this is a package we don't know about on the system partition, we
9172            // may need to remove disabled child packages on the system partition
9173            // or may need to not add child packages if the parent apk is updated
9174            // on the data partition and no longer defines this child package.
9175            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9176                // If this is a parent package for an updated system app and this system
9177                // app got an OTA update which no longer defines some of the child packages
9178                // we have to prune them from the disabled system packages.
9179                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9180                if (disabledPs != null) {
9181                    final int scannedChildCount = (pkg.childPackages != null)
9182                            ? pkg.childPackages.size() : 0;
9183                    final int disabledChildCount = disabledPs.childPackageNames != null
9184                            ? disabledPs.childPackageNames.size() : 0;
9185                    for (int i = 0; i < disabledChildCount; i++) {
9186                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9187                        boolean disabledPackageAvailable = false;
9188                        for (int j = 0; j < scannedChildCount; j++) {
9189                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9190                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9191                                disabledPackageAvailable = true;
9192                                break;
9193                            }
9194                         }
9195                         if (!disabledPackageAvailable) {
9196                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9197                         }
9198                    }
9199                }
9200            }
9201        }
9202
9203        final boolean isUpdatedPkg = updatedPkg != null;
9204        final boolean isUpdatedSystemPkg = isUpdatedPkg
9205                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9206        boolean isUpdatedPkgBetter = false;
9207        // First check if this is a system package that may involve an update
9208        if (isUpdatedSystemPkg) {
9209            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9210            // it needs to drop FLAG_PRIVILEGED.
9211            if (locationIsPrivileged(scanFile)) {
9212                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9213            } else {
9214                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9215            }
9216            // If new package is not located in "/oem" (e.g. due to an OTA),
9217            // it needs to drop FLAG_OEM.
9218            if (locationIsOem(scanFile)) {
9219                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
9220            } else {
9221                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
9222            }
9223
9224            if (ps != null && !ps.codePath.equals(scanFile)) {
9225                // The path has changed from what was last scanned...  check the
9226                // version of the new path against what we have stored to determine
9227                // what to do.
9228                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9229                if (pkg.mVersionCode <= ps.versionCode) {
9230                    // The system package has been updated and the code path does not match
9231                    // Ignore entry. Skip it.
9232                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9233                            + " ignored: updated version " + ps.versionCode
9234                            + " better than this " + pkg.mVersionCode);
9235                    if (!updatedPkg.codePath.equals(scanFile)) {
9236                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9237                                + ps.name + " changing from " + updatedPkg.codePathString
9238                                + " to " + scanFile);
9239                        updatedPkg.codePath = scanFile;
9240                        updatedPkg.codePathString = scanFile.toString();
9241                        updatedPkg.resourcePath = scanFile;
9242                        updatedPkg.resourcePathString = scanFile.toString();
9243                    }
9244                    updatedPkg.pkg = pkg;
9245                    updatedPkg.versionCode = pkg.mVersionCode;
9246
9247                    // Update the disabled system child packages to point to the package too.
9248                    final int childCount = updatedPkg.childPackageNames != null
9249                            ? updatedPkg.childPackageNames.size() : 0;
9250                    for (int i = 0; i < childCount; i++) {
9251                        String childPackageName = updatedPkg.childPackageNames.get(i);
9252                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9253                                childPackageName);
9254                        if (updatedChildPkg != null) {
9255                            updatedChildPkg.pkg = pkg;
9256                            updatedChildPkg.versionCode = pkg.mVersionCode;
9257                        }
9258                    }
9259                } else {
9260                    // The current app on the system partition is better than
9261                    // what we have updated to on the data partition; switch
9262                    // back to the system partition version.
9263                    // At this point, its safely assumed that package installation for
9264                    // apps in system partition will go through. If not there won't be a working
9265                    // version of the app
9266                    // writer
9267                    synchronized (mPackages) {
9268                        // Just remove the loaded entries from package lists.
9269                        mPackages.remove(ps.name);
9270                    }
9271
9272                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9273                            + " reverting from " + ps.codePathString
9274                            + ": new version " + pkg.mVersionCode
9275                            + " better than installed " + ps.versionCode);
9276
9277                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9278                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9279                    synchronized (mInstallLock) {
9280                        args.cleanUpResourcesLI();
9281                    }
9282                    synchronized (mPackages) {
9283                        mSettings.enableSystemPackageLPw(ps.name);
9284                    }
9285                    isUpdatedPkgBetter = true;
9286                }
9287            }
9288        }
9289
9290        String resourcePath = null;
9291        String baseResourcePath = null;
9292        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9293            if (ps != null && ps.resourcePathString != null) {
9294                resourcePath = ps.resourcePathString;
9295                baseResourcePath = ps.resourcePathString;
9296            } else {
9297                // Should not happen at all. Just log an error.
9298                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9299            }
9300        } else {
9301            resourcePath = pkg.codePath;
9302            baseResourcePath = pkg.baseCodePath;
9303        }
9304
9305        // Set application objects path explicitly.
9306        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9307        pkg.setApplicationInfoCodePath(pkg.codePath);
9308        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9309        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9310        pkg.setApplicationInfoResourcePath(resourcePath);
9311        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9312        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9313
9314        // throw an exception if we have an update to a system application, but, it's not more
9315        // recent than the package we've already scanned
9316        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9317            // Set CPU Abis to application info.
9318            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9319                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9320                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9321            } else {
9322                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9323                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9324            }
9325
9326            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9327                    + scanFile + " ignored: updated version " + ps.versionCode
9328                    + " better than this " + pkg.mVersionCode);
9329        }
9330
9331        if (isUpdatedPkg) {
9332            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9333            // initially
9334            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9335
9336            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9337            // flag set initially
9338            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9339                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9340            }
9341
9342            // An updated OEM app will not have the PARSE_IS_OEM
9343            // flag set initially
9344            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9345                policyFlags |= PackageParser.PARSE_IS_OEM;
9346            }
9347        }
9348
9349        // Verify certificates against what was last scanned
9350        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9351
9352        /*
9353         * A new system app appeared, but we already had a non-system one of the
9354         * same name installed earlier.
9355         */
9356        boolean shouldHideSystemApp = false;
9357        if (!isUpdatedPkg && ps != null
9358                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9359            /*
9360             * Check to make sure the signatures match first. If they don't,
9361             * wipe the installed application and its data.
9362             */
9363            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9364                    != PackageManager.SIGNATURE_MATCH) {
9365                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9366                        + " signatures don't match existing userdata copy; removing");
9367                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9368                        "scanPackageInternalLI")) {
9369                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9370                }
9371                ps = null;
9372            } else {
9373                /*
9374                 * If the newly-added system app is an older version than the
9375                 * already installed version, hide it. It will be scanned later
9376                 * and re-added like an update.
9377                 */
9378                if (pkg.mVersionCode <= ps.versionCode) {
9379                    shouldHideSystemApp = true;
9380                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9381                            + " but new version " + pkg.mVersionCode + " better than installed "
9382                            + ps.versionCode + "; hiding system");
9383                } else {
9384                    /*
9385                     * The newly found system app is a newer version that the
9386                     * one previously installed. Simply remove the
9387                     * already-installed application and replace it with our own
9388                     * while keeping the application data.
9389                     */
9390                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9391                            + " reverting from " + ps.codePathString + ": new version "
9392                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9393                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9394                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9395                    synchronized (mInstallLock) {
9396                        args.cleanUpResourcesLI();
9397                    }
9398                }
9399            }
9400        }
9401
9402        // The apk is forward locked (not public) if its code and resources
9403        // are kept in different files. (except for app in either system or
9404        // vendor path).
9405        // TODO grab this value from PackageSettings
9406        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9407            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9408                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9409            }
9410        }
9411
9412        final int userId = ((user == null) ? 0 : user.getIdentifier());
9413        if (ps != null && ps.getInstantApp(userId)) {
9414            scanFlags |= SCAN_AS_INSTANT_APP;
9415        }
9416        if (ps != null && ps.getVirtulalPreload(userId)) {
9417            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9418        }
9419
9420        // Note that we invoke the following method only if we are about to unpack an application
9421        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9422                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9423
9424        /*
9425         * If the system app should be overridden by a previously installed
9426         * data, hide the system app now and let the /data/app scan pick it up
9427         * again.
9428         */
9429        if (shouldHideSystemApp) {
9430            synchronized (mPackages) {
9431                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9432            }
9433        }
9434
9435        return scannedPkg;
9436    }
9437
9438    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9439        // Derive the new package synthetic package name
9440        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9441                + pkg.staticSharedLibVersion);
9442    }
9443
9444    private static String fixProcessName(String defProcessName,
9445            String processName) {
9446        if (processName == null) {
9447            return defProcessName;
9448        }
9449        return processName;
9450    }
9451
9452    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9453            throws PackageManagerException {
9454        if (pkgSetting.signatures.mSignatures != null) {
9455            // Already existing package. Make sure signatures match
9456            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9457                    == PackageManager.SIGNATURE_MATCH;
9458            if (!match) {
9459                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9460                        == PackageManager.SIGNATURE_MATCH;
9461            }
9462            if (!match) {
9463                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9464                        == PackageManager.SIGNATURE_MATCH;
9465            }
9466            if (!match) {
9467                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9468                        + pkg.packageName + " signatures do not match the "
9469                        + "previously installed version; ignoring!");
9470            }
9471        }
9472
9473        // Check for shared user signatures
9474        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9475            // Already existing package. Make sure signatures match
9476            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9477                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9478            if (!match) {
9479                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9480                        == PackageManager.SIGNATURE_MATCH;
9481            }
9482            if (!match) {
9483                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9484                        == PackageManager.SIGNATURE_MATCH;
9485            }
9486            if (!match) {
9487                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9488                        "Package " + pkg.packageName
9489                        + " has no signatures that match those in shared user "
9490                        + pkgSetting.sharedUser.name + "; ignoring!");
9491            }
9492        }
9493    }
9494
9495    /**
9496     * Enforces that only the system UID or root's UID can call a method exposed
9497     * via Binder.
9498     *
9499     * @param message used as message if SecurityException is thrown
9500     * @throws SecurityException if the caller is not system or root
9501     */
9502    private static final void enforceSystemOrRoot(String message) {
9503        final int uid = Binder.getCallingUid();
9504        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9505            throw new SecurityException(message);
9506        }
9507    }
9508
9509    @Override
9510    public void performFstrimIfNeeded() {
9511        enforceSystemOrRoot("Only the system can request fstrim");
9512
9513        // Before everything else, see whether we need to fstrim.
9514        try {
9515            IStorageManager sm = PackageHelper.getStorageManager();
9516            if (sm != null) {
9517                boolean doTrim = false;
9518                final long interval = android.provider.Settings.Global.getLong(
9519                        mContext.getContentResolver(),
9520                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9521                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9522                if (interval > 0) {
9523                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9524                    if (timeSinceLast > interval) {
9525                        doTrim = true;
9526                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9527                                + "; running immediately");
9528                    }
9529                }
9530                if (doTrim) {
9531                    final boolean dexOptDialogShown;
9532                    synchronized (mPackages) {
9533                        dexOptDialogShown = mDexOptDialogShown;
9534                    }
9535                    if (!isFirstBoot() && dexOptDialogShown) {
9536                        try {
9537                            ActivityManager.getService().showBootMessage(
9538                                    mContext.getResources().getString(
9539                                            R.string.android_upgrading_fstrim), true);
9540                        } catch (RemoteException e) {
9541                        }
9542                    }
9543                    sm.runMaintenance();
9544                }
9545            } else {
9546                Slog.e(TAG, "storageManager service unavailable!");
9547            }
9548        } catch (RemoteException e) {
9549            // Can't happen; StorageManagerService is local
9550        }
9551    }
9552
9553    @Override
9554    public void updatePackagesIfNeeded() {
9555        enforceSystemOrRoot("Only the system can request package update");
9556
9557        // We need to re-extract after an OTA.
9558        boolean causeUpgrade = isUpgrade();
9559
9560        // First boot or factory reset.
9561        // Note: we also handle devices that are upgrading to N right now as if it is their
9562        //       first boot, as they do not have profile data.
9563        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9564
9565        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9566        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9567
9568        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9569            return;
9570        }
9571
9572        List<PackageParser.Package> pkgs;
9573        synchronized (mPackages) {
9574            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9575        }
9576
9577        final long startTime = System.nanoTime();
9578        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9579                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9580                    false /* bootComplete */);
9581
9582        final int elapsedTimeSeconds =
9583                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9584
9585        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9586        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9587        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9588        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9589        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9590    }
9591
9592    /*
9593     * Return the prebuilt profile path given a package base code path.
9594     */
9595    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9596        return pkg.baseCodePath + ".prof";
9597    }
9598
9599    /**
9600     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9601     * containing statistics about the invocation. The array consists of three elements,
9602     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9603     * and {@code numberOfPackagesFailed}.
9604     */
9605    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9606            final String compilerFilter, boolean bootComplete) {
9607
9608        int numberOfPackagesVisited = 0;
9609        int numberOfPackagesOptimized = 0;
9610        int numberOfPackagesSkipped = 0;
9611        int numberOfPackagesFailed = 0;
9612        final int numberOfPackagesToDexopt = pkgs.size();
9613
9614        for (PackageParser.Package pkg : pkgs) {
9615            numberOfPackagesVisited++;
9616
9617            boolean useProfileForDexopt = false;
9618
9619            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9620                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9621                // that are already compiled.
9622                File profileFile = new File(getPrebuildProfilePath(pkg));
9623                // Copy profile if it exists.
9624                if (profileFile.exists()) {
9625                    try {
9626                        // We could also do this lazily before calling dexopt in
9627                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9628                        // is that we don't have a good way to say "do this only once".
9629                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9630                                pkg.applicationInfo.uid, pkg.packageName)) {
9631                            Log.e(TAG, "Installer failed to copy system profile!");
9632                        } else {
9633                            // Disabled as this causes speed-profile compilation during first boot
9634                            // even if things are already compiled.
9635                            // useProfileForDexopt = true;
9636                        }
9637                    } catch (Exception e) {
9638                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9639                                e);
9640                    }
9641                } else {
9642                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9643                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9644                    // minimize the number off apps being speed-profile compiled during first boot.
9645                    // The other paths will not change the filter.
9646                    if (disabledPs != null && disabledPs.pkg.isStub) {
9647                        // The package is the stub one, remove the stub suffix to get the normal
9648                        // package and APK names.
9649                        String systemProfilePath =
9650                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9651                        File systemProfile = new File(systemProfilePath);
9652                        // Use the profile for compilation if there exists one for the same package
9653                        // in the system partition.
9654                        useProfileForDexopt = systemProfile.exists();
9655                    }
9656                }
9657            }
9658
9659            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9660                if (DEBUG_DEXOPT) {
9661                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9662                }
9663                numberOfPackagesSkipped++;
9664                continue;
9665            }
9666
9667            if (DEBUG_DEXOPT) {
9668                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9669                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9670            }
9671
9672            if (showDialog) {
9673                try {
9674                    ActivityManager.getService().showBootMessage(
9675                            mContext.getResources().getString(R.string.android_upgrading_apk,
9676                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9677                } catch (RemoteException e) {
9678                }
9679                synchronized (mPackages) {
9680                    mDexOptDialogShown = true;
9681                }
9682            }
9683
9684            String pkgCompilerFilter = compilerFilter;
9685            if (useProfileForDexopt) {
9686                // Use background dexopt mode to try and use the profile. Note that this does not
9687                // guarantee usage of the profile.
9688                pkgCompilerFilter =
9689                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9690                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9691            }
9692
9693            // checkProfiles is false to avoid merging profiles during boot which
9694            // might interfere with background compilation (b/28612421).
9695            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9696            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9697            // trade-off worth doing to save boot time work.
9698            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9699            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9700                    pkg.packageName,
9701                    pkgCompilerFilter,
9702                    dexoptFlags));
9703
9704            switch (primaryDexOptStaus) {
9705                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9706                    numberOfPackagesOptimized++;
9707                    break;
9708                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9709                    numberOfPackagesSkipped++;
9710                    break;
9711                case PackageDexOptimizer.DEX_OPT_FAILED:
9712                    numberOfPackagesFailed++;
9713                    break;
9714                default:
9715                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9716                    break;
9717            }
9718        }
9719
9720        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9721                numberOfPackagesFailed };
9722    }
9723
9724    @Override
9725    public void notifyPackageUse(String packageName, int reason) {
9726        synchronized (mPackages) {
9727            final int callingUid = Binder.getCallingUid();
9728            final int callingUserId = UserHandle.getUserId(callingUid);
9729            if (getInstantAppPackageName(callingUid) != null) {
9730                if (!isCallerSameApp(packageName, callingUid)) {
9731                    return;
9732                }
9733            } else {
9734                if (isInstantApp(packageName, callingUserId)) {
9735                    return;
9736                }
9737            }
9738            notifyPackageUseLocked(packageName, reason);
9739        }
9740    }
9741
9742    private void notifyPackageUseLocked(String packageName, int reason) {
9743        final PackageParser.Package p = mPackages.get(packageName);
9744        if (p == null) {
9745            return;
9746        }
9747        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9748    }
9749
9750    @Override
9751    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9752            List<String> classPaths, String loaderIsa) {
9753        int userId = UserHandle.getCallingUserId();
9754        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9755        if (ai == null) {
9756            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9757                + loadingPackageName + ", user=" + userId);
9758            return;
9759        }
9760        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9761    }
9762
9763    @Override
9764    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9765            IDexModuleRegisterCallback callback) {
9766        int userId = UserHandle.getCallingUserId();
9767        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9768        DexManager.RegisterDexModuleResult result;
9769        if (ai == null) {
9770            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9771                     " calling user. package=" + packageName + ", user=" + userId);
9772            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9773        } else {
9774            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9775        }
9776
9777        if (callback != null) {
9778            mHandler.post(() -> {
9779                try {
9780                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9781                } catch (RemoteException e) {
9782                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9783                }
9784            });
9785        }
9786    }
9787
9788    /**
9789     * Ask the package manager to perform a dex-opt with the given compiler filter.
9790     *
9791     * Note: exposed only for the shell command to allow moving packages explicitly to a
9792     *       definite state.
9793     */
9794    @Override
9795    public boolean performDexOptMode(String packageName,
9796            boolean checkProfiles, String targetCompilerFilter, boolean force,
9797            boolean bootComplete, String splitName) {
9798        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9799                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9800                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9801        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9802                splitName, flags));
9803    }
9804
9805    /**
9806     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9807     * secondary dex files belonging to the given package.
9808     *
9809     * Note: exposed only for the shell command to allow moving packages explicitly to a
9810     *       definite state.
9811     */
9812    @Override
9813    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9814            boolean force) {
9815        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9816                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9817                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9818                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9819        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9820    }
9821
9822    /*package*/ boolean performDexOpt(DexoptOptions options) {
9823        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9824            return false;
9825        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9826            return false;
9827        }
9828
9829        if (options.isDexoptOnlySecondaryDex()) {
9830            return mDexManager.dexoptSecondaryDex(options);
9831        } else {
9832            int dexoptStatus = performDexOptWithStatus(options);
9833            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9834        }
9835    }
9836
9837    /**
9838     * Perform dexopt on the given package and return one of following result:
9839     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9840     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9841     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9842     */
9843    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9844        return performDexOptTraced(options);
9845    }
9846
9847    private int performDexOptTraced(DexoptOptions options) {
9848        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9849        try {
9850            return performDexOptInternal(options);
9851        } finally {
9852            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9853        }
9854    }
9855
9856    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9857    // if the package can now be considered up to date for the given filter.
9858    private int performDexOptInternal(DexoptOptions options) {
9859        PackageParser.Package p;
9860        synchronized (mPackages) {
9861            p = mPackages.get(options.getPackageName());
9862            if (p == null) {
9863                // Package could not be found. Report failure.
9864                return PackageDexOptimizer.DEX_OPT_FAILED;
9865            }
9866            mPackageUsage.maybeWriteAsync(mPackages);
9867            mCompilerStats.maybeWriteAsync();
9868        }
9869        long callingId = Binder.clearCallingIdentity();
9870        try {
9871            synchronized (mInstallLock) {
9872                return performDexOptInternalWithDependenciesLI(p, options);
9873            }
9874        } finally {
9875            Binder.restoreCallingIdentity(callingId);
9876        }
9877    }
9878
9879    public ArraySet<String> getOptimizablePackages() {
9880        ArraySet<String> pkgs = new ArraySet<String>();
9881        synchronized (mPackages) {
9882            for (PackageParser.Package p : mPackages.values()) {
9883                if (PackageDexOptimizer.canOptimizePackage(p)) {
9884                    pkgs.add(p.packageName);
9885                }
9886            }
9887        }
9888        return pkgs;
9889    }
9890
9891    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9892            DexoptOptions options) {
9893        // Select the dex optimizer based on the force parameter.
9894        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9895        //       allocate an object here.
9896        PackageDexOptimizer pdo = options.isForce()
9897                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9898                : mPackageDexOptimizer;
9899
9900        // Dexopt all dependencies first. Note: we ignore the return value and march on
9901        // on errors.
9902        // Note that we are going to call performDexOpt on those libraries as many times as
9903        // they are referenced in packages. When we do a batch of performDexOpt (for example
9904        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9905        // and the first package that uses the library will dexopt it. The
9906        // others will see that the compiled code for the library is up to date.
9907        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9908        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9909        if (!deps.isEmpty()) {
9910            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9911                    options.getCompilerFilter(), options.getSplitName(),
9912                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9913            for (PackageParser.Package depPackage : deps) {
9914                // TODO: Analyze and investigate if we (should) profile libraries.
9915                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9916                        getOrCreateCompilerPackageStats(depPackage),
9917                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9918            }
9919        }
9920        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9921                getOrCreateCompilerPackageStats(p),
9922                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9923    }
9924
9925    /**
9926     * Reconcile the information we have about the secondary dex files belonging to
9927     * {@code packagName} and the actual dex files. For all dex files that were
9928     * deleted, update the internal records and delete the generated oat files.
9929     */
9930    @Override
9931    public void reconcileSecondaryDexFiles(String packageName) {
9932        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9933            return;
9934        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9935            return;
9936        }
9937        mDexManager.reconcileSecondaryDexFiles(packageName);
9938    }
9939
9940    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9941    // a reference there.
9942    /*package*/ DexManager getDexManager() {
9943        return mDexManager;
9944    }
9945
9946    /**
9947     * Execute the background dexopt job immediately.
9948     */
9949    @Override
9950    public boolean runBackgroundDexoptJob() {
9951        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9952            return false;
9953        }
9954        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9955    }
9956
9957    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9958        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9959                || p.usesStaticLibraries != null) {
9960            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9961            Set<String> collectedNames = new HashSet<>();
9962            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9963
9964            retValue.remove(p);
9965
9966            return retValue;
9967        } else {
9968            return Collections.emptyList();
9969        }
9970    }
9971
9972    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9973            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9974        if (!collectedNames.contains(p.packageName)) {
9975            collectedNames.add(p.packageName);
9976            collected.add(p);
9977
9978            if (p.usesLibraries != null) {
9979                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9980                        null, collected, collectedNames);
9981            }
9982            if (p.usesOptionalLibraries != null) {
9983                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9984                        null, collected, collectedNames);
9985            }
9986            if (p.usesStaticLibraries != null) {
9987                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9988                        p.usesStaticLibrariesVersions, collected, collectedNames);
9989            }
9990        }
9991    }
9992
9993    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9994            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9995        final int libNameCount = libs.size();
9996        for (int i = 0; i < libNameCount; i++) {
9997            String libName = libs.get(i);
9998            int version = (versions != null && versions.length == libNameCount)
9999                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10000            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10001            if (libPkg != null) {
10002                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10003            }
10004        }
10005    }
10006
10007    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10008        synchronized (mPackages) {
10009            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10010            if (libEntry != null) {
10011                return mPackages.get(libEntry.apk);
10012            }
10013            return null;
10014        }
10015    }
10016
10017    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10018        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10019        if (versionedLib == null) {
10020            return null;
10021        }
10022        return versionedLib.get(version);
10023    }
10024
10025    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10026        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10027                pkg.staticSharedLibName);
10028        if (versionedLib == null) {
10029            return null;
10030        }
10031        int previousLibVersion = -1;
10032        final int versionCount = versionedLib.size();
10033        for (int i = 0; i < versionCount; i++) {
10034            final int libVersion = versionedLib.keyAt(i);
10035            if (libVersion < pkg.staticSharedLibVersion) {
10036                previousLibVersion = Math.max(previousLibVersion, libVersion);
10037            }
10038        }
10039        if (previousLibVersion >= 0) {
10040            return versionedLib.get(previousLibVersion);
10041        }
10042        return null;
10043    }
10044
10045    public void shutdown() {
10046        mPackageUsage.writeNow(mPackages);
10047        mCompilerStats.writeNow();
10048        mDexManager.writePackageDexUsageNow();
10049    }
10050
10051    @Override
10052    public void dumpProfiles(String packageName) {
10053        PackageParser.Package pkg;
10054        synchronized (mPackages) {
10055            pkg = mPackages.get(packageName);
10056            if (pkg == null) {
10057                throw new IllegalArgumentException("Unknown package: " + packageName);
10058            }
10059        }
10060        /* Only the shell, root, or the app user should be able to dump profiles. */
10061        int callingUid = Binder.getCallingUid();
10062        if (callingUid != Process.SHELL_UID &&
10063            callingUid != Process.ROOT_UID &&
10064            callingUid != pkg.applicationInfo.uid) {
10065            throw new SecurityException("dumpProfiles");
10066        }
10067
10068        synchronized (mInstallLock) {
10069            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10070            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10071            try {
10072                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10073                String codePaths = TextUtils.join(";", allCodePaths);
10074                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10075            } catch (InstallerException e) {
10076                Slog.w(TAG, "Failed to dump profiles", e);
10077            }
10078            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10079        }
10080    }
10081
10082    @Override
10083    public void forceDexOpt(String packageName) {
10084        enforceSystemOrRoot("forceDexOpt");
10085
10086        PackageParser.Package pkg;
10087        synchronized (mPackages) {
10088            pkg = mPackages.get(packageName);
10089            if (pkg == null) {
10090                throw new IllegalArgumentException("Unknown package: " + packageName);
10091            }
10092        }
10093
10094        synchronized (mInstallLock) {
10095            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10096
10097            // Whoever is calling forceDexOpt wants a compiled package.
10098            // Don't use profiles since that may cause compilation to be skipped.
10099            final int res = performDexOptInternalWithDependenciesLI(
10100                    pkg,
10101                    new DexoptOptions(packageName,
10102                            getDefaultCompilerFilter(),
10103                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10104
10105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10106            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10107                throw new IllegalStateException("Failed to dexopt: " + res);
10108            }
10109        }
10110    }
10111
10112    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10113        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10114            Slog.w(TAG, "Unable to update from " + oldPkg.name
10115                    + " to " + newPkg.packageName
10116                    + ": old package not in system partition");
10117            return false;
10118        } else if (mPackages.get(oldPkg.name) != null) {
10119            Slog.w(TAG, "Unable to update from " + oldPkg.name
10120                    + " to " + newPkg.packageName
10121                    + ": old package still exists");
10122            return false;
10123        }
10124        return true;
10125    }
10126
10127    void removeCodePathLI(File codePath) {
10128        if (codePath.isDirectory()) {
10129            try {
10130                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10131            } catch (InstallerException e) {
10132                Slog.w(TAG, "Failed to remove code path", e);
10133            }
10134        } else {
10135            codePath.delete();
10136        }
10137    }
10138
10139    private int[] resolveUserIds(int userId) {
10140        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10141    }
10142
10143    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10144        if (pkg == null) {
10145            Slog.wtf(TAG, "Package was null!", new Throwable());
10146            return;
10147        }
10148        clearAppDataLeafLIF(pkg, userId, flags);
10149        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10150        for (int i = 0; i < childCount; i++) {
10151            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10152        }
10153    }
10154
10155    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10156        final PackageSetting ps;
10157        synchronized (mPackages) {
10158            ps = mSettings.mPackages.get(pkg.packageName);
10159        }
10160        for (int realUserId : resolveUserIds(userId)) {
10161            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10162            try {
10163                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10164                        ceDataInode);
10165            } catch (InstallerException e) {
10166                Slog.w(TAG, String.valueOf(e));
10167            }
10168        }
10169    }
10170
10171    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10172        if (pkg == null) {
10173            Slog.wtf(TAG, "Package was null!", new Throwable());
10174            return;
10175        }
10176        destroyAppDataLeafLIF(pkg, userId, flags);
10177        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10178        for (int i = 0; i < childCount; i++) {
10179            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10180        }
10181    }
10182
10183    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10184        final PackageSetting ps;
10185        synchronized (mPackages) {
10186            ps = mSettings.mPackages.get(pkg.packageName);
10187        }
10188        for (int realUserId : resolveUserIds(userId)) {
10189            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10190            try {
10191                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10192                        ceDataInode);
10193            } catch (InstallerException e) {
10194                Slog.w(TAG, String.valueOf(e));
10195            }
10196            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10197        }
10198    }
10199
10200    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10201        if (pkg == null) {
10202            Slog.wtf(TAG, "Package was null!", new Throwable());
10203            return;
10204        }
10205        destroyAppProfilesLeafLIF(pkg);
10206        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10207        for (int i = 0; i < childCount; i++) {
10208            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10209        }
10210    }
10211
10212    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10213        try {
10214            mInstaller.destroyAppProfiles(pkg.packageName);
10215        } catch (InstallerException e) {
10216            Slog.w(TAG, String.valueOf(e));
10217        }
10218    }
10219
10220    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10221        if (pkg == null) {
10222            Slog.wtf(TAG, "Package was null!", new Throwable());
10223            return;
10224        }
10225        clearAppProfilesLeafLIF(pkg);
10226        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10227        for (int i = 0; i < childCount; i++) {
10228            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10229        }
10230    }
10231
10232    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10233        try {
10234            mInstaller.clearAppProfiles(pkg.packageName);
10235        } catch (InstallerException e) {
10236            Slog.w(TAG, String.valueOf(e));
10237        }
10238    }
10239
10240    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10241            long lastUpdateTime) {
10242        // Set parent install/update time
10243        PackageSetting ps = (PackageSetting) pkg.mExtras;
10244        if (ps != null) {
10245            ps.firstInstallTime = firstInstallTime;
10246            ps.lastUpdateTime = lastUpdateTime;
10247        }
10248        // Set children install/update time
10249        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10250        for (int i = 0; i < childCount; i++) {
10251            PackageParser.Package childPkg = pkg.childPackages.get(i);
10252            ps = (PackageSetting) childPkg.mExtras;
10253            if (ps != null) {
10254                ps.firstInstallTime = firstInstallTime;
10255                ps.lastUpdateTime = lastUpdateTime;
10256            }
10257        }
10258    }
10259
10260    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10261            PackageParser.Package changingLib) {
10262        if (file.path != null) {
10263            usesLibraryFiles.add(file.path);
10264            return;
10265        }
10266        PackageParser.Package p = mPackages.get(file.apk);
10267        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10268            // If we are doing this while in the middle of updating a library apk,
10269            // then we need to make sure to use that new apk for determining the
10270            // dependencies here.  (We haven't yet finished committing the new apk
10271            // to the package manager state.)
10272            if (p == null || p.packageName.equals(changingLib.packageName)) {
10273                p = changingLib;
10274            }
10275        }
10276        if (p != null) {
10277            usesLibraryFiles.addAll(p.getAllCodePaths());
10278            if (p.usesLibraryFiles != null) {
10279                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10280            }
10281        }
10282    }
10283
10284    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10285            PackageParser.Package changingLib) throws PackageManagerException {
10286        if (pkg == null) {
10287            return;
10288        }
10289        ArraySet<String> usesLibraryFiles = null;
10290        if (pkg.usesLibraries != null) {
10291            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10292                    null, null, pkg.packageName, changingLib, true,
10293                    pkg.applicationInfo.targetSdkVersion, null);
10294        }
10295        if (pkg.usesStaticLibraries != null) {
10296            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10297                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10298                    pkg.packageName, changingLib, true,
10299                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10300        }
10301        if (pkg.usesOptionalLibraries != null) {
10302            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10303                    null, null, pkg.packageName, changingLib, false,
10304                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10305        }
10306        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10307            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10308        } else {
10309            pkg.usesLibraryFiles = null;
10310        }
10311    }
10312
10313    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10314            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10315            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10316            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10317            throws PackageManagerException {
10318        final int libCount = requestedLibraries.size();
10319        for (int i = 0; i < libCount; i++) {
10320            final String libName = requestedLibraries.get(i);
10321            final int libVersion = requiredVersions != null ? requiredVersions[i]
10322                    : SharedLibraryInfo.VERSION_UNDEFINED;
10323            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10324            if (libEntry == null) {
10325                if (required) {
10326                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10327                            "Package " + packageName + " requires unavailable shared library "
10328                                    + libName + "; failing!");
10329                } else if (DEBUG_SHARED_LIBRARIES) {
10330                    Slog.i(TAG, "Package " + packageName
10331                            + " desires unavailable shared library "
10332                            + libName + "; ignoring!");
10333                }
10334            } else {
10335                if (requiredVersions != null && requiredCertDigests != null) {
10336                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10337                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10338                            "Package " + packageName + " requires unavailable static shared"
10339                                    + " library " + libName + " version "
10340                                    + libEntry.info.getVersion() + "; failing!");
10341                    }
10342
10343                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10344                    if (libPkg == null) {
10345                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10346                                "Package " + packageName + " requires unavailable static shared"
10347                                        + " library; failing!");
10348                    }
10349
10350                    final String[] expectedCertDigests = requiredCertDigests[i];
10351                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10352                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10353                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10354                            : PackageUtils.computeSignaturesSha256Digests(
10355                                    new Signature[]{libPkg.mSignatures[0]});
10356
10357                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10358                    // target O we don't parse the "additional-certificate" tags similarly
10359                    // how we only consider all certs only for apps targeting O (see above).
10360                    // Therefore, the size check is safe to make.
10361                    if (expectedCertDigests.length != libCertDigests.length) {
10362                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10363                                "Package " + packageName + " requires differently signed" +
10364                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10365                    }
10366
10367                    // Use a predictable order as signature order may vary
10368                    Arrays.sort(libCertDigests);
10369                    Arrays.sort(expectedCertDigests);
10370
10371                    final int certCount = libCertDigests.length;
10372                    for (int j = 0; j < certCount; j++) {
10373                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10374                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10375                                    "Package " + packageName + " requires differently signed" +
10376                                            " static shared library; failing!");
10377                        }
10378                    }
10379                }
10380
10381                if (outUsedLibraries == null) {
10382                    outUsedLibraries = new ArraySet<>();
10383                }
10384                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10385            }
10386        }
10387        return outUsedLibraries;
10388    }
10389
10390    private static boolean hasString(List<String> list, List<String> which) {
10391        if (list == null) {
10392            return false;
10393        }
10394        for (int i=list.size()-1; i>=0; i--) {
10395            for (int j=which.size()-1; j>=0; j--) {
10396                if (which.get(j).equals(list.get(i))) {
10397                    return true;
10398                }
10399            }
10400        }
10401        return false;
10402    }
10403
10404    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10405            PackageParser.Package changingPkg) {
10406        ArrayList<PackageParser.Package> res = null;
10407        for (PackageParser.Package pkg : mPackages.values()) {
10408            if (changingPkg != null
10409                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10410                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10411                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10412                            changingPkg.staticSharedLibName)) {
10413                return null;
10414            }
10415            if (res == null) {
10416                res = new ArrayList<>();
10417            }
10418            res.add(pkg);
10419            try {
10420                updateSharedLibrariesLPr(pkg, changingPkg);
10421            } catch (PackageManagerException e) {
10422                // If a system app update or an app and a required lib missing we
10423                // delete the package and for updated system apps keep the data as
10424                // it is better for the user to reinstall than to be in an limbo
10425                // state. Also libs disappearing under an app should never happen
10426                // - just in case.
10427                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10428                    final int flags = pkg.isUpdatedSystemApp()
10429                            ? PackageManager.DELETE_KEEP_DATA : 0;
10430                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10431                            flags , null, true, null);
10432                }
10433                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10434            }
10435        }
10436        return res;
10437    }
10438
10439    /**
10440     * Derive the value of the {@code cpuAbiOverride} based on the provided
10441     * value and an optional stored value from the package settings.
10442     */
10443    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10444        String cpuAbiOverride = null;
10445
10446        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10447            cpuAbiOverride = null;
10448        } else if (abiOverride != null) {
10449            cpuAbiOverride = abiOverride;
10450        } else if (settings != null) {
10451            cpuAbiOverride = settings.cpuAbiOverrideString;
10452        }
10453
10454        return cpuAbiOverride;
10455    }
10456
10457    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10458            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10459                    throws PackageManagerException {
10460        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10461        // If the package has children and this is the first dive in the function
10462        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10463        // whether all packages (parent and children) would be successfully scanned
10464        // before the actual scan since scanning mutates internal state and we want
10465        // to atomically install the package and its children.
10466        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10467            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10468                scanFlags |= SCAN_CHECK_ONLY;
10469            }
10470        } else {
10471            scanFlags &= ~SCAN_CHECK_ONLY;
10472        }
10473
10474        final PackageParser.Package scannedPkg;
10475        try {
10476            // Scan the parent
10477            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10478            // Scan the children
10479            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10480            for (int i = 0; i < childCount; i++) {
10481                PackageParser.Package childPkg = pkg.childPackages.get(i);
10482                scanPackageLI(childPkg, policyFlags,
10483                        scanFlags, currentTime, user);
10484            }
10485        } finally {
10486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10487        }
10488
10489        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10490            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10491        }
10492
10493        return scannedPkg;
10494    }
10495
10496    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10497            int scanFlags, long currentTime, @Nullable UserHandle user)
10498                    throws PackageManagerException {
10499        boolean success = false;
10500        try {
10501            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10502                    currentTime, user);
10503            success = true;
10504            return res;
10505        } finally {
10506            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10507                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10508                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10509                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10510                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10511            }
10512        }
10513    }
10514
10515    /**
10516     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10517     */
10518    private static boolean apkHasCode(String fileName) {
10519        StrictJarFile jarFile = null;
10520        try {
10521            jarFile = new StrictJarFile(fileName,
10522                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10523            return jarFile.findEntry("classes.dex") != null;
10524        } catch (IOException ignore) {
10525        } finally {
10526            try {
10527                if (jarFile != null) {
10528                    jarFile.close();
10529                }
10530            } catch (IOException ignore) {}
10531        }
10532        return false;
10533    }
10534
10535    /**
10536     * Enforces code policy for the package. This ensures that if an APK has
10537     * declared hasCode="true" in its manifest that the APK actually contains
10538     * code.
10539     *
10540     * @throws PackageManagerException If bytecode could not be found when it should exist
10541     */
10542    private static void assertCodePolicy(PackageParser.Package pkg)
10543            throws PackageManagerException {
10544        final boolean shouldHaveCode =
10545                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10546        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10547            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10548                    "Package " + pkg.baseCodePath + " code is missing");
10549        }
10550
10551        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10552            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10553                final boolean splitShouldHaveCode =
10554                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10555                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10556                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10557                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10558                }
10559            }
10560        }
10561    }
10562
10563    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10564            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10565                    throws PackageManagerException {
10566        if (DEBUG_PACKAGE_SCANNING) {
10567            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10568                Log.d(TAG, "Scanning package " + pkg.packageName);
10569        }
10570
10571        applyPolicy(pkg, policyFlags);
10572
10573        assertPackageIsValid(pkg, policyFlags, scanFlags);
10574
10575        if (Build.IS_DEBUGGABLE &&
10576                pkg.isPrivilegedApp() &&
10577                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10578            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10579        }
10580
10581        // Initialize package source and resource directories
10582        final File scanFile = new File(pkg.codePath);
10583        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10584        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10585
10586        SharedUserSetting suid = null;
10587        PackageSetting pkgSetting = null;
10588
10589        // Getting the package setting may have a side-effect, so if we
10590        // are only checking if scan would succeed, stash a copy of the
10591        // old setting to restore at the end.
10592        PackageSetting nonMutatedPs = null;
10593
10594        // We keep references to the derived CPU Abis from settings in oder to reuse
10595        // them in the case where we're not upgrading or booting for the first time.
10596        String primaryCpuAbiFromSettings = null;
10597        String secondaryCpuAbiFromSettings = null;
10598
10599        // writer
10600        synchronized (mPackages) {
10601            if (pkg.mSharedUserId != null) {
10602                // SIDE EFFECTS; may potentially allocate a new shared user
10603                suid = mSettings.getSharedUserLPw(
10604                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10605                if (DEBUG_PACKAGE_SCANNING) {
10606                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10607                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10608                                + "): packages=" + suid.packages);
10609                }
10610            }
10611
10612            // Check if we are renaming from an original package name.
10613            PackageSetting origPackage = null;
10614            String realName = null;
10615            if (pkg.mOriginalPackages != null) {
10616                // This package may need to be renamed to a previously
10617                // installed name.  Let's check on that...
10618                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10619                if (pkg.mOriginalPackages.contains(renamed)) {
10620                    // This package had originally been installed as the
10621                    // original name, and we have already taken care of
10622                    // transitioning to the new one.  Just update the new
10623                    // one to continue using the old name.
10624                    realName = pkg.mRealPackage;
10625                    if (!pkg.packageName.equals(renamed)) {
10626                        // Callers into this function may have already taken
10627                        // care of renaming the package; only do it here if
10628                        // it is not already done.
10629                        pkg.setPackageName(renamed);
10630                    }
10631                } else {
10632                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10633                        if ((origPackage = mSettings.getPackageLPr(
10634                                pkg.mOriginalPackages.get(i))) != null) {
10635                            // We do have the package already installed under its
10636                            // original name...  should we use it?
10637                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10638                                // New package is not compatible with original.
10639                                origPackage = null;
10640                                continue;
10641                            } else if (origPackage.sharedUser != null) {
10642                                // Make sure uid is compatible between packages.
10643                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10644                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10645                                            + " to " + pkg.packageName + ": old uid "
10646                                            + origPackage.sharedUser.name
10647                                            + " differs from " + pkg.mSharedUserId);
10648                                    origPackage = null;
10649                                    continue;
10650                                }
10651                                // TODO: Add case when shared user id is added [b/28144775]
10652                            } else {
10653                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10654                                        + pkg.packageName + " to old name " + origPackage.name);
10655                            }
10656                            break;
10657                        }
10658                    }
10659                }
10660            }
10661
10662            if (mTransferedPackages.contains(pkg.packageName)) {
10663                Slog.w(TAG, "Package " + pkg.packageName
10664                        + " was transferred to another, but its .apk remains");
10665            }
10666
10667            // See comments in nonMutatedPs declaration
10668            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10669                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10670                if (foundPs != null) {
10671                    nonMutatedPs = new PackageSetting(foundPs);
10672                }
10673            }
10674
10675            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10676                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10677                if (foundPs != null) {
10678                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10679                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10680                }
10681            }
10682
10683            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10684            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10685                PackageManagerService.reportSettingsProblem(Log.WARN,
10686                        "Package " + pkg.packageName + " shared user changed from "
10687                                + (pkgSetting.sharedUser != null
10688                                        ? pkgSetting.sharedUser.name : "<nothing>")
10689                                + " to "
10690                                + (suid != null ? suid.name : "<nothing>")
10691                                + "; replacing with new");
10692                pkgSetting = null;
10693            }
10694            final PackageSetting oldPkgSetting =
10695                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10696            final PackageSetting disabledPkgSetting =
10697                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10698
10699            String[] usesStaticLibraries = null;
10700            if (pkg.usesStaticLibraries != null) {
10701                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10702                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10703            }
10704
10705            if (pkgSetting == null) {
10706                final String parentPackageName = (pkg.parentPackage != null)
10707                        ? pkg.parentPackage.packageName : null;
10708                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10709                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10710                // REMOVE SharedUserSetting from method; update in a separate call
10711                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10712                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10713                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10714                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10715                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10716                        true /*allowInstall*/, instantApp, virtualPreload,
10717                        parentPackageName, pkg.getChildPackageNames(),
10718                        UserManagerService.getInstance(), usesStaticLibraries,
10719                        pkg.usesStaticLibrariesVersions);
10720                // SIDE EFFECTS; updates system state; move elsewhere
10721                if (origPackage != null) {
10722                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10723                }
10724                mSettings.addUserToSettingLPw(pkgSetting);
10725            } else {
10726                // REMOVE SharedUserSetting from method; update in a separate call.
10727                //
10728                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10729                // secondaryCpuAbi are not known at this point so we always update them
10730                // to null here, only to reset them at a later point.
10731                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10732                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10733                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10734                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10735                        UserManagerService.getInstance(), usesStaticLibraries,
10736                        pkg.usesStaticLibrariesVersions);
10737            }
10738            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10739            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10740
10741            // SIDE EFFECTS; modifies system state; move elsewhere
10742            if (pkgSetting.origPackage != null) {
10743                // If we are first transitioning from an original package,
10744                // fix up the new package's name now.  We need to do this after
10745                // looking up the package under its new name, so getPackageLP
10746                // can take care of fiddling things correctly.
10747                pkg.setPackageName(origPackage.name);
10748
10749                // File a report about this.
10750                String msg = "New package " + pkgSetting.realName
10751                        + " renamed to replace old package " + pkgSetting.name;
10752                reportSettingsProblem(Log.WARN, msg);
10753
10754                // Make a note of it.
10755                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10756                    mTransferedPackages.add(origPackage.name);
10757                }
10758
10759                // No longer need to retain this.
10760                pkgSetting.origPackage = null;
10761            }
10762
10763            // SIDE EFFECTS; modifies system state; move elsewhere
10764            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10765                // Make a note of it.
10766                mTransferedPackages.add(pkg.packageName);
10767            }
10768
10769            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10770                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10771            }
10772
10773            if ((scanFlags & SCAN_BOOTING) == 0
10774                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10775                // Check all shared libraries and map to their actual file path.
10776                // We only do this here for apps not on a system dir, because those
10777                // are the only ones that can fail an install due to this.  We
10778                // will take care of the system apps by updating all of their
10779                // library paths after the scan is done. Also during the initial
10780                // scan don't update any libs as we do this wholesale after all
10781                // apps are scanned to avoid dependency based scanning.
10782                updateSharedLibrariesLPr(pkg, null);
10783            }
10784
10785            if (mFoundPolicyFile) {
10786                SELinuxMMAC.assignSeInfoValue(pkg);
10787            }
10788            pkg.applicationInfo.uid = pkgSetting.appId;
10789            pkg.mExtras = pkgSetting;
10790
10791
10792            // Static shared libs have same package with different versions where
10793            // we internally use a synthetic package name to allow multiple versions
10794            // of the same package, therefore we need to compare signatures against
10795            // the package setting for the latest library version.
10796            PackageSetting signatureCheckPs = pkgSetting;
10797            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10798                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10799                if (libraryEntry != null) {
10800                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10801                }
10802            }
10803
10804            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10805                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10806                    // We just determined the app is signed correctly, so bring
10807                    // over the latest parsed certs.
10808                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10809                } else {
10810                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10811                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10812                                "Package " + pkg.packageName + " upgrade keys do not match the "
10813                                + "previously installed version");
10814                    } else {
10815                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10816                        String msg = "System package " + pkg.packageName
10817                                + " signature changed; retaining data.";
10818                        reportSettingsProblem(Log.WARN, msg);
10819                    }
10820                }
10821            } else {
10822                try {
10823                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10824                    verifySignaturesLP(signatureCheckPs, pkg);
10825                    // We just determined the app is signed correctly, so bring
10826                    // over the latest parsed certs.
10827                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10828                } catch (PackageManagerException e) {
10829                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10830                        throw e;
10831                    }
10832                    // The signature has changed, but this package is in the system
10833                    // image...  let's recover!
10834                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10835                    // However...  if this package is part of a shared user, but it
10836                    // doesn't match the signature of the shared user, let's fail.
10837                    // What this means is that you can't change the signatures
10838                    // associated with an overall shared user, which doesn't seem all
10839                    // that unreasonable.
10840                    if (signatureCheckPs.sharedUser != null) {
10841                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10842                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10843                            throw new PackageManagerException(
10844                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10845                                    "Signature mismatch for shared user: "
10846                                            + pkgSetting.sharedUser);
10847                        }
10848                    }
10849                    // File a report about this.
10850                    String msg = "System package " + pkg.packageName
10851                            + " signature changed; retaining data.";
10852                    reportSettingsProblem(Log.WARN, msg);
10853                }
10854            }
10855
10856            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10857                // This package wants to adopt ownership of permissions from
10858                // another package.
10859                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10860                    final String origName = pkg.mAdoptPermissions.get(i);
10861                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10862                    if (orig != null) {
10863                        if (verifyPackageUpdateLPr(orig, pkg)) {
10864                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10865                                    + pkg.packageName);
10866                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10867                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10868                        }
10869                    }
10870                }
10871            }
10872        }
10873
10874        pkg.applicationInfo.processName = fixProcessName(
10875                pkg.applicationInfo.packageName,
10876                pkg.applicationInfo.processName);
10877
10878        if (pkg != mPlatformPackage) {
10879            // Get all of our default paths setup
10880            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10881        }
10882
10883        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10884
10885        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10886            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10887                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10888                final boolean extractNativeLibs = !pkg.isLibrary();
10889                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10890                        mAppLib32InstallDir);
10891                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10892
10893                // Some system apps still use directory structure for native libraries
10894                // in which case we might end up not detecting abi solely based on apk
10895                // structure. Try to detect abi based on directory structure.
10896                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10897                        pkg.applicationInfo.primaryCpuAbi == null) {
10898                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10899                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10900                }
10901            } else {
10902                // This is not a first boot or an upgrade, don't bother deriving the
10903                // ABI during the scan. Instead, trust the value that was stored in the
10904                // package setting.
10905                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10906                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10907
10908                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10909
10910                if (DEBUG_ABI_SELECTION) {
10911                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10912                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10913                        pkg.applicationInfo.secondaryCpuAbi);
10914                }
10915            }
10916        } else {
10917            if ((scanFlags & SCAN_MOVE) != 0) {
10918                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10919                // but we already have this packages package info in the PackageSetting. We just
10920                // use that and derive the native library path based on the new codepath.
10921                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10922                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10923            }
10924
10925            // Set native library paths again. For moves, the path will be updated based on the
10926            // ABIs we've determined above. For non-moves, the path will be updated based on the
10927            // ABIs we determined during compilation, but the path will depend on the final
10928            // package path (after the rename away from the stage path).
10929            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10930        }
10931
10932        // This is a special case for the "system" package, where the ABI is
10933        // dictated by the zygote configuration (and init.rc). We should keep track
10934        // of this ABI so that we can deal with "normal" applications that run under
10935        // the same UID correctly.
10936        if (mPlatformPackage == pkg) {
10937            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10938                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10939        }
10940
10941        // If there's a mismatch between the abi-override in the package setting
10942        // and the abiOverride specified for the install. Warn about this because we
10943        // would've already compiled the app without taking the package setting into
10944        // account.
10945        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10946            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10947                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10948                        " for package " + pkg.packageName);
10949            }
10950        }
10951
10952        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10953        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10954        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10955
10956        // Copy the derived override back to the parsed package, so that we can
10957        // update the package settings accordingly.
10958        pkg.cpuAbiOverride = cpuAbiOverride;
10959
10960        if (DEBUG_ABI_SELECTION) {
10961            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10962                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10963                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10964        }
10965
10966        // Push the derived path down into PackageSettings so we know what to
10967        // clean up at uninstall time.
10968        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10969
10970        if (DEBUG_ABI_SELECTION) {
10971            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10972                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10973                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10974        }
10975
10976        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10977        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10978            // We don't do this here during boot because we can do it all
10979            // at once after scanning all existing packages.
10980            //
10981            // We also do this *before* we perform dexopt on this package, so that
10982            // we can avoid redundant dexopts, and also to make sure we've got the
10983            // code and package path correct.
10984            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10985        }
10986
10987        if (mFactoryTest && pkg.requestedPermissions.contains(
10988                android.Manifest.permission.FACTORY_TEST)) {
10989            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10990        }
10991
10992        if (isSystemApp(pkg)) {
10993            pkgSetting.isOrphaned = true;
10994        }
10995
10996        // Take care of first install / last update times.
10997        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10998        if (currentTime != 0) {
10999            if (pkgSetting.firstInstallTime == 0) {
11000                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11001            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11002                pkgSetting.lastUpdateTime = currentTime;
11003            }
11004        } else if (pkgSetting.firstInstallTime == 0) {
11005            // We need *something*.  Take time time stamp of the file.
11006            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11007        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11008            if (scanFileTime != pkgSetting.timeStamp) {
11009                // A package on the system image has changed; consider this
11010                // to be an update.
11011                pkgSetting.lastUpdateTime = scanFileTime;
11012            }
11013        }
11014        pkgSetting.setTimeStamp(scanFileTime);
11015
11016        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11017            if (nonMutatedPs != null) {
11018                synchronized (mPackages) {
11019                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11020                }
11021            }
11022        } else {
11023            final int userId = user == null ? 0 : user.getIdentifier();
11024            // Modify state for the given package setting
11025            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11026                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11027            if (pkgSetting.getInstantApp(userId)) {
11028                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11029            }
11030        }
11031        return pkg;
11032    }
11033
11034    /**
11035     * Applies policy to the parsed package based upon the given policy flags.
11036     * Ensures the package is in a good state.
11037     * <p>
11038     * Implementation detail: This method must NOT have any side effect. It would
11039     * ideally be static, but, it requires locks to read system state.
11040     */
11041    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11042        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11043            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11044            if (pkg.applicationInfo.isDirectBootAware()) {
11045                // we're direct boot aware; set for all components
11046                for (PackageParser.Service s : pkg.services) {
11047                    s.info.encryptionAware = s.info.directBootAware = true;
11048                }
11049                for (PackageParser.Provider p : pkg.providers) {
11050                    p.info.encryptionAware = p.info.directBootAware = true;
11051                }
11052                for (PackageParser.Activity a : pkg.activities) {
11053                    a.info.encryptionAware = a.info.directBootAware = true;
11054                }
11055                for (PackageParser.Activity r : pkg.receivers) {
11056                    r.info.encryptionAware = r.info.directBootAware = true;
11057                }
11058            }
11059            if (compressedFileExists(pkg.codePath)) {
11060                pkg.isStub = true;
11061            }
11062        } else {
11063            // Only allow system apps to be flagged as core apps.
11064            pkg.coreApp = false;
11065            // clear flags not applicable to regular apps
11066            pkg.applicationInfo.privateFlags &=
11067                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11068            pkg.applicationInfo.privateFlags &=
11069                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11070        }
11071        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11072
11073        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11074            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11075        }
11076
11077        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
11078            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
11079        }
11080
11081        if (!isSystemApp(pkg)) {
11082            // Only system apps can use these features.
11083            pkg.mOriginalPackages = null;
11084            pkg.mRealPackage = null;
11085            pkg.mAdoptPermissions = null;
11086        }
11087    }
11088
11089    /**
11090     * Asserts the parsed package is valid according to the given policy. If the
11091     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11092     * <p>
11093     * Implementation detail: This method must NOT have any side effects. It would
11094     * ideally be static, but, it requires locks to read system state.
11095     *
11096     * @throws PackageManagerException If the package fails any of the validation checks
11097     */
11098    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11099            throws PackageManagerException {
11100        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11101            assertCodePolicy(pkg);
11102        }
11103
11104        if (pkg.applicationInfo.getCodePath() == null ||
11105                pkg.applicationInfo.getResourcePath() == null) {
11106            // Bail out. The resource and code paths haven't been set.
11107            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11108                    "Code and resource paths haven't been set correctly");
11109        }
11110
11111        // Make sure we're not adding any bogus keyset info
11112        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11113        ksms.assertScannedPackageValid(pkg);
11114
11115        synchronized (mPackages) {
11116            // The special "android" package can only be defined once
11117            if (pkg.packageName.equals("android")) {
11118                if (mAndroidApplication != null) {
11119                    Slog.w(TAG, "*************************************************");
11120                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11121                    Slog.w(TAG, " codePath=" + pkg.codePath);
11122                    Slog.w(TAG, "*************************************************");
11123                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11124                            "Core android package being redefined.  Skipping.");
11125                }
11126            }
11127
11128            // A package name must be unique; don't allow duplicates
11129            if (mPackages.containsKey(pkg.packageName)) {
11130                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11131                        "Application package " + pkg.packageName
11132                        + " already installed.  Skipping duplicate.");
11133            }
11134
11135            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11136                // Static libs have a synthetic package name containing the version
11137                // but we still want the base name to be unique.
11138                if (mPackages.containsKey(pkg.manifestPackageName)) {
11139                    throw new PackageManagerException(
11140                            "Duplicate static shared lib provider package");
11141                }
11142
11143                // Static shared libraries should have at least O target SDK
11144                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11145                    throw new PackageManagerException(
11146                            "Packages declaring static-shared libs must target O SDK or higher");
11147                }
11148
11149                // Package declaring static a shared lib cannot be instant apps
11150                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11151                    throw new PackageManagerException(
11152                            "Packages declaring static-shared libs cannot be instant apps");
11153                }
11154
11155                // Package declaring static a shared lib cannot be renamed since the package
11156                // name is synthetic and apps can't code around package manager internals.
11157                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11158                    throw new PackageManagerException(
11159                            "Packages declaring static-shared libs cannot be renamed");
11160                }
11161
11162                // Package declaring static a shared lib cannot declare child packages
11163                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11164                    throw new PackageManagerException(
11165                            "Packages declaring static-shared libs cannot have child packages");
11166                }
11167
11168                // Package declaring static a shared lib cannot declare dynamic libs
11169                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11170                    throw new PackageManagerException(
11171                            "Packages declaring static-shared libs cannot declare dynamic libs");
11172                }
11173
11174                // Package declaring static a shared lib cannot declare shared users
11175                if (pkg.mSharedUserId != null) {
11176                    throw new PackageManagerException(
11177                            "Packages declaring static-shared libs cannot declare shared users");
11178                }
11179
11180                // Static shared libs cannot declare activities
11181                if (!pkg.activities.isEmpty()) {
11182                    throw new PackageManagerException(
11183                            "Static shared libs cannot declare activities");
11184                }
11185
11186                // Static shared libs cannot declare services
11187                if (!pkg.services.isEmpty()) {
11188                    throw new PackageManagerException(
11189                            "Static shared libs cannot declare services");
11190                }
11191
11192                // Static shared libs cannot declare providers
11193                if (!pkg.providers.isEmpty()) {
11194                    throw new PackageManagerException(
11195                            "Static shared libs cannot declare content providers");
11196                }
11197
11198                // Static shared libs cannot declare receivers
11199                if (!pkg.receivers.isEmpty()) {
11200                    throw new PackageManagerException(
11201                            "Static shared libs cannot declare broadcast receivers");
11202                }
11203
11204                // Static shared libs cannot declare permission groups
11205                if (!pkg.permissionGroups.isEmpty()) {
11206                    throw new PackageManagerException(
11207                            "Static shared libs cannot declare permission groups");
11208                }
11209
11210                // Static shared libs cannot declare permissions
11211                if (!pkg.permissions.isEmpty()) {
11212                    throw new PackageManagerException(
11213                            "Static shared libs cannot declare permissions");
11214                }
11215
11216                // Static shared libs cannot declare protected broadcasts
11217                if (pkg.protectedBroadcasts != null) {
11218                    throw new PackageManagerException(
11219                            "Static shared libs cannot declare protected broadcasts");
11220                }
11221
11222                // Static shared libs cannot be overlay targets
11223                if (pkg.mOverlayTarget != null) {
11224                    throw new PackageManagerException(
11225                            "Static shared libs cannot be overlay targets");
11226                }
11227
11228                // The version codes must be ordered as lib versions
11229                int minVersionCode = Integer.MIN_VALUE;
11230                int maxVersionCode = Integer.MAX_VALUE;
11231
11232                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11233                        pkg.staticSharedLibName);
11234                if (versionedLib != null) {
11235                    final int versionCount = versionedLib.size();
11236                    for (int i = 0; i < versionCount; i++) {
11237                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11238                        final int libVersionCode = libInfo.getDeclaringPackage()
11239                                .getVersionCode();
11240                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11241                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11242                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11243                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11244                        } else {
11245                            minVersionCode = maxVersionCode = libVersionCode;
11246                            break;
11247                        }
11248                    }
11249                }
11250                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11251                    throw new PackageManagerException("Static shared"
11252                            + " lib version codes must be ordered as lib versions");
11253                }
11254            }
11255
11256            // Only privileged apps and updated privileged apps can add child packages.
11257            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11258                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11259                    throw new PackageManagerException("Only privileged apps can add child "
11260                            + "packages. Ignoring package " + pkg.packageName);
11261                }
11262                final int childCount = pkg.childPackages.size();
11263                for (int i = 0; i < childCount; i++) {
11264                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11265                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11266                            childPkg.packageName)) {
11267                        throw new PackageManagerException("Can't override child of "
11268                                + "another disabled app. Ignoring package " + pkg.packageName);
11269                    }
11270                }
11271            }
11272
11273            // If we're only installing presumed-existing packages, require that the
11274            // scanned APK is both already known and at the path previously established
11275            // for it.  Previously unknown packages we pick up normally, but if we have an
11276            // a priori expectation about this package's install presence, enforce it.
11277            // With a singular exception for new system packages. When an OTA contains
11278            // a new system package, we allow the codepath to change from a system location
11279            // to the user-installed location. If we don't allow this change, any newer,
11280            // user-installed version of the application will be ignored.
11281            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11282                if (mExpectingBetter.containsKey(pkg.packageName)) {
11283                    logCriticalInfo(Log.WARN,
11284                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11285                } else {
11286                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11287                    if (known != null) {
11288                        if (DEBUG_PACKAGE_SCANNING) {
11289                            Log.d(TAG, "Examining " + pkg.codePath
11290                                    + " and requiring known paths " + known.codePathString
11291                                    + " & " + known.resourcePathString);
11292                        }
11293                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11294                                || !pkg.applicationInfo.getResourcePath().equals(
11295                                        known.resourcePathString)) {
11296                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11297                                    "Application package " + pkg.packageName
11298                                    + " found at " + pkg.applicationInfo.getCodePath()
11299                                    + " but expected at " + known.codePathString
11300                                    + "; ignoring.");
11301                        }
11302                    } else {
11303                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11304                                "Application package " + pkg.packageName
11305                                + " not found; ignoring.");
11306                    }
11307                }
11308            }
11309
11310            // Verify that this new package doesn't have any content providers
11311            // that conflict with existing packages.  Only do this if the
11312            // package isn't already installed, since we don't want to break
11313            // things that are installed.
11314            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11315                final int N = pkg.providers.size();
11316                int i;
11317                for (i=0; i<N; i++) {
11318                    PackageParser.Provider p = pkg.providers.get(i);
11319                    if (p.info.authority != null) {
11320                        String names[] = p.info.authority.split(";");
11321                        for (int j = 0; j < names.length; j++) {
11322                            if (mProvidersByAuthority.containsKey(names[j])) {
11323                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11324                                final String otherPackageName =
11325                                        ((other != null && other.getComponentName() != null) ?
11326                                                other.getComponentName().getPackageName() : "?");
11327                                throw new PackageManagerException(
11328                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11329                                        "Can't install because provider name " + names[j]
11330                                                + " (in package " + pkg.applicationInfo.packageName
11331                                                + ") is already used by " + otherPackageName);
11332                            }
11333                        }
11334                    }
11335                }
11336            }
11337        }
11338    }
11339
11340    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11341            int type, String declaringPackageName, int declaringVersionCode) {
11342        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11343        if (versionedLib == null) {
11344            versionedLib = new SparseArray<>();
11345            mSharedLibraries.put(name, versionedLib);
11346            if (type == SharedLibraryInfo.TYPE_STATIC) {
11347                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11348            }
11349        } else if (versionedLib.indexOfKey(version) >= 0) {
11350            return false;
11351        }
11352        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11353                version, type, declaringPackageName, declaringVersionCode);
11354        versionedLib.put(version, libEntry);
11355        return true;
11356    }
11357
11358    private boolean removeSharedLibraryLPw(String name, int version) {
11359        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11360        if (versionedLib == null) {
11361            return false;
11362        }
11363        final int libIdx = versionedLib.indexOfKey(version);
11364        if (libIdx < 0) {
11365            return false;
11366        }
11367        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11368        versionedLib.remove(version);
11369        if (versionedLib.size() <= 0) {
11370            mSharedLibraries.remove(name);
11371            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11372                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11373                        .getPackageName());
11374            }
11375        }
11376        return true;
11377    }
11378
11379    /**
11380     * Adds a scanned package to the system. When this method is finished, the package will
11381     * be available for query, resolution, etc...
11382     */
11383    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11384            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11385        final String pkgName = pkg.packageName;
11386        if (mCustomResolverComponentName != null &&
11387                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11388            setUpCustomResolverActivity(pkg);
11389        }
11390
11391        if (pkg.packageName.equals("android")) {
11392            synchronized (mPackages) {
11393                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11394                    // Set up information for our fall-back user intent resolution activity.
11395                    mPlatformPackage = pkg;
11396                    pkg.mVersionCode = mSdkVersion;
11397                    mAndroidApplication = pkg.applicationInfo;
11398                    if (!mResolverReplaced) {
11399                        mResolveActivity.applicationInfo = mAndroidApplication;
11400                        mResolveActivity.name = ResolverActivity.class.getName();
11401                        mResolveActivity.packageName = mAndroidApplication.packageName;
11402                        mResolveActivity.processName = "system:ui";
11403                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11404                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11405                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11406                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11407                        mResolveActivity.exported = true;
11408                        mResolveActivity.enabled = true;
11409                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11410                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11411                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11412                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11413                                | ActivityInfo.CONFIG_ORIENTATION
11414                                | ActivityInfo.CONFIG_KEYBOARD
11415                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11416                        mResolveInfo.activityInfo = mResolveActivity;
11417                        mResolveInfo.priority = 0;
11418                        mResolveInfo.preferredOrder = 0;
11419                        mResolveInfo.match = 0;
11420                        mResolveComponentName = new ComponentName(
11421                                mAndroidApplication.packageName, mResolveActivity.name);
11422                    }
11423                }
11424            }
11425        }
11426
11427        ArrayList<PackageParser.Package> clientLibPkgs = null;
11428        // writer
11429        synchronized (mPackages) {
11430            boolean hasStaticSharedLibs = false;
11431
11432            // Any app can add new static shared libraries
11433            if (pkg.staticSharedLibName != null) {
11434                // Static shared libs don't allow renaming as they have synthetic package
11435                // names to allow install of multiple versions, so use name from manifest.
11436                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11437                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11438                        pkg.manifestPackageName, pkg.mVersionCode)) {
11439                    hasStaticSharedLibs = true;
11440                } else {
11441                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11442                                + pkg.staticSharedLibName + " already exists; skipping");
11443                }
11444                // Static shared libs cannot be updated once installed since they
11445                // use synthetic package name which includes the version code, so
11446                // not need to update other packages's shared lib dependencies.
11447            }
11448
11449            if (!hasStaticSharedLibs
11450                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11451                // Only system apps can add new dynamic shared libraries.
11452                if (pkg.libraryNames != null) {
11453                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11454                        String name = pkg.libraryNames.get(i);
11455                        boolean allowed = false;
11456                        if (pkg.isUpdatedSystemApp()) {
11457                            // New library entries can only be added through the
11458                            // system image.  This is important to get rid of a lot
11459                            // of nasty edge cases: for example if we allowed a non-
11460                            // system update of the app to add a library, then uninstalling
11461                            // the update would make the library go away, and assumptions
11462                            // we made such as through app install filtering would now
11463                            // have allowed apps on the device which aren't compatible
11464                            // with it.  Better to just have the restriction here, be
11465                            // conservative, and create many fewer cases that can negatively
11466                            // impact the user experience.
11467                            final PackageSetting sysPs = mSettings
11468                                    .getDisabledSystemPkgLPr(pkg.packageName);
11469                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11470                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11471                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11472                                        allowed = true;
11473                                        break;
11474                                    }
11475                                }
11476                            }
11477                        } else {
11478                            allowed = true;
11479                        }
11480                        if (allowed) {
11481                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11482                                    SharedLibraryInfo.VERSION_UNDEFINED,
11483                                    SharedLibraryInfo.TYPE_DYNAMIC,
11484                                    pkg.packageName, pkg.mVersionCode)) {
11485                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11486                                        + name + " already exists; skipping");
11487                            }
11488                        } else {
11489                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11490                                    + name + " that is not declared on system image; skipping");
11491                        }
11492                    }
11493
11494                    if ((scanFlags & SCAN_BOOTING) == 0) {
11495                        // If we are not booting, we need to update any applications
11496                        // that are clients of our shared library.  If we are booting,
11497                        // this will all be done once the scan is complete.
11498                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11499                    }
11500                }
11501            }
11502        }
11503
11504        if ((scanFlags & SCAN_BOOTING) != 0) {
11505            // No apps can run during boot scan, so they don't need to be frozen
11506        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11507            // Caller asked to not kill app, so it's probably not frozen
11508        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11509            // Caller asked us to ignore frozen check for some reason; they
11510            // probably didn't know the package name
11511        } else {
11512            // We're doing major surgery on this package, so it better be frozen
11513            // right now to keep it from launching
11514            checkPackageFrozen(pkgName);
11515        }
11516
11517        // Also need to kill any apps that are dependent on the library.
11518        if (clientLibPkgs != null) {
11519            for (int i=0; i<clientLibPkgs.size(); i++) {
11520                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11521                killApplication(clientPkg.applicationInfo.packageName,
11522                        clientPkg.applicationInfo.uid, "update lib");
11523            }
11524        }
11525
11526        // writer
11527        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11528
11529        synchronized (mPackages) {
11530            // We don't expect installation to fail beyond this point
11531
11532            // Add the new setting to mSettings
11533            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11534            // Add the new setting to mPackages
11535            mPackages.put(pkg.applicationInfo.packageName, pkg);
11536            // Make sure we don't accidentally delete its data.
11537            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11538            while (iter.hasNext()) {
11539                PackageCleanItem item = iter.next();
11540                if (pkgName.equals(item.packageName)) {
11541                    iter.remove();
11542                }
11543            }
11544
11545            // Add the package's KeySets to the global KeySetManagerService
11546            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11547            ksms.addScannedPackageLPw(pkg);
11548
11549            int N = pkg.providers.size();
11550            StringBuilder r = null;
11551            int i;
11552            for (i=0; i<N; i++) {
11553                PackageParser.Provider p = pkg.providers.get(i);
11554                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11555                        p.info.processName);
11556                mProviders.addProvider(p);
11557                p.syncable = p.info.isSyncable;
11558                if (p.info.authority != null) {
11559                    String names[] = p.info.authority.split(";");
11560                    p.info.authority = null;
11561                    for (int j = 0; j < names.length; j++) {
11562                        if (j == 1 && p.syncable) {
11563                            // We only want the first authority for a provider to possibly be
11564                            // syncable, so if we already added this provider using a different
11565                            // authority clear the syncable flag. We copy the provider before
11566                            // changing it because the mProviders object contains a reference
11567                            // to a provider that we don't want to change.
11568                            // Only do this for the second authority since the resulting provider
11569                            // object can be the same for all future authorities for this provider.
11570                            p = new PackageParser.Provider(p);
11571                            p.syncable = false;
11572                        }
11573                        if (!mProvidersByAuthority.containsKey(names[j])) {
11574                            mProvidersByAuthority.put(names[j], p);
11575                            if (p.info.authority == null) {
11576                                p.info.authority = names[j];
11577                            } else {
11578                                p.info.authority = p.info.authority + ";" + names[j];
11579                            }
11580                            if (DEBUG_PACKAGE_SCANNING) {
11581                                if (chatty)
11582                                    Log.d(TAG, "Registered content provider: " + names[j]
11583                                            + ", className = " + p.info.name + ", isSyncable = "
11584                                            + p.info.isSyncable);
11585                            }
11586                        } else {
11587                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11588                            Slog.w(TAG, "Skipping provider name " + names[j] +
11589                                    " (in package " + pkg.applicationInfo.packageName +
11590                                    "): name already used by "
11591                                    + ((other != null && other.getComponentName() != null)
11592                                            ? other.getComponentName().getPackageName() : "?"));
11593                        }
11594                    }
11595                }
11596                if (chatty) {
11597                    if (r == null) {
11598                        r = new StringBuilder(256);
11599                    } else {
11600                        r.append(' ');
11601                    }
11602                    r.append(p.info.name);
11603                }
11604            }
11605            if (r != null) {
11606                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11607            }
11608
11609            N = pkg.services.size();
11610            r = null;
11611            for (i=0; i<N; i++) {
11612                PackageParser.Service s = pkg.services.get(i);
11613                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11614                        s.info.processName);
11615                mServices.addService(s);
11616                if (chatty) {
11617                    if (r == null) {
11618                        r = new StringBuilder(256);
11619                    } else {
11620                        r.append(' ');
11621                    }
11622                    r.append(s.info.name);
11623                }
11624            }
11625            if (r != null) {
11626                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11627            }
11628
11629            N = pkg.receivers.size();
11630            r = null;
11631            for (i=0; i<N; i++) {
11632                PackageParser.Activity a = pkg.receivers.get(i);
11633                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11634                        a.info.processName);
11635                mReceivers.addActivity(a, "receiver");
11636                if (chatty) {
11637                    if (r == null) {
11638                        r = new StringBuilder(256);
11639                    } else {
11640                        r.append(' ');
11641                    }
11642                    r.append(a.info.name);
11643                }
11644            }
11645            if (r != null) {
11646                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11647            }
11648
11649            N = pkg.activities.size();
11650            r = null;
11651            for (i=0; i<N; i++) {
11652                PackageParser.Activity a = pkg.activities.get(i);
11653                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11654                        a.info.processName);
11655                mActivities.addActivity(a, "activity");
11656                if (chatty) {
11657                    if (r == null) {
11658                        r = new StringBuilder(256);
11659                    } else {
11660                        r.append(' ');
11661                    }
11662                    r.append(a.info.name);
11663                }
11664            }
11665            if (r != null) {
11666                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11667            }
11668
11669            N = pkg.permissionGroups.size();
11670            r = null;
11671            for (i=0; i<N; i++) {
11672                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11673                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11674                final String curPackageName = cur == null ? null : cur.info.packageName;
11675                // Dont allow ephemeral apps to define new permission groups.
11676                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11677                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11678                            + pg.info.packageName
11679                            + " ignored: instant apps cannot define new permission groups.");
11680                    continue;
11681                }
11682                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11683                if (cur == null || isPackageUpdate) {
11684                    mPermissionGroups.put(pg.info.name, pg);
11685                    if (chatty) {
11686                        if (r == null) {
11687                            r = new StringBuilder(256);
11688                        } else {
11689                            r.append(' ');
11690                        }
11691                        if (isPackageUpdate) {
11692                            r.append("UPD:");
11693                        }
11694                        r.append(pg.info.name);
11695                    }
11696                } else {
11697                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11698                            + pg.info.packageName + " ignored: original from "
11699                            + cur.info.packageName);
11700                    if (chatty) {
11701                        if (r == null) {
11702                            r = new StringBuilder(256);
11703                        } else {
11704                            r.append(' ');
11705                        }
11706                        r.append("DUP:");
11707                        r.append(pg.info.name);
11708                    }
11709                }
11710            }
11711            if (r != null) {
11712                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11713            }
11714
11715            N = pkg.permissions.size();
11716            r = null;
11717            for (i=0; i<N; i++) {
11718                PackageParser.Permission p = pkg.permissions.get(i);
11719
11720                // Dont allow ephemeral apps to define new permissions.
11721                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11722                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11723                            + p.info.packageName
11724                            + " ignored: instant apps cannot define new permissions.");
11725                    continue;
11726                }
11727
11728                // Assume by default that we did not install this permission into the system.
11729                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11730
11731                // Now that permission groups have a special meaning, we ignore permission
11732                // groups for legacy apps to prevent unexpected behavior. In particular,
11733                // permissions for one app being granted to someone just because they happen
11734                // to be in a group defined by another app (before this had no implications).
11735                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11736                    p.group = mPermissionGroups.get(p.info.group);
11737                    // Warn for a permission in an unknown group.
11738                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11739                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11740                                + p.info.packageName + " in an unknown group " + p.info.group);
11741                    }
11742                }
11743
11744                final ArrayMap<String, BasePermission> permissionMap =
11745                        p.tree ? mSettings.mPermissionTrees
11746                                : mSettings.mPermissions;
11747                final BasePermission bp = BasePermission.createOrUpdate(
11748                        permissionMap.get(p.info.name), p, pkg, mSettings.mPermissionTrees, chatty);
11749                permissionMap.put(p.info.name, bp);
11750            }
11751
11752            N = pkg.instrumentation.size();
11753            r = null;
11754            for (i=0; i<N; i++) {
11755                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11756                a.info.packageName = pkg.applicationInfo.packageName;
11757                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11758                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11759                a.info.splitNames = pkg.splitNames;
11760                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11761                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11762                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11763                a.info.dataDir = pkg.applicationInfo.dataDir;
11764                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11765                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11766                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11767                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11768                mInstrumentation.put(a.getComponentName(), a);
11769                if (chatty) {
11770                    if (r == null) {
11771                        r = new StringBuilder(256);
11772                    } else {
11773                        r.append(' ');
11774                    }
11775                    r.append(a.info.name);
11776                }
11777            }
11778            if (r != null) {
11779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11780            }
11781
11782            if (pkg.protectedBroadcasts != null) {
11783                N = pkg.protectedBroadcasts.size();
11784                synchronized (mProtectedBroadcasts) {
11785                    for (i = 0; i < N; i++) {
11786                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11787                    }
11788                }
11789            }
11790        }
11791
11792        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11793    }
11794
11795    /**
11796     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11797     * is derived purely on the basis of the contents of {@code scanFile} and
11798     * {@code cpuAbiOverride}.
11799     *
11800     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11801     */
11802    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11803                                 String cpuAbiOverride, boolean extractLibs,
11804                                 File appLib32InstallDir)
11805            throws PackageManagerException {
11806        // Give ourselves some initial paths; we'll come back for another
11807        // pass once we've determined ABI below.
11808        setNativeLibraryPaths(pkg, appLib32InstallDir);
11809
11810        // We would never need to extract libs for forward-locked and external packages,
11811        // since the container service will do it for us. We shouldn't attempt to
11812        // extract libs from system app when it was not updated.
11813        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11814                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11815            extractLibs = false;
11816        }
11817
11818        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11819        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11820
11821        NativeLibraryHelper.Handle handle = null;
11822        try {
11823            handle = NativeLibraryHelper.Handle.create(pkg);
11824            // TODO(multiArch): This can be null for apps that didn't go through the
11825            // usual installation process. We can calculate it again, like we
11826            // do during install time.
11827            //
11828            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11829            // unnecessary.
11830            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11831
11832            // Null out the abis so that they can be recalculated.
11833            pkg.applicationInfo.primaryCpuAbi = null;
11834            pkg.applicationInfo.secondaryCpuAbi = null;
11835            if (isMultiArch(pkg.applicationInfo)) {
11836                // Warn if we've set an abiOverride for multi-lib packages..
11837                // By definition, we need to copy both 32 and 64 bit libraries for
11838                // such packages.
11839                if (pkg.cpuAbiOverride != null
11840                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11841                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11842                }
11843
11844                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11845                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11846                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11847                    if (extractLibs) {
11848                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11849                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11850                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11851                                useIsaSpecificSubdirs);
11852                    } else {
11853                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11854                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11855                    }
11856                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11857                }
11858
11859                // Shared library native code should be in the APK zip aligned
11860                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11861                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11862                            "Shared library native lib extraction not supported");
11863                }
11864
11865                maybeThrowExceptionForMultiArchCopy(
11866                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11867
11868                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11869                    if (extractLibs) {
11870                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11871                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11872                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11873                                useIsaSpecificSubdirs);
11874                    } else {
11875                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11876                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11877                    }
11878                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11879                }
11880
11881                maybeThrowExceptionForMultiArchCopy(
11882                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11883
11884                if (abi64 >= 0) {
11885                    // Shared library native libs should be in the APK zip aligned
11886                    if (extractLibs && pkg.isLibrary()) {
11887                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11888                                "Shared library native lib extraction not supported");
11889                    }
11890                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11891                }
11892
11893                if (abi32 >= 0) {
11894                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11895                    if (abi64 >= 0) {
11896                        if (pkg.use32bitAbi) {
11897                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11898                            pkg.applicationInfo.primaryCpuAbi = abi;
11899                        } else {
11900                            pkg.applicationInfo.secondaryCpuAbi = abi;
11901                        }
11902                    } else {
11903                        pkg.applicationInfo.primaryCpuAbi = abi;
11904                    }
11905                }
11906            } else {
11907                String[] abiList = (cpuAbiOverride != null) ?
11908                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11909
11910                // Enable gross and lame hacks for apps that are built with old
11911                // SDK tools. We must scan their APKs for renderscript bitcode and
11912                // not launch them if it's present. Don't bother checking on devices
11913                // that don't have 64 bit support.
11914                boolean needsRenderScriptOverride = false;
11915                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11916                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11917                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11918                    needsRenderScriptOverride = true;
11919                }
11920
11921                final int copyRet;
11922                if (extractLibs) {
11923                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11924                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11925                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11926                } else {
11927                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11928                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11929                }
11930                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11931
11932                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11933                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11934                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11935                }
11936
11937                if (copyRet >= 0) {
11938                    // Shared libraries that have native libs must be multi-architecture
11939                    if (pkg.isLibrary()) {
11940                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11941                                "Shared library with native libs must be multiarch");
11942                    }
11943                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11944                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11945                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11946                } else if (needsRenderScriptOverride) {
11947                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11948                }
11949            }
11950        } catch (IOException ioe) {
11951            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11952        } finally {
11953            IoUtils.closeQuietly(handle);
11954        }
11955
11956        // Now that we've calculated the ABIs and determined if it's an internal app,
11957        // we will go ahead and populate the nativeLibraryPath.
11958        setNativeLibraryPaths(pkg, appLib32InstallDir);
11959    }
11960
11961    /**
11962     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11963     * i.e, so that all packages can be run inside a single process if required.
11964     *
11965     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11966     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11967     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11968     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11969     * updating a package that belongs to a shared user.
11970     *
11971     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11972     * adds unnecessary complexity.
11973     */
11974    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11975            PackageParser.Package scannedPackage) {
11976        String requiredInstructionSet = null;
11977        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11978            requiredInstructionSet = VMRuntime.getInstructionSet(
11979                     scannedPackage.applicationInfo.primaryCpuAbi);
11980        }
11981
11982        PackageSetting requirer = null;
11983        for (PackageSetting ps : packagesForUser) {
11984            // If packagesForUser contains scannedPackage, we skip it. This will happen
11985            // when scannedPackage is an update of an existing package. Without this check,
11986            // we will never be able to change the ABI of any package belonging to a shared
11987            // user, even if it's compatible with other packages.
11988            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11989                if (ps.primaryCpuAbiString == null) {
11990                    continue;
11991                }
11992
11993                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11994                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11995                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11996                    // this but there's not much we can do.
11997                    String errorMessage = "Instruction set mismatch, "
11998                            + ((requirer == null) ? "[caller]" : requirer)
11999                            + " requires " + requiredInstructionSet + " whereas " + ps
12000                            + " requires " + instructionSet;
12001                    Slog.w(TAG, errorMessage);
12002                }
12003
12004                if (requiredInstructionSet == null) {
12005                    requiredInstructionSet = instructionSet;
12006                    requirer = ps;
12007                }
12008            }
12009        }
12010
12011        if (requiredInstructionSet != null) {
12012            String adjustedAbi;
12013            if (requirer != null) {
12014                // requirer != null implies that either scannedPackage was null or that scannedPackage
12015                // did not require an ABI, in which case we have to adjust scannedPackage to match
12016                // the ABI of the set (which is the same as requirer's ABI)
12017                adjustedAbi = requirer.primaryCpuAbiString;
12018                if (scannedPackage != null) {
12019                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12020                }
12021            } else {
12022                // requirer == null implies that we're updating all ABIs in the set to
12023                // match scannedPackage.
12024                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12025            }
12026
12027            for (PackageSetting ps : packagesForUser) {
12028                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12029                    if (ps.primaryCpuAbiString != null) {
12030                        continue;
12031                    }
12032
12033                    ps.primaryCpuAbiString = adjustedAbi;
12034                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12035                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12036                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12037                        if (DEBUG_ABI_SELECTION) {
12038                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12039                                    + " (requirer="
12040                                    + (requirer != null ? requirer.pkg : "null")
12041                                    + ", scannedPackage="
12042                                    + (scannedPackage != null ? scannedPackage : "null")
12043                                    + ")");
12044                        }
12045                        try {
12046                            mInstaller.rmdex(ps.codePathString,
12047                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12048                        } catch (InstallerException ignored) {
12049                        }
12050                    }
12051                }
12052            }
12053        }
12054    }
12055
12056    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12057        synchronized (mPackages) {
12058            mResolverReplaced = true;
12059            // Set up information for custom user intent resolution activity.
12060            mResolveActivity.applicationInfo = pkg.applicationInfo;
12061            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12062            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12063            mResolveActivity.processName = pkg.applicationInfo.packageName;
12064            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12065            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12066                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12067            mResolveActivity.theme = 0;
12068            mResolveActivity.exported = true;
12069            mResolveActivity.enabled = true;
12070            mResolveInfo.activityInfo = mResolveActivity;
12071            mResolveInfo.priority = 0;
12072            mResolveInfo.preferredOrder = 0;
12073            mResolveInfo.match = 0;
12074            mResolveComponentName = mCustomResolverComponentName;
12075            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12076                    mResolveComponentName);
12077        }
12078    }
12079
12080    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12081        if (installerActivity == null) {
12082            if (DEBUG_EPHEMERAL) {
12083                Slog.d(TAG, "Clear ephemeral installer activity");
12084            }
12085            mInstantAppInstallerActivity = null;
12086            return;
12087        }
12088
12089        if (DEBUG_EPHEMERAL) {
12090            Slog.d(TAG, "Set ephemeral installer activity: "
12091                    + installerActivity.getComponentName());
12092        }
12093        // Set up information for ephemeral installer activity
12094        mInstantAppInstallerActivity = installerActivity;
12095        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12096                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12097        mInstantAppInstallerActivity.exported = true;
12098        mInstantAppInstallerActivity.enabled = true;
12099        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12100        mInstantAppInstallerInfo.priority = 0;
12101        mInstantAppInstallerInfo.preferredOrder = 1;
12102        mInstantAppInstallerInfo.isDefault = true;
12103        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12104                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12105    }
12106
12107    private static String calculateBundledApkRoot(final String codePathString) {
12108        final File codePath = new File(codePathString);
12109        final File codeRoot;
12110        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12111            codeRoot = Environment.getRootDirectory();
12112        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12113            codeRoot = Environment.getOemDirectory();
12114        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12115            codeRoot = Environment.getVendorDirectory();
12116        } else {
12117            // Unrecognized code path; take its top real segment as the apk root:
12118            // e.g. /something/app/blah.apk => /something
12119            try {
12120                File f = codePath.getCanonicalFile();
12121                File parent = f.getParentFile();    // non-null because codePath is a file
12122                File tmp;
12123                while ((tmp = parent.getParentFile()) != null) {
12124                    f = parent;
12125                    parent = tmp;
12126                }
12127                codeRoot = f;
12128                Slog.w(TAG, "Unrecognized code path "
12129                        + codePath + " - using " + codeRoot);
12130            } catch (IOException e) {
12131                // Can't canonicalize the code path -- shenanigans?
12132                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12133                return Environment.getRootDirectory().getPath();
12134            }
12135        }
12136        return codeRoot.getPath();
12137    }
12138
12139    /**
12140     * Derive and set the location of native libraries for the given package,
12141     * which varies depending on where and how the package was installed.
12142     */
12143    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12144        final ApplicationInfo info = pkg.applicationInfo;
12145        final String codePath = pkg.codePath;
12146        final File codeFile = new File(codePath);
12147        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12148        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12149
12150        info.nativeLibraryRootDir = null;
12151        info.nativeLibraryRootRequiresIsa = false;
12152        info.nativeLibraryDir = null;
12153        info.secondaryNativeLibraryDir = null;
12154
12155        if (isApkFile(codeFile)) {
12156            // Monolithic install
12157            if (bundledApp) {
12158                // If "/system/lib64/apkname" exists, assume that is the per-package
12159                // native library directory to use; otherwise use "/system/lib/apkname".
12160                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12161                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12162                        getPrimaryInstructionSet(info));
12163
12164                // This is a bundled system app so choose the path based on the ABI.
12165                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12166                // is just the default path.
12167                final String apkName = deriveCodePathName(codePath);
12168                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12169                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12170                        apkName).getAbsolutePath();
12171
12172                if (info.secondaryCpuAbi != null) {
12173                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12174                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12175                            secondaryLibDir, apkName).getAbsolutePath();
12176                }
12177            } else if (asecApp) {
12178                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12179                        .getAbsolutePath();
12180            } else {
12181                final String apkName = deriveCodePathName(codePath);
12182                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12183                        .getAbsolutePath();
12184            }
12185
12186            info.nativeLibraryRootRequiresIsa = false;
12187            info.nativeLibraryDir = info.nativeLibraryRootDir;
12188        } else {
12189            // Cluster install
12190            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12191            info.nativeLibraryRootRequiresIsa = true;
12192
12193            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12194                    getPrimaryInstructionSet(info)).getAbsolutePath();
12195
12196            if (info.secondaryCpuAbi != null) {
12197                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12198                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12199            }
12200        }
12201    }
12202
12203    /**
12204     * Calculate the abis and roots for a bundled app. These can uniquely
12205     * be determined from the contents of the system partition, i.e whether
12206     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12207     * of this information, and instead assume that the system was built
12208     * sensibly.
12209     */
12210    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12211                                           PackageSetting pkgSetting) {
12212        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12213
12214        // If "/system/lib64/apkname" exists, assume that is the per-package
12215        // native library directory to use; otherwise use "/system/lib/apkname".
12216        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12217        setBundledAppAbi(pkg, apkRoot, apkName);
12218        // pkgSetting might be null during rescan following uninstall of updates
12219        // to a bundled app, so accommodate that possibility.  The settings in
12220        // that case will be established later from the parsed package.
12221        //
12222        // If the settings aren't null, sync them up with what we've just derived.
12223        // note that apkRoot isn't stored in the package settings.
12224        if (pkgSetting != null) {
12225            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12226            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12227        }
12228    }
12229
12230    /**
12231     * Deduces the ABI of a bundled app and sets the relevant fields on the
12232     * parsed pkg object.
12233     *
12234     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12235     *        under which system libraries are installed.
12236     * @param apkName the name of the installed package.
12237     */
12238    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12239        final File codeFile = new File(pkg.codePath);
12240
12241        final boolean has64BitLibs;
12242        final boolean has32BitLibs;
12243        if (isApkFile(codeFile)) {
12244            // Monolithic install
12245            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12246            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12247        } else {
12248            // Cluster install
12249            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12250            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12251                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12252                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12253                has64BitLibs = (new File(rootDir, isa)).exists();
12254            } else {
12255                has64BitLibs = false;
12256            }
12257            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12258                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12259                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12260                has32BitLibs = (new File(rootDir, isa)).exists();
12261            } else {
12262                has32BitLibs = false;
12263            }
12264        }
12265
12266        if (has64BitLibs && !has32BitLibs) {
12267            // The package has 64 bit libs, but not 32 bit libs. Its primary
12268            // ABI should be 64 bit. We can safely assume here that the bundled
12269            // native libraries correspond to the most preferred ABI in the list.
12270
12271            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12272            pkg.applicationInfo.secondaryCpuAbi = null;
12273        } else if (has32BitLibs && !has64BitLibs) {
12274            // The package has 32 bit libs but not 64 bit libs. Its primary
12275            // ABI should be 32 bit.
12276
12277            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12278            pkg.applicationInfo.secondaryCpuAbi = null;
12279        } else if (has32BitLibs && has64BitLibs) {
12280            // The application has both 64 and 32 bit bundled libraries. We check
12281            // here that the app declares multiArch support, and warn if it doesn't.
12282            //
12283            // We will be lenient here and record both ABIs. The primary will be the
12284            // ABI that's higher on the list, i.e, a device that's configured to prefer
12285            // 64 bit apps will see a 64 bit primary ABI,
12286
12287            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12288                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12289            }
12290
12291            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12292                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12293                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12294            } else {
12295                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12296                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12297            }
12298        } else {
12299            pkg.applicationInfo.primaryCpuAbi = null;
12300            pkg.applicationInfo.secondaryCpuAbi = null;
12301        }
12302    }
12303
12304    private void killApplication(String pkgName, int appId, String reason) {
12305        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12306    }
12307
12308    private void killApplication(String pkgName, int appId, int userId, String reason) {
12309        // Request the ActivityManager to kill the process(only for existing packages)
12310        // so that we do not end up in a confused state while the user is still using the older
12311        // version of the application while the new one gets installed.
12312        final long token = Binder.clearCallingIdentity();
12313        try {
12314            IActivityManager am = ActivityManager.getService();
12315            if (am != null) {
12316                try {
12317                    am.killApplication(pkgName, appId, userId, reason);
12318                } catch (RemoteException e) {
12319                }
12320            }
12321        } finally {
12322            Binder.restoreCallingIdentity(token);
12323        }
12324    }
12325
12326    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12327        // Remove the parent package setting
12328        PackageSetting ps = (PackageSetting) pkg.mExtras;
12329        if (ps != null) {
12330            removePackageLI(ps, chatty);
12331        }
12332        // Remove the child package setting
12333        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12334        for (int i = 0; i < childCount; i++) {
12335            PackageParser.Package childPkg = pkg.childPackages.get(i);
12336            ps = (PackageSetting) childPkg.mExtras;
12337            if (ps != null) {
12338                removePackageLI(ps, chatty);
12339            }
12340        }
12341    }
12342
12343    void removePackageLI(PackageSetting ps, boolean chatty) {
12344        if (DEBUG_INSTALL) {
12345            if (chatty)
12346                Log.d(TAG, "Removing package " + ps.name);
12347        }
12348
12349        // writer
12350        synchronized (mPackages) {
12351            mPackages.remove(ps.name);
12352            final PackageParser.Package pkg = ps.pkg;
12353            if (pkg != null) {
12354                cleanPackageDataStructuresLILPw(pkg, chatty);
12355            }
12356        }
12357    }
12358
12359    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12360        if (DEBUG_INSTALL) {
12361            if (chatty)
12362                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12363        }
12364
12365        // writer
12366        synchronized (mPackages) {
12367            // Remove the parent package
12368            mPackages.remove(pkg.applicationInfo.packageName);
12369            cleanPackageDataStructuresLILPw(pkg, chatty);
12370
12371            // Remove the child packages
12372            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12373            for (int i = 0; i < childCount; i++) {
12374                PackageParser.Package childPkg = pkg.childPackages.get(i);
12375                mPackages.remove(childPkg.applicationInfo.packageName);
12376                cleanPackageDataStructuresLILPw(childPkg, chatty);
12377            }
12378        }
12379    }
12380
12381    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12382        int N = pkg.providers.size();
12383        StringBuilder r = null;
12384        int i;
12385        for (i=0; i<N; i++) {
12386            PackageParser.Provider p = pkg.providers.get(i);
12387            mProviders.removeProvider(p);
12388            if (p.info.authority == null) {
12389
12390                /* There was another ContentProvider with this authority when
12391                 * this app was installed so this authority is null,
12392                 * Ignore it as we don't have to unregister the provider.
12393                 */
12394                continue;
12395            }
12396            String names[] = p.info.authority.split(";");
12397            for (int j = 0; j < names.length; j++) {
12398                if (mProvidersByAuthority.get(names[j]) == p) {
12399                    mProvidersByAuthority.remove(names[j]);
12400                    if (DEBUG_REMOVE) {
12401                        if (chatty)
12402                            Log.d(TAG, "Unregistered content provider: " + names[j]
12403                                    + ", className = " + p.info.name + ", isSyncable = "
12404                                    + p.info.isSyncable);
12405                    }
12406                }
12407            }
12408            if (DEBUG_REMOVE && chatty) {
12409                if (r == null) {
12410                    r = new StringBuilder(256);
12411                } else {
12412                    r.append(' ');
12413                }
12414                r.append(p.info.name);
12415            }
12416        }
12417        if (r != null) {
12418            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12419        }
12420
12421        N = pkg.services.size();
12422        r = null;
12423        for (i=0; i<N; i++) {
12424            PackageParser.Service s = pkg.services.get(i);
12425            mServices.removeService(s);
12426            if (chatty) {
12427                if (r == null) {
12428                    r = new StringBuilder(256);
12429                } else {
12430                    r.append(' ');
12431                }
12432                r.append(s.info.name);
12433            }
12434        }
12435        if (r != null) {
12436            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12437        }
12438
12439        N = pkg.receivers.size();
12440        r = null;
12441        for (i=0; i<N; i++) {
12442            PackageParser.Activity a = pkg.receivers.get(i);
12443            mReceivers.removeActivity(a, "receiver");
12444            if (DEBUG_REMOVE && chatty) {
12445                if (r == null) {
12446                    r = new StringBuilder(256);
12447                } else {
12448                    r.append(' ');
12449                }
12450                r.append(a.info.name);
12451            }
12452        }
12453        if (r != null) {
12454            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12455        }
12456
12457        N = pkg.activities.size();
12458        r = null;
12459        for (i=0; i<N; i++) {
12460            PackageParser.Activity a = pkg.activities.get(i);
12461            mActivities.removeActivity(a, "activity");
12462            if (DEBUG_REMOVE && chatty) {
12463                if (r == null) {
12464                    r = new StringBuilder(256);
12465                } else {
12466                    r.append(' ');
12467                }
12468                r.append(a.info.name);
12469            }
12470        }
12471        if (r != null) {
12472            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12473        }
12474
12475        N = pkg.permissions.size();
12476        r = null;
12477        for (i=0; i<N; i++) {
12478            PackageParser.Permission p = pkg.permissions.get(i);
12479            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12480            if (bp == null) {
12481                bp = mSettings.mPermissionTrees.get(p.info.name);
12482            }
12483            if (bp != null && bp.isPermission(p)) {
12484                bp.setPermission(null);
12485                if (DEBUG_REMOVE && chatty) {
12486                    if (r == null) {
12487                        r = new StringBuilder(256);
12488                    } else {
12489                        r.append(' ');
12490                    }
12491                    r.append(p.info.name);
12492                }
12493            }
12494            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12495                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12496                if (appOpPkgs != null) {
12497                    appOpPkgs.remove(pkg.packageName);
12498                }
12499            }
12500        }
12501        if (r != null) {
12502            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12503        }
12504
12505        N = pkg.requestedPermissions.size();
12506        r = null;
12507        for (i=0; i<N; i++) {
12508            String perm = pkg.requestedPermissions.get(i);
12509            BasePermission bp = mSettings.mPermissions.get(perm);
12510            if (bp != null && bp.isAppOp()) {
12511                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12512                if (appOpPkgs != null) {
12513                    appOpPkgs.remove(pkg.packageName);
12514                    if (appOpPkgs.isEmpty()) {
12515                        mAppOpPermissionPackages.remove(perm);
12516                    }
12517                }
12518            }
12519        }
12520        if (r != null) {
12521            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12522        }
12523
12524        N = pkg.instrumentation.size();
12525        r = null;
12526        for (i=0; i<N; i++) {
12527            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12528            mInstrumentation.remove(a.getComponentName());
12529            if (DEBUG_REMOVE && chatty) {
12530                if (r == null) {
12531                    r = new StringBuilder(256);
12532                } else {
12533                    r.append(' ');
12534                }
12535                r.append(a.info.name);
12536            }
12537        }
12538        if (r != null) {
12539            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12540        }
12541
12542        r = null;
12543        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12544            // Only system apps can hold shared libraries.
12545            if (pkg.libraryNames != null) {
12546                for (i = 0; i < pkg.libraryNames.size(); i++) {
12547                    String name = pkg.libraryNames.get(i);
12548                    if (removeSharedLibraryLPw(name, 0)) {
12549                        if (DEBUG_REMOVE && chatty) {
12550                            if (r == null) {
12551                                r = new StringBuilder(256);
12552                            } else {
12553                                r.append(' ');
12554                            }
12555                            r.append(name);
12556                        }
12557                    }
12558                }
12559            }
12560        }
12561
12562        r = null;
12563
12564        // Any package can hold static shared libraries.
12565        if (pkg.staticSharedLibName != null) {
12566            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12567                if (DEBUG_REMOVE && chatty) {
12568                    if (r == null) {
12569                        r = new StringBuilder(256);
12570                    } else {
12571                        r.append(' ');
12572                    }
12573                    r.append(pkg.staticSharedLibName);
12574                }
12575            }
12576        }
12577
12578        if (r != null) {
12579            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12580        }
12581    }
12582
12583    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12584        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12585            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12586                return true;
12587            }
12588        }
12589        return false;
12590    }
12591
12592    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12593    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12594    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12595
12596    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12597        // Update the parent permissions
12598        updatePermissionsLPw(pkg.packageName, pkg, flags);
12599        // Update the child permissions
12600        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12601        for (int i = 0; i < childCount; i++) {
12602            PackageParser.Package childPkg = pkg.childPackages.get(i);
12603            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12604        }
12605    }
12606
12607    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12608            int flags) {
12609        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12610        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12611    }
12612
12613    private void updatePermissionsLPw(String changingPkg,
12614            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12615        // TODO: Most of the methods exposing BasePermission internals [source package name,
12616        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
12617        // have package settings, we should make note of it elsewhere [map between
12618        // source package name and BasePermission] and cycle through that here. Then we
12619        // define a single method on BasePermission that takes a PackageSetting, changing
12620        // package name and a package.
12621        // NOTE: With this approach, we also don't need to tree trees differently than
12622        // normal permissions. Today, we need two separate loops because these BasePermission
12623        // objects are stored separately.
12624        // Make sure there are no dangling permission trees.
12625        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12626        while (it.hasNext()) {
12627            final BasePermission bp = it.next();
12628            if (bp.getSourcePackageSetting() == null) {
12629                // We may not yet have parsed the package, so just see if
12630                // we still know about its settings.
12631                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12632            }
12633            if (bp.getSourcePackageSetting() == null) {
12634                Slog.w(TAG, "Removing dangling permission tree: " + bp.getName()
12635                        + " from package " + bp.getSourcePackageName());
12636                it.remove();
12637            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12638                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12639                    Slog.i(TAG, "Removing old permission tree: " + bp.getName()
12640                            + " from package " + bp.getSourcePackageName());
12641                    flags |= UPDATE_PERMISSIONS_ALL;
12642                    it.remove();
12643                }
12644            }
12645        }
12646
12647        // Make sure all dynamic permissions have been assigned to a package,
12648        // and make sure there are no dangling permissions.
12649        it = mSettings.mPermissions.values().iterator();
12650        while (it.hasNext()) {
12651            final BasePermission bp = it.next();
12652            if (bp.isDynamic()) {
12653                bp.updateDynamicPermission(mSettings.mPermissionTrees);
12654            }
12655            if (bp.getSourcePackageSetting() == null) {
12656                // We may not yet have parsed the package, so just see if
12657                // we still know about its settings.
12658                bp.setSourcePackageSetting(mSettings.mPackages.get(bp.getSourcePackageName()));
12659            }
12660            if (bp.getSourcePackageSetting() == null) {
12661                Slog.w(TAG, "Removing dangling permission: " + bp.getName()
12662                        + " from package " + bp.getSourcePackageName());
12663                it.remove();
12664            } else if (changingPkg != null && changingPkg.equals(bp.getSourcePackageName())) {
12665                if (pkgInfo == null || !hasPermission(pkgInfo, bp.getName())) {
12666                    Slog.i(TAG, "Removing old permission: " + bp.getName()
12667                            + " from package " + bp.getSourcePackageName());
12668                    flags |= UPDATE_PERMISSIONS_ALL;
12669                    it.remove();
12670                }
12671            }
12672        }
12673
12674        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12675        // Now update the permissions for all packages, in particular
12676        // replace the granted permissions of the system packages.
12677        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12678            for (PackageParser.Package pkg : mPackages.values()) {
12679                if (pkg != pkgInfo) {
12680                    // Only replace for packages on requested volume
12681                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12682                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12683                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12684                    grantPermissionsLPw(pkg, replace, changingPkg);
12685                }
12686            }
12687        }
12688
12689        if (pkgInfo != null) {
12690            // Only replace for packages on requested volume
12691            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12692            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12693                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12694            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12695        }
12696        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12697    }
12698
12699    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12700            String packageOfInterest) {
12701        // IMPORTANT: There are two types of permissions: install and runtime.
12702        // Install time permissions are granted when the app is installed to
12703        // all device users and users added in the future. Runtime permissions
12704        // are granted at runtime explicitly to specific users. Normal and signature
12705        // protected permissions are install time permissions. Dangerous permissions
12706        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12707        // otherwise they are runtime permissions. This function does not manage
12708        // runtime permissions except for the case an app targeting Lollipop MR1
12709        // being upgraded to target a newer SDK, in which case dangerous permissions
12710        // are transformed from install time to runtime ones.
12711
12712        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12713        if (ps == null) {
12714            return;
12715        }
12716
12717        PermissionsState permissionsState = ps.getPermissionsState();
12718        PermissionsState origPermissions = permissionsState;
12719
12720        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12721
12722        boolean runtimePermissionsRevoked = false;
12723        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12724
12725        boolean changedInstallPermission = false;
12726
12727        if (replace) {
12728            ps.installPermissionsFixed = false;
12729            if (!ps.isSharedUser()) {
12730                origPermissions = new PermissionsState(permissionsState);
12731                permissionsState.reset();
12732            } else {
12733                // We need to know only about runtime permission changes since the
12734                // calling code always writes the install permissions state but
12735                // the runtime ones are written only if changed. The only cases of
12736                // changed runtime permissions here are promotion of an install to
12737                // runtime and revocation of a runtime from a shared user.
12738                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12739                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12740                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12741                    runtimePermissionsRevoked = true;
12742                }
12743            }
12744        }
12745
12746        permissionsState.setGlobalGids(mGlobalGids);
12747
12748        final int N = pkg.requestedPermissions.size();
12749        for (int i=0; i<N; i++) {
12750            final String name = pkg.requestedPermissions.get(i);
12751            final BasePermission bp = mSettings.mPermissions.get(name);
12752            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12753                    >= Build.VERSION_CODES.M;
12754
12755            if (DEBUG_INSTALL) {
12756                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12757            }
12758
12759            if (bp == null || bp.getSourcePackageSetting() == null) {
12760                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12761                    if (DEBUG_PERMISSIONS) {
12762                        Slog.i(TAG, "Unknown permission " + name
12763                                + " in package " + pkg.packageName);
12764                    }
12765                }
12766                continue;
12767            }
12768
12769
12770            // Limit ephemeral apps to ephemeral allowed permissions.
12771            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12772                if (DEBUG_PERMISSIONS) {
12773                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12774                            + pkg.packageName);
12775                }
12776                continue;
12777            }
12778
12779            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12780                if (DEBUG_PERMISSIONS) {
12781                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12782                            + pkg.packageName);
12783                }
12784                continue;
12785            }
12786
12787            final String perm = bp.getName();
12788            boolean allowedSig = false;
12789            int grant = GRANT_DENIED;
12790
12791            // Keep track of app op permissions.
12792            if (bp.isAppOp()) {
12793                ArraySet<String> pkgs = mAppOpPermissionPackages.get(perm);
12794                if (pkgs == null) {
12795                    pkgs = new ArraySet<>();
12796                    mAppOpPermissionPackages.put(perm, pkgs);
12797                }
12798                pkgs.add(pkg.packageName);
12799            }
12800
12801            if (bp.isNormal()) {
12802                // For all apps normal permissions are install time ones.
12803                grant = GRANT_INSTALL;
12804            } else if (bp.isRuntime()) {
12805                // If a permission review is required for legacy apps we represent
12806                // their permissions as always granted runtime ones since we need
12807                // to keep the review required permission flag per user while an
12808                // install permission's state is shared across all users.
12809                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12810                    // For legacy apps dangerous permissions are install time ones.
12811                    grant = GRANT_INSTALL;
12812                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12813                    // For legacy apps that became modern, install becomes runtime.
12814                    grant = GRANT_UPGRADE;
12815                } else if (mPromoteSystemApps
12816                        && isSystemApp(ps)
12817                        && mExistingSystemPackages.contains(ps.name)) {
12818                    // For legacy system apps, install becomes runtime.
12819                    // We cannot check hasInstallPermission() for system apps since those
12820                    // permissions were granted implicitly and not persisted pre-M.
12821                    grant = GRANT_UPGRADE;
12822                } else {
12823                    // For modern apps keep runtime permissions unchanged.
12824                    grant = GRANT_RUNTIME;
12825                }
12826            } else if (bp.isSignature()) {
12827                // For all apps signature permissions are install time ones.
12828                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12829                if (allowedSig) {
12830                    grant = GRANT_INSTALL;
12831                }
12832            }
12833
12834            if (DEBUG_PERMISSIONS) {
12835                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12836            }
12837
12838            if (grant != GRANT_DENIED) {
12839                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12840                    // If this is an existing, non-system package, then
12841                    // we can't add any new permissions to it.
12842                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12843                        // Except...  if this is a permission that was added
12844                        // to the platform (note: need to only do this when
12845                        // updating the platform).
12846                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12847                            grant = GRANT_DENIED;
12848                        }
12849                    }
12850                }
12851
12852                switch (grant) {
12853                    case GRANT_INSTALL: {
12854                        // Revoke this as runtime permission to handle the case of
12855                        // a runtime permission being downgraded to an install one.
12856                        // Also in permission review mode we keep dangerous permissions
12857                        // for legacy apps
12858                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12859                            if (origPermissions.getRuntimePermissionState(
12860                                    perm, userId) != null) {
12861                                // Revoke the runtime permission and clear the flags.
12862                                origPermissions.revokeRuntimePermission(bp, userId);
12863                                origPermissions.updatePermissionFlags(bp, userId,
12864                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12865                                // If we revoked a permission permission, we have to write.
12866                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12867                                        changedRuntimePermissionUserIds, userId);
12868                            }
12869                        }
12870                        // Grant an install permission.
12871                        if (permissionsState.grantInstallPermission(bp) !=
12872                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12873                            changedInstallPermission = true;
12874                        }
12875                    } break;
12876
12877                    case GRANT_RUNTIME: {
12878                        // Grant previously granted runtime permissions.
12879                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12880                            PermissionState permissionState = origPermissions
12881                                    .getRuntimePermissionState(perm, userId);
12882                            int flags = permissionState != null
12883                                    ? permissionState.getFlags() : 0;
12884                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12885                                // Don't propagate the permission in a permission review mode if
12886                                // the former was revoked, i.e. marked to not propagate on upgrade.
12887                                // Note that in a permission review mode install permissions are
12888                                // represented as constantly granted runtime ones since we need to
12889                                // keep a per user state associated with the permission. Also the
12890                                // revoke on upgrade flag is no longer applicable and is reset.
12891                                final boolean revokeOnUpgrade = (flags & PackageManager
12892                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12893                                if (revokeOnUpgrade) {
12894                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12895                                    // Since we changed the flags, we have to write.
12896                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12897                                            changedRuntimePermissionUserIds, userId);
12898                                }
12899                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12900                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12901                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12902                                        // If we cannot put the permission as it was,
12903                                        // we have to write.
12904                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12905                                                changedRuntimePermissionUserIds, userId);
12906                                    }
12907                                }
12908
12909                                // If the app supports runtime permissions no need for a review.
12910                                if (mPermissionReviewRequired
12911                                        && appSupportsRuntimePermissions
12912                                        && (flags & PackageManager
12913                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12914                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12915                                    // Since we changed the flags, we have to write.
12916                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12917                                            changedRuntimePermissionUserIds, userId);
12918                                }
12919                            } else if (mPermissionReviewRequired
12920                                    && !appSupportsRuntimePermissions) {
12921                                // For legacy apps that need a permission review, every new
12922                                // runtime permission is granted but it is pending a review.
12923                                // We also need to review only platform defined runtime
12924                                // permissions as these are the only ones the platform knows
12925                                // how to disable the API to simulate revocation as legacy
12926                                // apps don't expect to run with revoked permissions.
12927                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12928                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12929                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12930                                        // We changed the flags, hence have to write.
12931                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12932                                                changedRuntimePermissionUserIds, userId);
12933                                    }
12934                                }
12935                                if (permissionsState.grantRuntimePermission(bp, userId)
12936                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12937                                    // We changed the permission, hence have to write.
12938                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12939                                            changedRuntimePermissionUserIds, userId);
12940                                }
12941                            }
12942                            // Propagate the permission flags.
12943                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12944                        }
12945                    } break;
12946
12947                    case GRANT_UPGRADE: {
12948                        // Grant runtime permissions for a previously held install permission.
12949                        PermissionState permissionState = origPermissions
12950                                .getInstallPermissionState(perm);
12951                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12952
12953                        if (origPermissions.revokeInstallPermission(bp)
12954                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12955                            // We will be transferring the permission flags, so clear them.
12956                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12957                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12958                            changedInstallPermission = true;
12959                        }
12960
12961                        // If the permission is not to be promoted to runtime we ignore it and
12962                        // also its other flags as they are not applicable to install permissions.
12963                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12964                            for (int userId : currentUserIds) {
12965                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12966                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12967                                    // Transfer the permission flags.
12968                                    permissionsState.updatePermissionFlags(bp, userId,
12969                                            flags, flags);
12970                                    // If we granted the permission, we have to write.
12971                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12972                                            changedRuntimePermissionUserIds, userId);
12973                                }
12974                            }
12975                        }
12976                    } break;
12977
12978                    default: {
12979                        if (packageOfInterest == null
12980                                || packageOfInterest.equals(pkg.packageName)) {
12981                            if (DEBUG_PERMISSIONS) {
12982                                Slog.i(TAG, "Not granting permission " + perm
12983                                        + " to package " + pkg.packageName
12984                                        + " because it was previously installed without");
12985                            }
12986                        }
12987                    } break;
12988                }
12989            } else {
12990                if (permissionsState.revokeInstallPermission(bp) !=
12991                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12992                    // Also drop the permission flags.
12993                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12994                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12995                    changedInstallPermission = true;
12996                    Slog.i(TAG, "Un-granting permission " + perm
12997                            + " from package " + pkg.packageName
12998                            + " (protectionLevel=" + bp.getProtectionLevel()
12999                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13000                            + ")");
13001                } else if (bp.isAppOp()) {
13002                    // Don't print warning for app op permissions, since it is fine for them
13003                    // not to be granted, there is a UI for the user to decide.
13004                    if (DEBUG_PERMISSIONS
13005                            && (packageOfInterest == null
13006                                    || packageOfInterest.equals(pkg.packageName))) {
13007                        Slog.i(TAG, "Not granting permission " + perm
13008                                + " to package " + pkg.packageName
13009                                + " (protectionLevel=" + bp.getProtectionLevel()
13010                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13011                                + ")");
13012                    }
13013                }
13014            }
13015        }
13016
13017        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13018                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13019            // This is the first that we have heard about this package, so the
13020            // permissions we have now selected are fixed until explicitly
13021            // changed.
13022            ps.installPermissionsFixed = true;
13023        }
13024
13025        // Persist the runtime permissions state for users with changes. If permissions
13026        // were revoked because no app in the shared user declares them we have to
13027        // write synchronously to avoid losing runtime permissions state.
13028        for (int userId : changedRuntimePermissionUserIds) {
13029            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13030        }
13031    }
13032
13033    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13034        boolean allowed = false;
13035        final int NP = PackageParser.NEW_PERMISSIONS.length;
13036        for (int ip=0; ip<NP; ip++) {
13037            final PackageParser.NewPermissionInfo npi
13038                    = PackageParser.NEW_PERMISSIONS[ip];
13039            if (npi.name.equals(perm)
13040                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13041                allowed = true;
13042                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13043                        + pkg.packageName);
13044                break;
13045            }
13046        }
13047        return allowed;
13048    }
13049
13050    /**
13051     * Determines whether a package is whitelisted for a particular privapp permission.
13052     *
13053     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
13054     *
13055     * <p>This handles parent/child apps.
13056     */
13057    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
13058        ArraySet<String> wlPermissions = SystemConfig.getInstance()
13059                .getPrivAppPermissions(pkg.packageName);
13060        // Let's check if this package is whitelisted...
13061        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13062        // If it's not, we'll also tail-recurse to the parent.
13063        return whitelisted ||
13064                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
13065    }
13066
13067    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13068            BasePermission bp, PermissionsState origPermissions) {
13069        boolean oemPermission = bp.isOEM();
13070        boolean privilegedPermission = bp.isPrivileged();
13071        boolean privappPermissionsDisable =
13072                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13073        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
13074        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13075        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13076                && !platformPackage && platformPermission) {
13077            if (!hasPrivappWhitelistEntry(perm, pkg)) {
13078                Slog.w(TAG, "Privileged permission " + perm + " for package "
13079                        + pkg.packageName + " - not in privapp-permissions whitelist");
13080                // Only report violations for apps on system image
13081                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13082                    // it's only a reportable violation if the permission isn't explicitly denied
13083                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13084                            .getPrivAppDenyPermissions(pkg.packageName);
13085                    final boolean permissionViolation =
13086                            deniedPermissions == null || !deniedPermissions.contains(perm);
13087                    if (permissionViolation) {
13088                        if (mPrivappPermissionsViolations == null) {
13089                            mPrivappPermissionsViolations = new ArraySet<>();
13090                        }
13091                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13092                    } else {
13093                        return false;
13094                    }
13095                }
13096                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13097                    return false;
13098                }
13099            }
13100        }
13101        boolean allowed = (compareSignatures(
13102                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
13103                        == PackageManager.SIGNATURE_MATCH)
13104                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13105                        == PackageManager.SIGNATURE_MATCH);
13106        if (!allowed && (privilegedPermission || oemPermission)) {
13107            if (isSystemApp(pkg)) {
13108                // For updated system applications, a privileged/oem permission
13109                // is granted only if it had been defined by the original application.
13110                if (pkg.isUpdatedSystemApp()) {
13111                    final PackageSetting sysPs = mSettings
13112                            .getDisabledSystemPkgLPr(pkg.packageName);
13113                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13114                        // If the original was granted this permission, we take
13115                        // that grant decision as read and propagate it to the
13116                        // update.
13117                        if ((privilegedPermission && sysPs.isPrivileged())
13118                                || (oemPermission && sysPs.isOem()
13119                                        && canGrantOemPermission(sysPs, perm))) {
13120                            allowed = true;
13121                        }
13122                    } else {
13123                        // The system apk may have been updated with an older
13124                        // version of the one on the data partition, but which
13125                        // granted a new system permission that it didn't have
13126                        // before.  In this case we do want to allow the app to
13127                        // now get the new permission if the ancestral apk is
13128                        // privileged to get it.
13129                        if (sysPs != null && sysPs.pkg != null
13130                                && isPackageRequestingPermission(sysPs.pkg, perm)
13131                                && ((privilegedPermission && sysPs.isPrivileged())
13132                                        || (oemPermission && sysPs.isOem()
13133                                                && canGrantOemPermission(sysPs, perm)))) {
13134                            allowed = true;
13135                        }
13136                        // Also if a privileged parent package on the system image or any of
13137                        // its children requested a privileged/oem permission, the updated child
13138                        // packages can also get the permission.
13139                        if (pkg.parentPackage != null) {
13140                            final PackageSetting disabledSysParentPs = mSettings
13141                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13142                            final PackageParser.Package disabledSysParentPkg =
13143                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
13144                                    ? null : disabledSysParentPs.pkg;
13145                            if (disabledSysParentPkg != null
13146                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
13147                                            || (oemPermission && disabledSysParentPs.isOem()))) {
13148                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
13149                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
13150                                    allowed = true;
13151                                } else if (disabledSysParentPkg.childPackages != null) {
13152                                    final int count = disabledSysParentPkg.childPackages.size();
13153                                    for (int i = 0; i < count; i++) {
13154                                        final PackageParser.Package disabledSysChildPkg =
13155                                                disabledSysParentPkg.childPackages.get(i);
13156                                        final PackageSetting disabledSysChildPs =
13157                                                mSettings.getDisabledSystemPkgLPr(
13158                                                        disabledSysChildPkg.packageName);
13159                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
13160                                                && canGrantOemPermission(
13161                                                        disabledSysChildPs, perm)) {
13162                                            allowed = true;
13163                                            break;
13164                                        }
13165                                    }
13166                                }
13167                            }
13168                        }
13169                    }
13170                } else {
13171                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
13172                            || (oemPermission && isOemApp(pkg)
13173                                    && canGrantOemPermission(
13174                                            mSettings.getPackageLPr(pkg.packageName), perm));
13175                }
13176            }
13177        }
13178        if (!allowed) {
13179            if (!allowed
13180                    && bp.isPre23()
13181                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13182                // If this was a previously normal/dangerous permission that got moved
13183                // to a system permission as part of the runtime permission redesign, then
13184                // we still want to blindly grant it to old apps.
13185                allowed = true;
13186            }
13187            if (!allowed && bp.isInstaller()
13188                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13189                // If this permission is to be granted to the system installer and
13190                // this app is an installer, then it gets the permission.
13191                allowed = true;
13192            }
13193            if (!allowed && bp.isVerifier()
13194                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13195                // If this permission is to be granted to the system verifier and
13196                // this app is a verifier, then it gets the permission.
13197                allowed = true;
13198            }
13199            if (!allowed && bp.isPreInstalled()
13200                    && isSystemApp(pkg)) {
13201                // Any pre-installed system app is allowed to get this permission.
13202                allowed = true;
13203            }
13204            if (!allowed && bp.isDevelopment()) {
13205                // For development permissions, a development permission
13206                // is granted only if it was already granted.
13207                allowed = origPermissions.hasInstallPermission(perm);
13208            }
13209            if (!allowed && bp.isSetup()
13210                    && pkg.packageName.equals(mSetupWizardPackage)) {
13211                // If this permission is to be granted to the system setup wizard and
13212                // this app is a setup wizard, then it gets the permission.
13213                allowed = true;
13214            }
13215        }
13216        return allowed;
13217    }
13218
13219    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
13220        if (!ps.isOem()) {
13221            return false;
13222        }
13223        // all oem permissions must explicitly be granted or denied
13224        final Boolean granted =
13225                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
13226        if (granted == null) {
13227            throw new IllegalStateException("OEM permission" + permission + " requested by package "
13228                    + ps.name + " must be explicitly declared granted or not");
13229        }
13230        return Boolean.TRUE == granted;
13231    }
13232
13233    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13234        final int permCount = pkg.requestedPermissions.size();
13235        for (int j = 0; j < permCount; j++) {
13236            String requestedPermission = pkg.requestedPermissions.get(j);
13237            if (permission.equals(requestedPermission)) {
13238                return true;
13239            }
13240        }
13241        return false;
13242    }
13243
13244    final class ActivityIntentResolver
13245            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13246        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13247                boolean defaultOnly, int userId) {
13248            if (!sUserManager.exists(userId)) return null;
13249            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13250            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13251        }
13252
13253        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13254                int userId) {
13255            if (!sUserManager.exists(userId)) return null;
13256            mFlags = flags;
13257            return super.queryIntent(intent, resolvedType,
13258                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13259                    userId);
13260        }
13261
13262        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13263                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13264            if (!sUserManager.exists(userId)) return null;
13265            if (packageActivities == null) {
13266                return null;
13267            }
13268            mFlags = flags;
13269            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13270            final int N = packageActivities.size();
13271            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13272                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13273
13274            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13275            for (int i = 0; i < N; ++i) {
13276                intentFilters = packageActivities.get(i).intents;
13277                if (intentFilters != null && intentFilters.size() > 0) {
13278                    PackageParser.ActivityIntentInfo[] array =
13279                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13280                    intentFilters.toArray(array);
13281                    listCut.add(array);
13282                }
13283            }
13284            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13285        }
13286
13287        /**
13288         * Finds a privileged activity that matches the specified activity names.
13289         */
13290        private PackageParser.Activity findMatchingActivity(
13291                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13292            for (PackageParser.Activity sysActivity : activityList) {
13293                if (sysActivity.info.name.equals(activityInfo.name)) {
13294                    return sysActivity;
13295                }
13296                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13297                    return sysActivity;
13298                }
13299                if (sysActivity.info.targetActivity != null) {
13300                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13301                        return sysActivity;
13302                    }
13303                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13304                        return sysActivity;
13305                    }
13306                }
13307            }
13308            return null;
13309        }
13310
13311        public class IterGenerator<E> {
13312            public Iterator<E> generate(ActivityIntentInfo info) {
13313                return null;
13314            }
13315        }
13316
13317        public class ActionIterGenerator extends IterGenerator<String> {
13318            @Override
13319            public Iterator<String> generate(ActivityIntentInfo info) {
13320                return info.actionsIterator();
13321            }
13322        }
13323
13324        public class CategoriesIterGenerator extends IterGenerator<String> {
13325            @Override
13326            public Iterator<String> generate(ActivityIntentInfo info) {
13327                return info.categoriesIterator();
13328            }
13329        }
13330
13331        public class SchemesIterGenerator extends IterGenerator<String> {
13332            @Override
13333            public Iterator<String> generate(ActivityIntentInfo info) {
13334                return info.schemesIterator();
13335            }
13336        }
13337
13338        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13339            @Override
13340            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13341                return info.authoritiesIterator();
13342            }
13343        }
13344
13345        /**
13346         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13347         * MODIFIED. Do not pass in a list that should not be changed.
13348         */
13349        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13350                IterGenerator<T> generator, Iterator<T> searchIterator) {
13351            // loop through the set of actions; every one must be found in the intent filter
13352            while (searchIterator.hasNext()) {
13353                // we must have at least one filter in the list to consider a match
13354                if (intentList.size() == 0) {
13355                    break;
13356                }
13357
13358                final T searchAction = searchIterator.next();
13359
13360                // loop through the set of intent filters
13361                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13362                while (intentIter.hasNext()) {
13363                    final ActivityIntentInfo intentInfo = intentIter.next();
13364                    boolean selectionFound = false;
13365
13366                    // loop through the intent filter's selection criteria; at least one
13367                    // of them must match the searched criteria
13368                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13369                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13370                        final T intentSelection = intentSelectionIter.next();
13371                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13372                            selectionFound = true;
13373                            break;
13374                        }
13375                    }
13376
13377                    // the selection criteria wasn't found in this filter's set; this filter
13378                    // is not a potential match
13379                    if (!selectionFound) {
13380                        intentIter.remove();
13381                    }
13382                }
13383            }
13384        }
13385
13386        private boolean isProtectedAction(ActivityIntentInfo filter) {
13387            final Iterator<String> actionsIter = filter.actionsIterator();
13388            while (actionsIter != null && actionsIter.hasNext()) {
13389                final String filterAction = actionsIter.next();
13390                if (PROTECTED_ACTIONS.contains(filterAction)) {
13391                    return true;
13392                }
13393            }
13394            return false;
13395        }
13396
13397        /**
13398         * Adjusts the priority of the given intent filter according to policy.
13399         * <p>
13400         * <ul>
13401         * <li>The priority for non privileged applications is capped to '0'</li>
13402         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13403         * <li>The priority for unbundled updates to privileged applications is capped to the
13404         *      priority defined on the system partition</li>
13405         * </ul>
13406         * <p>
13407         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13408         * allowed to obtain any priority on any action.
13409         */
13410        private void adjustPriority(
13411                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13412            // nothing to do; priority is fine as-is
13413            if (intent.getPriority() <= 0) {
13414                return;
13415            }
13416
13417            final ActivityInfo activityInfo = intent.activity.info;
13418            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13419
13420            final boolean privilegedApp =
13421                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13422            if (!privilegedApp) {
13423                // non-privileged applications can never define a priority >0
13424                if (DEBUG_FILTERS) {
13425                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13426                            + " package: " + applicationInfo.packageName
13427                            + " activity: " + intent.activity.className
13428                            + " origPrio: " + intent.getPriority());
13429                }
13430                intent.setPriority(0);
13431                return;
13432            }
13433
13434            if (systemActivities == null) {
13435                // the system package is not disabled; we're parsing the system partition
13436                if (isProtectedAction(intent)) {
13437                    if (mDeferProtectedFilters) {
13438                        // We can't deal with these just yet. No component should ever obtain a
13439                        // >0 priority for a protected actions, with ONE exception -- the setup
13440                        // wizard. The setup wizard, however, cannot be known until we're able to
13441                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13442                        // until all intent filters have been processed. Chicken, meet egg.
13443                        // Let the filter temporarily have a high priority and rectify the
13444                        // priorities after all system packages have been scanned.
13445                        mProtectedFilters.add(intent);
13446                        if (DEBUG_FILTERS) {
13447                            Slog.i(TAG, "Protected action; save for later;"
13448                                    + " package: " + applicationInfo.packageName
13449                                    + " activity: " + intent.activity.className
13450                                    + " origPrio: " + intent.getPriority());
13451                        }
13452                        return;
13453                    } else {
13454                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13455                            Slog.i(TAG, "No setup wizard;"
13456                                + " All protected intents capped to priority 0");
13457                        }
13458                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13459                            if (DEBUG_FILTERS) {
13460                                Slog.i(TAG, "Found setup wizard;"
13461                                    + " allow priority " + intent.getPriority() + ";"
13462                                    + " package: " + intent.activity.info.packageName
13463                                    + " activity: " + intent.activity.className
13464                                    + " priority: " + intent.getPriority());
13465                            }
13466                            // setup wizard gets whatever it wants
13467                            return;
13468                        }
13469                        if (DEBUG_FILTERS) {
13470                            Slog.i(TAG, "Protected action; cap priority to 0;"
13471                                    + " package: " + intent.activity.info.packageName
13472                                    + " activity: " + intent.activity.className
13473                                    + " origPrio: " + intent.getPriority());
13474                        }
13475                        intent.setPriority(0);
13476                        return;
13477                    }
13478                }
13479                // privileged apps on the system image get whatever priority they request
13480                return;
13481            }
13482
13483            // privileged app unbundled update ... try to find the same activity
13484            final PackageParser.Activity foundActivity =
13485                    findMatchingActivity(systemActivities, activityInfo);
13486            if (foundActivity == null) {
13487                // this is a new activity; it cannot obtain >0 priority
13488                if (DEBUG_FILTERS) {
13489                    Slog.i(TAG, "New activity; cap priority to 0;"
13490                            + " package: " + applicationInfo.packageName
13491                            + " activity: " + intent.activity.className
13492                            + " origPrio: " + intent.getPriority());
13493                }
13494                intent.setPriority(0);
13495                return;
13496            }
13497
13498            // found activity, now check for filter equivalence
13499
13500            // a shallow copy is enough; we modify the list, not its contents
13501            final List<ActivityIntentInfo> intentListCopy =
13502                    new ArrayList<>(foundActivity.intents);
13503            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13504
13505            // find matching action subsets
13506            final Iterator<String> actionsIterator = intent.actionsIterator();
13507            if (actionsIterator != null) {
13508                getIntentListSubset(
13509                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13510                if (intentListCopy.size() == 0) {
13511                    // no more intents to match; we're not equivalent
13512                    if (DEBUG_FILTERS) {
13513                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13514                                + " package: " + applicationInfo.packageName
13515                                + " activity: " + intent.activity.className
13516                                + " origPrio: " + intent.getPriority());
13517                    }
13518                    intent.setPriority(0);
13519                    return;
13520                }
13521            }
13522
13523            // find matching category subsets
13524            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13525            if (categoriesIterator != null) {
13526                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13527                        categoriesIterator);
13528                if (intentListCopy.size() == 0) {
13529                    // no more intents to match; we're not equivalent
13530                    if (DEBUG_FILTERS) {
13531                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13532                                + " package: " + applicationInfo.packageName
13533                                + " activity: " + intent.activity.className
13534                                + " origPrio: " + intent.getPriority());
13535                    }
13536                    intent.setPriority(0);
13537                    return;
13538                }
13539            }
13540
13541            // find matching schemes subsets
13542            final Iterator<String> schemesIterator = intent.schemesIterator();
13543            if (schemesIterator != null) {
13544                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13545                        schemesIterator);
13546                if (intentListCopy.size() == 0) {
13547                    // no more intents to match; we're not equivalent
13548                    if (DEBUG_FILTERS) {
13549                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13550                                + " package: " + applicationInfo.packageName
13551                                + " activity: " + intent.activity.className
13552                                + " origPrio: " + intent.getPriority());
13553                    }
13554                    intent.setPriority(0);
13555                    return;
13556                }
13557            }
13558
13559            // find matching authorities subsets
13560            final Iterator<IntentFilter.AuthorityEntry>
13561                    authoritiesIterator = intent.authoritiesIterator();
13562            if (authoritiesIterator != null) {
13563                getIntentListSubset(intentListCopy,
13564                        new AuthoritiesIterGenerator(),
13565                        authoritiesIterator);
13566                if (intentListCopy.size() == 0) {
13567                    // no more intents to match; we're not equivalent
13568                    if (DEBUG_FILTERS) {
13569                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13570                                + " package: " + applicationInfo.packageName
13571                                + " activity: " + intent.activity.className
13572                                + " origPrio: " + intent.getPriority());
13573                    }
13574                    intent.setPriority(0);
13575                    return;
13576                }
13577            }
13578
13579            // we found matching filter(s); app gets the max priority of all intents
13580            int cappedPriority = 0;
13581            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13582                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13583            }
13584            if (intent.getPriority() > cappedPriority) {
13585                if (DEBUG_FILTERS) {
13586                    Slog.i(TAG, "Found matching filter(s);"
13587                            + " cap priority to " + cappedPriority + ";"
13588                            + " package: " + applicationInfo.packageName
13589                            + " activity: " + intent.activity.className
13590                            + " origPrio: " + intent.getPriority());
13591                }
13592                intent.setPriority(cappedPriority);
13593                return;
13594            }
13595            // all this for nothing; the requested priority was <= what was on the system
13596        }
13597
13598        public final void addActivity(PackageParser.Activity a, String type) {
13599            mActivities.put(a.getComponentName(), a);
13600            if (DEBUG_SHOW_INFO)
13601                Log.v(
13602                TAG, "  " + type + " " +
13603                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13604            if (DEBUG_SHOW_INFO)
13605                Log.v(TAG, "    Class=" + a.info.name);
13606            final int NI = a.intents.size();
13607            for (int j=0; j<NI; j++) {
13608                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13609                if ("activity".equals(type)) {
13610                    final PackageSetting ps =
13611                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13612                    final List<PackageParser.Activity> systemActivities =
13613                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13614                    adjustPriority(systemActivities, intent);
13615                }
13616                if (DEBUG_SHOW_INFO) {
13617                    Log.v(TAG, "    IntentFilter:");
13618                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13619                }
13620                if (!intent.debugCheck()) {
13621                    Log.w(TAG, "==> For Activity " + a.info.name);
13622                }
13623                addFilter(intent);
13624            }
13625        }
13626
13627        public final void removeActivity(PackageParser.Activity a, String type) {
13628            mActivities.remove(a.getComponentName());
13629            if (DEBUG_SHOW_INFO) {
13630                Log.v(TAG, "  " + type + " "
13631                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13632                                : a.info.name) + ":");
13633                Log.v(TAG, "    Class=" + a.info.name);
13634            }
13635            final int NI = a.intents.size();
13636            for (int j=0; j<NI; j++) {
13637                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13638                if (DEBUG_SHOW_INFO) {
13639                    Log.v(TAG, "    IntentFilter:");
13640                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13641                }
13642                removeFilter(intent);
13643            }
13644        }
13645
13646        @Override
13647        protected boolean allowFilterResult(
13648                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13649            ActivityInfo filterAi = filter.activity.info;
13650            for (int i=dest.size()-1; i>=0; i--) {
13651                ActivityInfo destAi = dest.get(i).activityInfo;
13652                if (destAi.name == filterAi.name
13653                        && destAi.packageName == filterAi.packageName) {
13654                    return false;
13655                }
13656            }
13657            return true;
13658        }
13659
13660        @Override
13661        protected ActivityIntentInfo[] newArray(int size) {
13662            return new ActivityIntentInfo[size];
13663        }
13664
13665        @Override
13666        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13667            if (!sUserManager.exists(userId)) return true;
13668            PackageParser.Package p = filter.activity.owner;
13669            if (p != null) {
13670                PackageSetting ps = (PackageSetting)p.mExtras;
13671                if (ps != null) {
13672                    // System apps are never considered stopped for purposes of
13673                    // filtering, because there may be no way for the user to
13674                    // actually re-launch them.
13675                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13676                            && ps.getStopped(userId);
13677                }
13678            }
13679            return false;
13680        }
13681
13682        @Override
13683        protected boolean isPackageForFilter(String packageName,
13684                PackageParser.ActivityIntentInfo info) {
13685            return packageName.equals(info.activity.owner.packageName);
13686        }
13687
13688        @Override
13689        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13690                int match, int userId) {
13691            if (!sUserManager.exists(userId)) return null;
13692            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13693                return null;
13694            }
13695            final PackageParser.Activity activity = info.activity;
13696            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13697            if (ps == null) {
13698                return null;
13699            }
13700            final PackageUserState userState = ps.readUserState(userId);
13701            ActivityInfo ai =
13702                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13703            if (ai == null) {
13704                return null;
13705            }
13706            final boolean matchExplicitlyVisibleOnly =
13707                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13708            final boolean matchVisibleToInstantApp =
13709                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13710            final boolean componentVisible =
13711                    matchVisibleToInstantApp
13712                    && info.isVisibleToInstantApp()
13713                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13714            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13715            // throw out filters that aren't visible to ephemeral apps
13716            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13717                return null;
13718            }
13719            // throw out instant app filters if we're not explicitly requesting them
13720            if (!matchInstantApp && userState.instantApp) {
13721                return null;
13722            }
13723            // throw out instant app filters if updates are available; will trigger
13724            // instant app resolution
13725            if (userState.instantApp && ps.isUpdateAvailable()) {
13726                return null;
13727            }
13728            final ResolveInfo res = new ResolveInfo();
13729            res.activityInfo = ai;
13730            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13731                res.filter = info;
13732            }
13733            if (info != null) {
13734                res.handleAllWebDataURI = info.handleAllWebDataURI();
13735            }
13736            res.priority = info.getPriority();
13737            res.preferredOrder = activity.owner.mPreferredOrder;
13738            //System.out.println("Result: " + res.activityInfo.className +
13739            //                   " = " + res.priority);
13740            res.match = match;
13741            res.isDefault = info.hasDefault;
13742            res.labelRes = info.labelRes;
13743            res.nonLocalizedLabel = info.nonLocalizedLabel;
13744            if (userNeedsBadging(userId)) {
13745                res.noResourceId = true;
13746            } else {
13747                res.icon = info.icon;
13748            }
13749            res.iconResourceId = info.icon;
13750            res.system = res.activityInfo.applicationInfo.isSystemApp();
13751            res.isInstantAppAvailable = userState.instantApp;
13752            return res;
13753        }
13754
13755        @Override
13756        protected void sortResults(List<ResolveInfo> results) {
13757            Collections.sort(results, mResolvePrioritySorter);
13758        }
13759
13760        @Override
13761        protected void dumpFilter(PrintWriter out, String prefix,
13762                PackageParser.ActivityIntentInfo filter) {
13763            out.print(prefix); out.print(
13764                    Integer.toHexString(System.identityHashCode(filter.activity)));
13765                    out.print(' ');
13766                    filter.activity.printComponentShortName(out);
13767                    out.print(" filter ");
13768                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13769        }
13770
13771        @Override
13772        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13773            return filter.activity;
13774        }
13775
13776        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13777            PackageParser.Activity activity = (PackageParser.Activity)label;
13778            out.print(prefix); out.print(
13779                    Integer.toHexString(System.identityHashCode(activity)));
13780                    out.print(' ');
13781                    activity.printComponentShortName(out);
13782            if (count > 1) {
13783                out.print(" ("); out.print(count); out.print(" filters)");
13784            }
13785            out.println();
13786        }
13787
13788        // Keys are String (activity class name), values are Activity.
13789        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13790                = new ArrayMap<ComponentName, PackageParser.Activity>();
13791        private int mFlags;
13792    }
13793
13794    private final class ServiceIntentResolver
13795            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13796        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13797                boolean defaultOnly, int userId) {
13798            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13799            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13800        }
13801
13802        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13803                int userId) {
13804            if (!sUserManager.exists(userId)) return null;
13805            mFlags = flags;
13806            return super.queryIntent(intent, resolvedType,
13807                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13808                    userId);
13809        }
13810
13811        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13812                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13813            if (!sUserManager.exists(userId)) return null;
13814            if (packageServices == null) {
13815                return null;
13816            }
13817            mFlags = flags;
13818            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13819            final int N = packageServices.size();
13820            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13821                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13822
13823            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13824            for (int i = 0; i < N; ++i) {
13825                intentFilters = packageServices.get(i).intents;
13826                if (intentFilters != null && intentFilters.size() > 0) {
13827                    PackageParser.ServiceIntentInfo[] array =
13828                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13829                    intentFilters.toArray(array);
13830                    listCut.add(array);
13831                }
13832            }
13833            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13834        }
13835
13836        public final void addService(PackageParser.Service s) {
13837            mServices.put(s.getComponentName(), s);
13838            if (DEBUG_SHOW_INFO) {
13839                Log.v(TAG, "  "
13840                        + (s.info.nonLocalizedLabel != null
13841                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13842                Log.v(TAG, "    Class=" + s.info.name);
13843            }
13844            final int NI = s.intents.size();
13845            int j;
13846            for (j=0; j<NI; j++) {
13847                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13848                if (DEBUG_SHOW_INFO) {
13849                    Log.v(TAG, "    IntentFilter:");
13850                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13851                }
13852                if (!intent.debugCheck()) {
13853                    Log.w(TAG, "==> For Service " + s.info.name);
13854                }
13855                addFilter(intent);
13856            }
13857        }
13858
13859        public final void removeService(PackageParser.Service s) {
13860            mServices.remove(s.getComponentName());
13861            if (DEBUG_SHOW_INFO) {
13862                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13863                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13864                Log.v(TAG, "    Class=" + s.info.name);
13865            }
13866            final int NI = s.intents.size();
13867            int j;
13868            for (j=0; j<NI; j++) {
13869                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13870                if (DEBUG_SHOW_INFO) {
13871                    Log.v(TAG, "    IntentFilter:");
13872                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13873                }
13874                removeFilter(intent);
13875            }
13876        }
13877
13878        @Override
13879        protected boolean allowFilterResult(
13880                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13881            ServiceInfo filterSi = filter.service.info;
13882            for (int i=dest.size()-1; i>=0; i--) {
13883                ServiceInfo destAi = dest.get(i).serviceInfo;
13884                if (destAi.name == filterSi.name
13885                        && destAi.packageName == filterSi.packageName) {
13886                    return false;
13887                }
13888            }
13889            return true;
13890        }
13891
13892        @Override
13893        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13894            return new PackageParser.ServiceIntentInfo[size];
13895        }
13896
13897        @Override
13898        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13899            if (!sUserManager.exists(userId)) return true;
13900            PackageParser.Package p = filter.service.owner;
13901            if (p != null) {
13902                PackageSetting ps = (PackageSetting)p.mExtras;
13903                if (ps != null) {
13904                    // System apps are never considered stopped for purposes of
13905                    // filtering, because there may be no way for the user to
13906                    // actually re-launch them.
13907                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13908                            && ps.getStopped(userId);
13909                }
13910            }
13911            return false;
13912        }
13913
13914        @Override
13915        protected boolean isPackageForFilter(String packageName,
13916                PackageParser.ServiceIntentInfo info) {
13917            return packageName.equals(info.service.owner.packageName);
13918        }
13919
13920        @Override
13921        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13922                int match, int userId) {
13923            if (!sUserManager.exists(userId)) return null;
13924            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13925            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13926                return null;
13927            }
13928            final PackageParser.Service service = info.service;
13929            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13930            if (ps == null) {
13931                return null;
13932            }
13933            final PackageUserState userState = ps.readUserState(userId);
13934            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13935                    userState, userId);
13936            if (si == null) {
13937                return null;
13938            }
13939            final boolean matchVisibleToInstantApp =
13940                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13941            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13942            // throw out filters that aren't visible to ephemeral apps
13943            if (matchVisibleToInstantApp
13944                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13945                return null;
13946            }
13947            // throw out ephemeral filters if we're not explicitly requesting them
13948            if (!isInstantApp && userState.instantApp) {
13949                return null;
13950            }
13951            // throw out instant app filters if updates are available; will trigger
13952            // instant app resolution
13953            if (userState.instantApp && ps.isUpdateAvailable()) {
13954                return null;
13955            }
13956            final ResolveInfo res = new ResolveInfo();
13957            res.serviceInfo = si;
13958            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13959                res.filter = filter;
13960            }
13961            res.priority = info.getPriority();
13962            res.preferredOrder = service.owner.mPreferredOrder;
13963            res.match = match;
13964            res.isDefault = info.hasDefault;
13965            res.labelRes = info.labelRes;
13966            res.nonLocalizedLabel = info.nonLocalizedLabel;
13967            res.icon = info.icon;
13968            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13969            return res;
13970        }
13971
13972        @Override
13973        protected void sortResults(List<ResolveInfo> results) {
13974            Collections.sort(results, mResolvePrioritySorter);
13975        }
13976
13977        @Override
13978        protected void dumpFilter(PrintWriter out, String prefix,
13979                PackageParser.ServiceIntentInfo filter) {
13980            out.print(prefix); out.print(
13981                    Integer.toHexString(System.identityHashCode(filter.service)));
13982                    out.print(' ');
13983                    filter.service.printComponentShortName(out);
13984                    out.print(" filter ");
13985                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13986        }
13987
13988        @Override
13989        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13990            return filter.service;
13991        }
13992
13993        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13994            PackageParser.Service service = (PackageParser.Service)label;
13995            out.print(prefix); out.print(
13996                    Integer.toHexString(System.identityHashCode(service)));
13997                    out.print(' ');
13998                    service.printComponentShortName(out);
13999            if (count > 1) {
14000                out.print(" ("); out.print(count); out.print(" filters)");
14001            }
14002            out.println();
14003        }
14004
14005//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14006//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14007//            final List<ResolveInfo> retList = Lists.newArrayList();
14008//            while (i.hasNext()) {
14009//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14010//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14011//                    retList.add(resolveInfo);
14012//                }
14013//            }
14014//            return retList;
14015//        }
14016
14017        // Keys are String (activity class name), values are Activity.
14018        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14019                = new ArrayMap<ComponentName, PackageParser.Service>();
14020        private int mFlags;
14021    }
14022
14023    private final class ProviderIntentResolver
14024            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14025        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14026                boolean defaultOnly, int userId) {
14027            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14028            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14029        }
14030
14031        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14032                int userId) {
14033            if (!sUserManager.exists(userId))
14034                return null;
14035            mFlags = flags;
14036            return super.queryIntent(intent, resolvedType,
14037                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14038                    userId);
14039        }
14040
14041        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14042                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14043            if (!sUserManager.exists(userId))
14044                return null;
14045            if (packageProviders == null) {
14046                return null;
14047            }
14048            mFlags = flags;
14049            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14050            final int N = packageProviders.size();
14051            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14052                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14053
14054            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14055            for (int i = 0; i < N; ++i) {
14056                intentFilters = packageProviders.get(i).intents;
14057                if (intentFilters != null && intentFilters.size() > 0) {
14058                    PackageParser.ProviderIntentInfo[] array =
14059                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14060                    intentFilters.toArray(array);
14061                    listCut.add(array);
14062                }
14063            }
14064            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14065        }
14066
14067        public final void addProvider(PackageParser.Provider p) {
14068            if (mProviders.containsKey(p.getComponentName())) {
14069                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14070                return;
14071            }
14072
14073            mProviders.put(p.getComponentName(), p);
14074            if (DEBUG_SHOW_INFO) {
14075                Log.v(TAG, "  "
14076                        + (p.info.nonLocalizedLabel != null
14077                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14078                Log.v(TAG, "    Class=" + p.info.name);
14079            }
14080            final int NI = p.intents.size();
14081            int j;
14082            for (j = 0; j < NI; j++) {
14083                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14084                if (DEBUG_SHOW_INFO) {
14085                    Log.v(TAG, "    IntentFilter:");
14086                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14087                }
14088                if (!intent.debugCheck()) {
14089                    Log.w(TAG, "==> For Provider " + p.info.name);
14090                }
14091                addFilter(intent);
14092            }
14093        }
14094
14095        public final void removeProvider(PackageParser.Provider p) {
14096            mProviders.remove(p.getComponentName());
14097            if (DEBUG_SHOW_INFO) {
14098                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14099                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14100                Log.v(TAG, "    Class=" + p.info.name);
14101            }
14102            final int NI = p.intents.size();
14103            int j;
14104            for (j = 0; j < NI; j++) {
14105                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14106                if (DEBUG_SHOW_INFO) {
14107                    Log.v(TAG, "    IntentFilter:");
14108                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14109                }
14110                removeFilter(intent);
14111            }
14112        }
14113
14114        @Override
14115        protected boolean allowFilterResult(
14116                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14117            ProviderInfo filterPi = filter.provider.info;
14118            for (int i = dest.size() - 1; i >= 0; i--) {
14119                ProviderInfo destPi = dest.get(i).providerInfo;
14120                if (destPi.name == filterPi.name
14121                        && destPi.packageName == filterPi.packageName) {
14122                    return false;
14123                }
14124            }
14125            return true;
14126        }
14127
14128        @Override
14129        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14130            return new PackageParser.ProviderIntentInfo[size];
14131        }
14132
14133        @Override
14134        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14135            if (!sUserManager.exists(userId))
14136                return true;
14137            PackageParser.Package p = filter.provider.owner;
14138            if (p != null) {
14139                PackageSetting ps = (PackageSetting) p.mExtras;
14140                if (ps != null) {
14141                    // System apps are never considered stopped for purposes of
14142                    // filtering, because there may be no way for the user to
14143                    // actually re-launch them.
14144                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14145                            && ps.getStopped(userId);
14146                }
14147            }
14148            return false;
14149        }
14150
14151        @Override
14152        protected boolean isPackageForFilter(String packageName,
14153                PackageParser.ProviderIntentInfo info) {
14154            return packageName.equals(info.provider.owner.packageName);
14155        }
14156
14157        @Override
14158        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14159                int match, int userId) {
14160            if (!sUserManager.exists(userId))
14161                return null;
14162            final PackageParser.ProviderIntentInfo info = filter;
14163            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14164                return null;
14165            }
14166            final PackageParser.Provider provider = info.provider;
14167            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14168            if (ps == null) {
14169                return null;
14170            }
14171            final PackageUserState userState = ps.readUserState(userId);
14172            final boolean matchVisibleToInstantApp =
14173                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14174            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14175            // throw out filters that aren't visible to instant applications
14176            if (matchVisibleToInstantApp
14177                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14178                return null;
14179            }
14180            // throw out instant application filters if we're not explicitly requesting them
14181            if (!isInstantApp && userState.instantApp) {
14182                return null;
14183            }
14184            // throw out instant application filters if updates are available; will trigger
14185            // instant application resolution
14186            if (userState.instantApp && ps.isUpdateAvailable()) {
14187                return null;
14188            }
14189            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14190                    userState, userId);
14191            if (pi == null) {
14192                return null;
14193            }
14194            final ResolveInfo res = new ResolveInfo();
14195            res.providerInfo = pi;
14196            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14197                res.filter = filter;
14198            }
14199            res.priority = info.getPriority();
14200            res.preferredOrder = provider.owner.mPreferredOrder;
14201            res.match = match;
14202            res.isDefault = info.hasDefault;
14203            res.labelRes = info.labelRes;
14204            res.nonLocalizedLabel = info.nonLocalizedLabel;
14205            res.icon = info.icon;
14206            res.system = res.providerInfo.applicationInfo.isSystemApp();
14207            return res;
14208        }
14209
14210        @Override
14211        protected void sortResults(List<ResolveInfo> results) {
14212            Collections.sort(results, mResolvePrioritySorter);
14213        }
14214
14215        @Override
14216        protected void dumpFilter(PrintWriter out, String prefix,
14217                PackageParser.ProviderIntentInfo filter) {
14218            out.print(prefix);
14219            out.print(
14220                    Integer.toHexString(System.identityHashCode(filter.provider)));
14221            out.print(' ');
14222            filter.provider.printComponentShortName(out);
14223            out.print(" filter ");
14224            out.println(Integer.toHexString(System.identityHashCode(filter)));
14225        }
14226
14227        @Override
14228        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14229            return filter.provider;
14230        }
14231
14232        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14233            PackageParser.Provider provider = (PackageParser.Provider)label;
14234            out.print(prefix); out.print(
14235                    Integer.toHexString(System.identityHashCode(provider)));
14236                    out.print(' ');
14237                    provider.printComponentShortName(out);
14238            if (count > 1) {
14239                out.print(" ("); out.print(count); out.print(" filters)");
14240            }
14241            out.println();
14242        }
14243
14244        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14245                = new ArrayMap<ComponentName, PackageParser.Provider>();
14246        private int mFlags;
14247    }
14248
14249    static final class EphemeralIntentResolver
14250            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14251        /**
14252         * The result that has the highest defined order. Ordering applies on a
14253         * per-package basis. Mapping is from package name to Pair of order and
14254         * EphemeralResolveInfo.
14255         * <p>
14256         * NOTE: This is implemented as a field variable for convenience and efficiency.
14257         * By having a field variable, we're able to track filter ordering as soon as
14258         * a non-zero order is defined. Otherwise, multiple loops across the result set
14259         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14260         * this needs to be contained entirely within {@link #filterResults}.
14261         */
14262        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14263
14264        @Override
14265        protected AuxiliaryResolveInfo[] newArray(int size) {
14266            return new AuxiliaryResolveInfo[size];
14267        }
14268
14269        @Override
14270        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14271            return true;
14272        }
14273
14274        @Override
14275        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14276                int userId) {
14277            if (!sUserManager.exists(userId)) {
14278                return null;
14279            }
14280            final String packageName = responseObj.resolveInfo.getPackageName();
14281            final Integer order = responseObj.getOrder();
14282            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14283                    mOrderResult.get(packageName);
14284            // ordering is enabled and this item's order isn't high enough
14285            if (lastOrderResult != null && lastOrderResult.first >= order) {
14286                return null;
14287            }
14288            final InstantAppResolveInfo res = responseObj.resolveInfo;
14289            if (order > 0) {
14290                // non-zero order, enable ordering
14291                mOrderResult.put(packageName, new Pair<>(order, res));
14292            }
14293            return responseObj;
14294        }
14295
14296        @Override
14297        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14298            // only do work if ordering is enabled [most of the time it won't be]
14299            if (mOrderResult.size() == 0) {
14300                return;
14301            }
14302            int resultSize = results.size();
14303            for (int i = 0; i < resultSize; i++) {
14304                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14305                final String packageName = info.getPackageName();
14306                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14307                if (savedInfo == null) {
14308                    // package doesn't having ordering
14309                    continue;
14310                }
14311                if (savedInfo.second == info) {
14312                    // circled back to the highest ordered item; remove from order list
14313                    mOrderResult.remove(packageName);
14314                    if (mOrderResult.size() == 0) {
14315                        // no more ordered items
14316                        break;
14317                    }
14318                    continue;
14319                }
14320                // item has a worse order, remove it from the result list
14321                results.remove(i);
14322                resultSize--;
14323                i--;
14324            }
14325        }
14326    }
14327
14328    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14329            new Comparator<ResolveInfo>() {
14330        public int compare(ResolveInfo r1, ResolveInfo r2) {
14331            int v1 = r1.priority;
14332            int v2 = r2.priority;
14333            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14334            if (v1 != v2) {
14335                return (v1 > v2) ? -1 : 1;
14336            }
14337            v1 = r1.preferredOrder;
14338            v2 = r2.preferredOrder;
14339            if (v1 != v2) {
14340                return (v1 > v2) ? -1 : 1;
14341            }
14342            if (r1.isDefault != r2.isDefault) {
14343                return r1.isDefault ? -1 : 1;
14344            }
14345            v1 = r1.match;
14346            v2 = r2.match;
14347            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14348            if (v1 != v2) {
14349                return (v1 > v2) ? -1 : 1;
14350            }
14351            if (r1.system != r2.system) {
14352                return r1.system ? -1 : 1;
14353            }
14354            if (r1.activityInfo != null) {
14355                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14356            }
14357            if (r1.serviceInfo != null) {
14358                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14359            }
14360            if (r1.providerInfo != null) {
14361                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14362            }
14363            return 0;
14364        }
14365    };
14366
14367    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14368            new Comparator<ProviderInfo>() {
14369        public int compare(ProviderInfo p1, ProviderInfo p2) {
14370            final int v1 = p1.initOrder;
14371            final int v2 = p2.initOrder;
14372            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14373        }
14374    };
14375
14376    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14377            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14378            final int[] userIds) {
14379        mHandler.post(new Runnable() {
14380            @Override
14381            public void run() {
14382                try {
14383                    final IActivityManager am = ActivityManager.getService();
14384                    if (am == null) return;
14385                    final int[] resolvedUserIds;
14386                    if (userIds == null) {
14387                        resolvedUserIds = am.getRunningUserIds();
14388                    } else {
14389                        resolvedUserIds = userIds;
14390                    }
14391                    for (int id : resolvedUserIds) {
14392                        final Intent intent = new Intent(action,
14393                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14394                        if (extras != null) {
14395                            intent.putExtras(extras);
14396                        }
14397                        if (targetPkg != null) {
14398                            intent.setPackage(targetPkg);
14399                        }
14400                        // Modify the UID when posting to other users
14401                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14402                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14403                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14404                            intent.putExtra(Intent.EXTRA_UID, uid);
14405                        }
14406                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14407                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14408                        if (DEBUG_BROADCASTS) {
14409                            RuntimeException here = new RuntimeException("here");
14410                            here.fillInStackTrace();
14411                            Slog.d(TAG, "Sending to user " + id + ": "
14412                                    + intent.toShortString(false, true, false, false)
14413                                    + " " + intent.getExtras(), here);
14414                        }
14415                        am.broadcastIntent(null, intent, null, finishedReceiver,
14416                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14417                                null, finishedReceiver != null, false, id);
14418                    }
14419                } catch (RemoteException ex) {
14420                }
14421            }
14422        });
14423    }
14424
14425    /**
14426     * Check if the external storage media is available. This is true if there
14427     * is a mounted external storage medium or if the external storage is
14428     * emulated.
14429     */
14430    private boolean isExternalMediaAvailable() {
14431        return mMediaMounted || Environment.isExternalStorageEmulated();
14432    }
14433
14434    @Override
14435    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14436        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14437            return null;
14438        }
14439        // writer
14440        synchronized (mPackages) {
14441            if (!isExternalMediaAvailable()) {
14442                // If the external storage is no longer mounted at this point,
14443                // the caller may not have been able to delete all of this
14444                // packages files and can not delete any more.  Bail.
14445                return null;
14446            }
14447            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14448            if (lastPackage != null) {
14449                pkgs.remove(lastPackage);
14450            }
14451            if (pkgs.size() > 0) {
14452                return pkgs.get(0);
14453            }
14454        }
14455        return null;
14456    }
14457
14458    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14459        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14460                userId, andCode ? 1 : 0, packageName);
14461        if (mSystemReady) {
14462            msg.sendToTarget();
14463        } else {
14464            if (mPostSystemReadyMessages == null) {
14465                mPostSystemReadyMessages = new ArrayList<>();
14466            }
14467            mPostSystemReadyMessages.add(msg);
14468        }
14469    }
14470
14471    void startCleaningPackages() {
14472        // reader
14473        if (!isExternalMediaAvailable()) {
14474            return;
14475        }
14476        synchronized (mPackages) {
14477            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14478                return;
14479            }
14480        }
14481        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14482        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14483        IActivityManager am = ActivityManager.getService();
14484        if (am != null) {
14485            int dcsUid = -1;
14486            synchronized (mPackages) {
14487                if (!mDefaultContainerWhitelisted) {
14488                    mDefaultContainerWhitelisted = true;
14489                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14490                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14491                }
14492            }
14493            try {
14494                if (dcsUid > 0) {
14495                    am.backgroundWhitelistUid(dcsUid);
14496                }
14497                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14498                        UserHandle.USER_SYSTEM);
14499            } catch (RemoteException e) {
14500            }
14501        }
14502    }
14503
14504    @Override
14505    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14506            int installFlags, String installerPackageName, int userId) {
14507        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14508
14509        final int callingUid = Binder.getCallingUid();
14510        enforceCrossUserPermission(callingUid, userId,
14511                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14512
14513        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14514            try {
14515                if (observer != null) {
14516                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14517                }
14518            } catch (RemoteException re) {
14519            }
14520            return;
14521        }
14522
14523        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14524            installFlags |= PackageManager.INSTALL_FROM_ADB;
14525
14526        } else {
14527            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14528            // about installerPackageName.
14529
14530            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14531            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14532        }
14533
14534        UserHandle user;
14535        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14536            user = UserHandle.ALL;
14537        } else {
14538            user = new UserHandle(userId);
14539        }
14540
14541        // Only system components can circumvent runtime permissions when installing.
14542        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14543                && mContext.checkCallingOrSelfPermission(Manifest.permission
14544                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14545            throw new SecurityException("You need the "
14546                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14547                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14548        }
14549
14550        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14551                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14552            throw new IllegalArgumentException(
14553                    "New installs into ASEC containers no longer supported");
14554        }
14555
14556        final File originFile = new File(originPath);
14557        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14558
14559        final Message msg = mHandler.obtainMessage(INIT_COPY);
14560        final VerificationInfo verificationInfo = new VerificationInfo(
14561                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14562        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14563                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14564                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14565                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14566        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14567        msg.obj = params;
14568
14569        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14570                System.identityHashCode(msg.obj));
14571        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14572                System.identityHashCode(msg.obj));
14573
14574        mHandler.sendMessage(msg);
14575    }
14576
14577
14578    /**
14579     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14580     * it is acting on behalf on an enterprise or the user).
14581     *
14582     * Note that the ordering of the conditionals in this method is important. The checks we perform
14583     * are as follows, in this order:
14584     *
14585     * 1) If the install is being performed by a system app, we can trust the app to have set the
14586     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14587     *    what it is.
14588     * 2) If the install is being performed by a device or profile owner app, the install reason
14589     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14590     *    set the install reason correctly. If the app targets an older SDK version where install
14591     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14592     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14593     * 3) In all other cases, the install is being performed by a regular app that is neither part
14594     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14595     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14596     *    set to enterprise policy and if so, change it to unknown instead.
14597     */
14598    private int fixUpInstallReason(String installerPackageName, int installerUid,
14599            int installReason) {
14600        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14601                == PERMISSION_GRANTED) {
14602            // If the install is being performed by a system app, we trust that app to have set the
14603            // install reason correctly.
14604            return installReason;
14605        }
14606
14607        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14608            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14609        if (dpm != null) {
14610            ComponentName owner = null;
14611            try {
14612                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14613                if (owner == null) {
14614                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14615                }
14616            } catch (RemoteException e) {
14617            }
14618            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14619                // If the install is being performed by a device or profile owner, the install
14620                // reason should be enterprise policy.
14621                return PackageManager.INSTALL_REASON_POLICY;
14622            }
14623        }
14624
14625        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14626            // If the install is being performed by a regular app (i.e. neither system app nor
14627            // device or profile owner), we have no reason to believe that the app is acting on
14628            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14629            // change it to unknown instead.
14630            return PackageManager.INSTALL_REASON_UNKNOWN;
14631        }
14632
14633        // If the install is being performed by a regular app and the install reason was set to any
14634        // value but enterprise policy, leave the install reason unchanged.
14635        return installReason;
14636    }
14637
14638    void installStage(String packageName, File stagedDir,
14639            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14640            String installerPackageName, int installerUid, UserHandle user,
14641            Certificate[][] certificates) {
14642        if (DEBUG_EPHEMERAL) {
14643            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14644                Slog.d(TAG, "Ephemeral install of " + packageName);
14645            }
14646        }
14647        final VerificationInfo verificationInfo = new VerificationInfo(
14648                sessionParams.originatingUri, sessionParams.referrerUri,
14649                sessionParams.originatingUid, installerUid);
14650
14651        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
14652
14653        final Message msg = mHandler.obtainMessage(INIT_COPY);
14654        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14655                sessionParams.installReason);
14656        final InstallParams params = new InstallParams(origin, null, observer,
14657                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14658                verificationInfo, user, sessionParams.abiOverride,
14659                sessionParams.grantedRuntimePermissions, certificates, installReason);
14660        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14661        msg.obj = params;
14662
14663        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14664                System.identityHashCode(msg.obj));
14665        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14666                System.identityHashCode(msg.obj));
14667
14668        mHandler.sendMessage(msg);
14669    }
14670
14671    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14672            int userId) {
14673        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14674        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14675                false /*startReceiver*/, pkgSetting.appId, userId);
14676
14677        // Send a session commit broadcast
14678        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14679        info.installReason = pkgSetting.getInstallReason(userId);
14680        info.appPackageName = packageName;
14681        sendSessionCommitBroadcast(info, userId);
14682    }
14683
14684    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14685            boolean includeStopped, int appId, int... userIds) {
14686        if (ArrayUtils.isEmpty(userIds)) {
14687            return;
14688        }
14689        Bundle extras = new Bundle(1);
14690        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14691        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14692
14693        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14694                packageName, extras, 0, null, null, userIds);
14695        if (sendBootCompleted) {
14696            mHandler.post(() -> {
14697                        for (int userId : userIds) {
14698                            sendBootCompletedBroadcastToSystemApp(
14699                                    packageName, includeStopped, userId);
14700                        }
14701                    }
14702            );
14703        }
14704    }
14705
14706    /**
14707     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14708     * automatically without needing an explicit launch.
14709     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14710     */
14711    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14712            int userId) {
14713        // If user is not running, the app didn't miss any broadcast
14714        if (!mUserManagerInternal.isUserRunning(userId)) {
14715            return;
14716        }
14717        final IActivityManager am = ActivityManager.getService();
14718        try {
14719            // Deliver LOCKED_BOOT_COMPLETED first
14720            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14721                    .setPackage(packageName);
14722            if (includeStopped) {
14723                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14724            }
14725            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14726            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14727                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14728
14729            // Deliver BOOT_COMPLETED only if user is unlocked
14730            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14731                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14732                if (includeStopped) {
14733                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14734                }
14735                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14736                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14737            }
14738        } catch (RemoteException e) {
14739            throw e.rethrowFromSystemServer();
14740        }
14741    }
14742
14743    @Override
14744    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14745            int userId) {
14746        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14747        PackageSetting pkgSetting;
14748        final int callingUid = Binder.getCallingUid();
14749        enforceCrossUserPermission(callingUid, userId,
14750                true /* requireFullPermission */, true /* checkShell */,
14751                "setApplicationHiddenSetting for user " + userId);
14752
14753        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14754            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14755            return false;
14756        }
14757
14758        long callingId = Binder.clearCallingIdentity();
14759        try {
14760            boolean sendAdded = false;
14761            boolean sendRemoved = false;
14762            // writer
14763            synchronized (mPackages) {
14764                pkgSetting = mSettings.mPackages.get(packageName);
14765                if (pkgSetting == null) {
14766                    return false;
14767                }
14768                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14769                    return false;
14770                }
14771                // Do not allow "android" is being disabled
14772                if ("android".equals(packageName)) {
14773                    Slog.w(TAG, "Cannot hide package: android");
14774                    return false;
14775                }
14776                // Cannot hide static shared libs as they are considered
14777                // a part of the using app (emulating static linking). Also
14778                // static libs are installed always on internal storage.
14779                PackageParser.Package pkg = mPackages.get(packageName);
14780                if (pkg != null && pkg.staticSharedLibName != null) {
14781                    Slog.w(TAG, "Cannot hide package: " + packageName
14782                            + " providing static shared library: "
14783                            + pkg.staticSharedLibName);
14784                    return false;
14785                }
14786                // Only allow protected packages to hide themselves.
14787                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14788                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14789                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14790                    return false;
14791                }
14792
14793                if (pkgSetting.getHidden(userId) != hidden) {
14794                    pkgSetting.setHidden(hidden, userId);
14795                    mSettings.writePackageRestrictionsLPr(userId);
14796                    if (hidden) {
14797                        sendRemoved = true;
14798                    } else {
14799                        sendAdded = true;
14800                    }
14801                }
14802            }
14803            if (sendAdded) {
14804                sendPackageAddedForUser(packageName, pkgSetting, userId);
14805                return true;
14806            }
14807            if (sendRemoved) {
14808                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14809                        "hiding pkg");
14810                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14811                return true;
14812            }
14813        } finally {
14814            Binder.restoreCallingIdentity(callingId);
14815        }
14816        return false;
14817    }
14818
14819    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14820            int userId) {
14821        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14822        info.removedPackage = packageName;
14823        info.installerPackageName = pkgSetting.installerPackageName;
14824        info.removedUsers = new int[] {userId};
14825        info.broadcastUsers = new int[] {userId};
14826        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14827        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14828    }
14829
14830    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14831        if (pkgList.length > 0) {
14832            Bundle extras = new Bundle(1);
14833            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14834
14835            sendPackageBroadcast(
14836                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14837                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14838                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14839                    new int[] {userId});
14840        }
14841    }
14842
14843    /**
14844     * Returns true if application is not found or there was an error. Otherwise it returns
14845     * the hidden state of the package for the given user.
14846     */
14847    @Override
14848    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14849        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14850        final int callingUid = Binder.getCallingUid();
14851        enforceCrossUserPermission(callingUid, userId,
14852                true /* requireFullPermission */, false /* checkShell */,
14853                "getApplicationHidden for user " + userId);
14854        PackageSetting ps;
14855        long callingId = Binder.clearCallingIdentity();
14856        try {
14857            // writer
14858            synchronized (mPackages) {
14859                ps = mSettings.mPackages.get(packageName);
14860                if (ps == null) {
14861                    return true;
14862                }
14863                if (filterAppAccessLPr(ps, callingUid, userId)) {
14864                    return true;
14865                }
14866                return ps.getHidden(userId);
14867            }
14868        } finally {
14869            Binder.restoreCallingIdentity(callingId);
14870        }
14871    }
14872
14873    /**
14874     * @hide
14875     */
14876    @Override
14877    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14878            int installReason) {
14879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14880                null);
14881        PackageSetting pkgSetting;
14882        final int callingUid = Binder.getCallingUid();
14883        enforceCrossUserPermission(callingUid, userId,
14884                true /* requireFullPermission */, true /* checkShell */,
14885                "installExistingPackage for user " + userId);
14886        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14887            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14888        }
14889
14890        long callingId = Binder.clearCallingIdentity();
14891        try {
14892            boolean installed = false;
14893            final boolean instantApp =
14894                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14895            final boolean fullApp =
14896                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14897
14898            // writer
14899            synchronized (mPackages) {
14900                pkgSetting = mSettings.mPackages.get(packageName);
14901                if (pkgSetting == null) {
14902                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14903                }
14904                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14905                    // only allow the existing package to be used if it's installed as a full
14906                    // application for at least one user
14907                    boolean installAllowed = false;
14908                    for (int checkUserId : sUserManager.getUserIds()) {
14909                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14910                        if (installAllowed) {
14911                            break;
14912                        }
14913                    }
14914                    if (!installAllowed) {
14915                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14916                    }
14917                }
14918                if (!pkgSetting.getInstalled(userId)) {
14919                    pkgSetting.setInstalled(true, userId);
14920                    pkgSetting.setHidden(false, userId);
14921                    pkgSetting.setInstallReason(installReason, userId);
14922                    mSettings.writePackageRestrictionsLPr(userId);
14923                    mSettings.writeKernelMappingLPr(pkgSetting);
14924                    installed = true;
14925                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14926                    // upgrade app from instant to full; we don't allow app downgrade
14927                    installed = true;
14928                }
14929                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14930            }
14931
14932            if (installed) {
14933                if (pkgSetting.pkg != null) {
14934                    synchronized (mInstallLock) {
14935                        // We don't need to freeze for a brand new install
14936                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14937                    }
14938                }
14939                sendPackageAddedForUser(packageName, pkgSetting, userId);
14940                synchronized (mPackages) {
14941                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14942                }
14943            }
14944        } finally {
14945            Binder.restoreCallingIdentity(callingId);
14946        }
14947
14948        return PackageManager.INSTALL_SUCCEEDED;
14949    }
14950
14951    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14952            boolean instantApp, boolean fullApp) {
14953        // no state specified; do nothing
14954        if (!instantApp && !fullApp) {
14955            return;
14956        }
14957        if (userId != UserHandle.USER_ALL) {
14958            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14959                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14960            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14961                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14962            }
14963        } else {
14964            for (int currentUserId : sUserManager.getUserIds()) {
14965                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14966                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14967                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14968                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14969                }
14970            }
14971        }
14972    }
14973
14974    boolean isUserRestricted(int userId, String restrictionKey) {
14975        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14976        if (restrictions.getBoolean(restrictionKey, false)) {
14977            Log.w(TAG, "User is restricted: " + restrictionKey);
14978            return true;
14979        }
14980        return false;
14981    }
14982
14983    @Override
14984    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14985            int userId) {
14986        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14987        final int callingUid = Binder.getCallingUid();
14988        enforceCrossUserPermission(callingUid, userId,
14989                true /* requireFullPermission */, true /* checkShell */,
14990                "setPackagesSuspended for user " + userId);
14991
14992        if (ArrayUtils.isEmpty(packageNames)) {
14993            return packageNames;
14994        }
14995
14996        // List of package names for whom the suspended state has changed.
14997        List<String> changedPackages = new ArrayList<>(packageNames.length);
14998        // List of package names for whom the suspended state is not set as requested in this
14999        // method.
15000        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15001        long callingId = Binder.clearCallingIdentity();
15002        try {
15003            for (int i = 0; i < packageNames.length; i++) {
15004                String packageName = packageNames[i];
15005                boolean changed = false;
15006                final int appId;
15007                synchronized (mPackages) {
15008                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15009                    if (pkgSetting == null
15010                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15011                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15012                                + "\". Skipping suspending/un-suspending.");
15013                        unactionedPackages.add(packageName);
15014                        continue;
15015                    }
15016                    appId = pkgSetting.appId;
15017                    if (pkgSetting.getSuspended(userId) != suspended) {
15018                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15019                            unactionedPackages.add(packageName);
15020                            continue;
15021                        }
15022                        pkgSetting.setSuspended(suspended, userId);
15023                        mSettings.writePackageRestrictionsLPr(userId);
15024                        changed = true;
15025                        changedPackages.add(packageName);
15026                    }
15027                }
15028
15029                if (changed && suspended) {
15030                    killApplication(packageName, UserHandle.getUid(userId, appId),
15031                            "suspending package");
15032                }
15033            }
15034        } finally {
15035            Binder.restoreCallingIdentity(callingId);
15036        }
15037
15038        if (!changedPackages.isEmpty()) {
15039            sendPackagesSuspendedForUser(changedPackages.toArray(
15040                    new String[changedPackages.size()]), userId, suspended);
15041        }
15042
15043        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15044    }
15045
15046    @Override
15047    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15048        final int callingUid = Binder.getCallingUid();
15049        enforceCrossUserPermission(callingUid, userId,
15050                true /* requireFullPermission */, false /* checkShell */,
15051                "isPackageSuspendedForUser for user " + userId);
15052        synchronized (mPackages) {
15053            final PackageSetting ps = mSettings.mPackages.get(packageName);
15054            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15055                throw new IllegalArgumentException("Unknown target package: " + packageName);
15056            }
15057            return ps.getSuspended(userId);
15058        }
15059    }
15060
15061    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15062        if (isPackageDeviceAdmin(packageName, userId)) {
15063            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15064                    + "\": has an active device admin");
15065            return false;
15066        }
15067
15068        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15069        if (packageName.equals(activeLauncherPackageName)) {
15070            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15071                    + "\": contains the active launcher");
15072            return false;
15073        }
15074
15075        if (packageName.equals(mRequiredInstallerPackage)) {
15076            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15077                    + "\": required for package installation");
15078            return false;
15079        }
15080
15081        if (packageName.equals(mRequiredUninstallerPackage)) {
15082            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15083                    + "\": required for package uninstallation");
15084            return false;
15085        }
15086
15087        if (packageName.equals(mRequiredVerifierPackage)) {
15088            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15089                    + "\": required for package verification");
15090            return false;
15091        }
15092
15093        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15094            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15095                    + "\": is the default dialer");
15096            return false;
15097        }
15098
15099        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15100            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15101                    + "\": protected package");
15102            return false;
15103        }
15104
15105        // Cannot suspend static shared libs as they are considered
15106        // a part of the using app (emulating static linking). Also
15107        // static libs are installed always on internal storage.
15108        PackageParser.Package pkg = mPackages.get(packageName);
15109        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15110            Slog.w(TAG, "Cannot suspend package: " + packageName
15111                    + " providing static shared library: "
15112                    + pkg.staticSharedLibName);
15113            return false;
15114        }
15115
15116        return true;
15117    }
15118
15119    private String getActiveLauncherPackageName(int userId) {
15120        Intent intent = new Intent(Intent.ACTION_MAIN);
15121        intent.addCategory(Intent.CATEGORY_HOME);
15122        ResolveInfo resolveInfo = resolveIntent(
15123                intent,
15124                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15125                PackageManager.MATCH_DEFAULT_ONLY,
15126                userId);
15127
15128        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15129    }
15130
15131    private String getDefaultDialerPackageName(int userId) {
15132        synchronized (mPackages) {
15133            return mSettings.getDefaultDialerPackageNameLPw(userId);
15134        }
15135    }
15136
15137    @Override
15138    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15139        mContext.enforceCallingOrSelfPermission(
15140                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15141                "Only package verification agents can verify applications");
15142
15143        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15144        final PackageVerificationResponse response = new PackageVerificationResponse(
15145                verificationCode, Binder.getCallingUid());
15146        msg.arg1 = id;
15147        msg.obj = response;
15148        mHandler.sendMessage(msg);
15149    }
15150
15151    @Override
15152    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15153            long millisecondsToDelay) {
15154        mContext.enforceCallingOrSelfPermission(
15155                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15156                "Only package verification agents can extend verification timeouts");
15157
15158        final PackageVerificationState state = mPendingVerification.get(id);
15159        final PackageVerificationResponse response = new PackageVerificationResponse(
15160                verificationCodeAtTimeout, Binder.getCallingUid());
15161
15162        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15163            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15164        }
15165        if (millisecondsToDelay < 0) {
15166            millisecondsToDelay = 0;
15167        }
15168        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15169                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15170            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15171        }
15172
15173        if ((state != null) && !state.timeoutExtended()) {
15174            state.extendTimeout();
15175
15176            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15177            msg.arg1 = id;
15178            msg.obj = response;
15179            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15180        }
15181    }
15182
15183    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15184            int verificationCode, UserHandle user) {
15185        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15186        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15187        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15188        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15189        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15190
15191        mContext.sendBroadcastAsUser(intent, user,
15192                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15193    }
15194
15195    private ComponentName matchComponentForVerifier(String packageName,
15196            List<ResolveInfo> receivers) {
15197        ActivityInfo targetReceiver = null;
15198
15199        final int NR = receivers.size();
15200        for (int i = 0; i < NR; i++) {
15201            final ResolveInfo info = receivers.get(i);
15202            if (info.activityInfo == null) {
15203                continue;
15204            }
15205
15206            if (packageName.equals(info.activityInfo.packageName)) {
15207                targetReceiver = info.activityInfo;
15208                break;
15209            }
15210        }
15211
15212        if (targetReceiver == null) {
15213            return null;
15214        }
15215
15216        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15217    }
15218
15219    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15220            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15221        if (pkgInfo.verifiers.length == 0) {
15222            return null;
15223        }
15224
15225        final int N = pkgInfo.verifiers.length;
15226        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15227        for (int i = 0; i < N; i++) {
15228            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15229
15230            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15231                    receivers);
15232            if (comp == null) {
15233                continue;
15234            }
15235
15236            final int verifierUid = getUidForVerifier(verifierInfo);
15237            if (verifierUid == -1) {
15238                continue;
15239            }
15240
15241            if (DEBUG_VERIFY) {
15242                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15243                        + " with the correct signature");
15244            }
15245            sufficientVerifiers.add(comp);
15246            verificationState.addSufficientVerifier(verifierUid);
15247        }
15248
15249        return sufficientVerifiers;
15250    }
15251
15252    private int getUidForVerifier(VerifierInfo verifierInfo) {
15253        synchronized (mPackages) {
15254            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15255            if (pkg == null) {
15256                return -1;
15257            } else if (pkg.mSignatures.length != 1) {
15258                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15259                        + " has more than one signature; ignoring");
15260                return -1;
15261            }
15262
15263            /*
15264             * If the public key of the package's signature does not match
15265             * our expected public key, then this is a different package and
15266             * we should skip.
15267             */
15268
15269            final byte[] expectedPublicKey;
15270            try {
15271                final Signature verifierSig = pkg.mSignatures[0];
15272                final PublicKey publicKey = verifierSig.getPublicKey();
15273                expectedPublicKey = publicKey.getEncoded();
15274            } catch (CertificateException e) {
15275                return -1;
15276            }
15277
15278            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15279
15280            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15281                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15282                        + " does not have the expected public key; ignoring");
15283                return -1;
15284            }
15285
15286            return pkg.applicationInfo.uid;
15287        }
15288    }
15289
15290    @Override
15291    public void finishPackageInstall(int token, boolean didLaunch) {
15292        enforceSystemOrRoot("Only the system is allowed to finish installs");
15293
15294        if (DEBUG_INSTALL) {
15295            Slog.v(TAG, "BM finishing package install for " + token);
15296        }
15297        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15298
15299        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15300        mHandler.sendMessage(msg);
15301    }
15302
15303    /**
15304     * Get the verification agent timeout.  Used for both the APK verifier and the
15305     * intent filter verifier.
15306     *
15307     * @return verification timeout in milliseconds
15308     */
15309    private long getVerificationTimeout() {
15310        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15311                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15312                DEFAULT_VERIFICATION_TIMEOUT);
15313    }
15314
15315    /**
15316     * Get the default verification agent response code.
15317     *
15318     * @return default verification response code
15319     */
15320    private int getDefaultVerificationResponse(UserHandle user) {
15321        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15322            return PackageManager.VERIFICATION_REJECT;
15323        }
15324        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15325                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15326                DEFAULT_VERIFICATION_RESPONSE);
15327    }
15328
15329    /**
15330     * Check whether or not package verification has been enabled.
15331     *
15332     * @return true if verification should be performed
15333     */
15334    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15335        if (!DEFAULT_VERIFY_ENABLE) {
15336            return false;
15337        }
15338
15339        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15340
15341        // Check if installing from ADB
15342        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15343            // Do not run verification in a test harness environment
15344            if (ActivityManager.isRunningInTestHarness()) {
15345                return false;
15346            }
15347            if (ensureVerifyAppsEnabled) {
15348                return true;
15349            }
15350            // Check if the developer does not want package verification for ADB installs
15351            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15352                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15353                return false;
15354            }
15355        } else {
15356            // only when not installed from ADB, skip verification for instant apps when
15357            // the installer and verifier are the same.
15358            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15359                if (mInstantAppInstallerActivity != null
15360                        && mInstantAppInstallerActivity.packageName.equals(
15361                                mRequiredVerifierPackage)) {
15362                    try {
15363                        mContext.getSystemService(AppOpsManager.class)
15364                                .checkPackage(installerUid, mRequiredVerifierPackage);
15365                        if (DEBUG_VERIFY) {
15366                            Slog.i(TAG, "disable verification for instant app");
15367                        }
15368                        return false;
15369                    } catch (SecurityException ignore) { }
15370                }
15371            }
15372        }
15373
15374        if (ensureVerifyAppsEnabled) {
15375            return true;
15376        }
15377
15378        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15379                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15380    }
15381
15382    @Override
15383    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15384            throws RemoteException {
15385        mContext.enforceCallingOrSelfPermission(
15386                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15387                "Only intentfilter verification agents can verify applications");
15388
15389        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15390        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15391                Binder.getCallingUid(), verificationCode, failedDomains);
15392        msg.arg1 = id;
15393        msg.obj = response;
15394        mHandler.sendMessage(msg);
15395    }
15396
15397    @Override
15398    public int getIntentVerificationStatus(String packageName, int userId) {
15399        final int callingUid = Binder.getCallingUid();
15400        if (UserHandle.getUserId(callingUid) != userId) {
15401            mContext.enforceCallingOrSelfPermission(
15402                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15403                    "getIntentVerificationStatus" + userId);
15404        }
15405        if (getInstantAppPackageName(callingUid) != null) {
15406            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15407        }
15408        synchronized (mPackages) {
15409            final PackageSetting ps = mSettings.mPackages.get(packageName);
15410            if (ps == null
15411                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15412                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15413            }
15414            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15415        }
15416    }
15417
15418    @Override
15419    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15420        mContext.enforceCallingOrSelfPermission(
15421                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15422
15423        boolean result = false;
15424        synchronized (mPackages) {
15425            final PackageSetting ps = mSettings.mPackages.get(packageName);
15426            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15427                return false;
15428            }
15429            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15430        }
15431        if (result) {
15432            scheduleWritePackageRestrictionsLocked(userId);
15433        }
15434        return result;
15435    }
15436
15437    @Override
15438    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15439            String packageName) {
15440        final int callingUid = Binder.getCallingUid();
15441        if (getInstantAppPackageName(callingUid) != null) {
15442            return ParceledListSlice.emptyList();
15443        }
15444        synchronized (mPackages) {
15445            final PackageSetting ps = mSettings.mPackages.get(packageName);
15446            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15447                return ParceledListSlice.emptyList();
15448            }
15449            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15450        }
15451    }
15452
15453    @Override
15454    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15455        if (TextUtils.isEmpty(packageName)) {
15456            return ParceledListSlice.emptyList();
15457        }
15458        final int callingUid = Binder.getCallingUid();
15459        final int callingUserId = UserHandle.getUserId(callingUid);
15460        synchronized (mPackages) {
15461            PackageParser.Package pkg = mPackages.get(packageName);
15462            if (pkg == null || pkg.activities == null) {
15463                return ParceledListSlice.emptyList();
15464            }
15465            if (pkg.mExtras == null) {
15466                return ParceledListSlice.emptyList();
15467            }
15468            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15469            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15470                return ParceledListSlice.emptyList();
15471            }
15472            final int count = pkg.activities.size();
15473            ArrayList<IntentFilter> result = new ArrayList<>();
15474            for (int n=0; n<count; n++) {
15475                PackageParser.Activity activity = pkg.activities.get(n);
15476                if (activity.intents != null && activity.intents.size() > 0) {
15477                    result.addAll(activity.intents);
15478                }
15479            }
15480            return new ParceledListSlice<>(result);
15481        }
15482    }
15483
15484    @Override
15485    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15486        mContext.enforceCallingOrSelfPermission(
15487                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15488        if (UserHandle.getCallingUserId() != userId) {
15489            mContext.enforceCallingOrSelfPermission(
15490                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15491        }
15492
15493        synchronized (mPackages) {
15494            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15495            if (packageName != null) {
15496                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15497                        packageName, userId);
15498            }
15499            return result;
15500        }
15501    }
15502
15503    @Override
15504    public String getDefaultBrowserPackageName(int userId) {
15505        if (UserHandle.getCallingUserId() != userId) {
15506            mContext.enforceCallingOrSelfPermission(
15507                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15508        }
15509        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15510            return null;
15511        }
15512        synchronized (mPackages) {
15513            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15514        }
15515    }
15516
15517    /**
15518     * Get the "allow unknown sources" setting.
15519     *
15520     * @return the current "allow unknown sources" setting
15521     */
15522    private int getUnknownSourcesSettings() {
15523        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15524                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15525                -1);
15526    }
15527
15528    @Override
15529    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15530        final int callingUid = Binder.getCallingUid();
15531        if (getInstantAppPackageName(callingUid) != null) {
15532            return;
15533        }
15534        // writer
15535        synchronized (mPackages) {
15536            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15537            if (targetPackageSetting == null
15538                    || filterAppAccessLPr(
15539                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15540                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15541            }
15542
15543            PackageSetting installerPackageSetting;
15544            if (installerPackageName != null) {
15545                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15546                if (installerPackageSetting == null) {
15547                    throw new IllegalArgumentException("Unknown installer package: "
15548                            + installerPackageName);
15549                }
15550            } else {
15551                installerPackageSetting = null;
15552            }
15553
15554            Signature[] callerSignature;
15555            Object obj = mSettings.getUserIdLPr(callingUid);
15556            if (obj != null) {
15557                if (obj instanceof SharedUserSetting) {
15558                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15559                } else if (obj instanceof PackageSetting) {
15560                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15561                } else {
15562                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15563                }
15564            } else {
15565                throw new SecurityException("Unknown calling UID: " + callingUid);
15566            }
15567
15568            // Verify: can't set installerPackageName to a package that is
15569            // not signed with the same cert as the caller.
15570            if (installerPackageSetting != null) {
15571                if (compareSignatures(callerSignature,
15572                        installerPackageSetting.signatures.mSignatures)
15573                        != PackageManager.SIGNATURE_MATCH) {
15574                    throw new SecurityException(
15575                            "Caller does not have same cert as new installer package "
15576                            + installerPackageName);
15577                }
15578            }
15579
15580            // Verify: if target already has an installer package, it must
15581            // be signed with the same cert as the caller.
15582            if (targetPackageSetting.installerPackageName != null) {
15583                PackageSetting setting = mSettings.mPackages.get(
15584                        targetPackageSetting.installerPackageName);
15585                // If the currently set package isn't valid, then it's always
15586                // okay to change it.
15587                if (setting != null) {
15588                    if (compareSignatures(callerSignature,
15589                            setting.signatures.mSignatures)
15590                            != PackageManager.SIGNATURE_MATCH) {
15591                        throw new SecurityException(
15592                                "Caller does not have same cert as old installer package "
15593                                + targetPackageSetting.installerPackageName);
15594                    }
15595                }
15596            }
15597
15598            // Okay!
15599            targetPackageSetting.installerPackageName = installerPackageName;
15600            if (installerPackageName != null) {
15601                mSettings.mInstallerPackages.add(installerPackageName);
15602            }
15603            scheduleWriteSettingsLocked();
15604        }
15605    }
15606
15607    @Override
15608    public void setApplicationCategoryHint(String packageName, int categoryHint,
15609            String callerPackageName) {
15610        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15611            throw new SecurityException("Instant applications don't have access to this method");
15612        }
15613        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15614                callerPackageName);
15615        synchronized (mPackages) {
15616            PackageSetting ps = mSettings.mPackages.get(packageName);
15617            if (ps == null) {
15618                throw new IllegalArgumentException("Unknown target package " + packageName);
15619            }
15620            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15621                throw new IllegalArgumentException("Unknown target package " + packageName);
15622            }
15623            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15624                throw new IllegalArgumentException("Calling package " + callerPackageName
15625                        + " is not installer for " + packageName);
15626            }
15627
15628            if (ps.categoryHint != categoryHint) {
15629                ps.categoryHint = categoryHint;
15630                scheduleWriteSettingsLocked();
15631            }
15632        }
15633    }
15634
15635    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15636        // Queue up an async operation since the package installation may take a little while.
15637        mHandler.post(new Runnable() {
15638            public void run() {
15639                mHandler.removeCallbacks(this);
15640                 // Result object to be returned
15641                PackageInstalledInfo res = new PackageInstalledInfo();
15642                res.setReturnCode(currentStatus);
15643                res.uid = -1;
15644                res.pkg = null;
15645                res.removedInfo = null;
15646                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15647                    args.doPreInstall(res.returnCode);
15648                    synchronized (mInstallLock) {
15649                        installPackageTracedLI(args, res);
15650                    }
15651                    args.doPostInstall(res.returnCode, res.uid);
15652                }
15653
15654                // A restore should be performed at this point if (a) the install
15655                // succeeded, (b) the operation is not an update, and (c) the new
15656                // package has not opted out of backup participation.
15657                final boolean update = res.removedInfo != null
15658                        && res.removedInfo.removedPackage != null;
15659                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15660                boolean doRestore = !update
15661                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15662
15663                // Set up the post-install work request bookkeeping.  This will be used
15664                // and cleaned up by the post-install event handling regardless of whether
15665                // there's a restore pass performed.  Token values are >= 1.
15666                int token;
15667                if (mNextInstallToken < 0) mNextInstallToken = 1;
15668                token = mNextInstallToken++;
15669
15670                PostInstallData data = new PostInstallData(args, res);
15671                mRunningInstalls.put(token, data);
15672                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15673
15674                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15675                    // Pass responsibility to the Backup Manager.  It will perform a
15676                    // restore if appropriate, then pass responsibility back to the
15677                    // Package Manager to run the post-install observer callbacks
15678                    // and broadcasts.
15679                    IBackupManager bm = IBackupManager.Stub.asInterface(
15680                            ServiceManager.getService(Context.BACKUP_SERVICE));
15681                    if (bm != null) {
15682                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15683                                + " to BM for possible restore");
15684                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15685                        try {
15686                            // TODO: http://b/22388012
15687                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15688                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15689                            } else {
15690                                doRestore = false;
15691                            }
15692                        } catch (RemoteException e) {
15693                            // can't happen; the backup manager is local
15694                        } catch (Exception e) {
15695                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15696                            doRestore = false;
15697                        }
15698                    } else {
15699                        Slog.e(TAG, "Backup Manager not found!");
15700                        doRestore = false;
15701                    }
15702                }
15703
15704                if (!doRestore) {
15705                    // No restore possible, or the Backup Manager was mysteriously not
15706                    // available -- just fire the post-install work request directly.
15707                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15708
15709                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15710
15711                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15712                    mHandler.sendMessage(msg);
15713                }
15714            }
15715        });
15716    }
15717
15718    /**
15719     * Callback from PackageSettings whenever an app is first transitioned out of the
15720     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15721     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15722     * here whether the app is the target of an ongoing install, and only send the
15723     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15724     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15725     * handling.
15726     */
15727    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15728        // Serialize this with the rest of the install-process message chain.  In the
15729        // restore-at-install case, this Runnable will necessarily run before the
15730        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15731        // are coherent.  In the non-restore case, the app has already completed install
15732        // and been launched through some other means, so it is not in a problematic
15733        // state for observers to see the FIRST_LAUNCH signal.
15734        mHandler.post(new Runnable() {
15735            @Override
15736            public void run() {
15737                for (int i = 0; i < mRunningInstalls.size(); i++) {
15738                    final PostInstallData data = mRunningInstalls.valueAt(i);
15739                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15740                        continue;
15741                    }
15742                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15743                        // right package; but is it for the right user?
15744                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15745                            if (userId == data.res.newUsers[uIndex]) {
15746                                if (DEBUG_BACKUP) {
15747                                    Slog.i(TAG, "Package " + pkgName
15748                                            + " being restored so deferring FIRST_LAUNCH");
15749                                }
15750                                return;
15751                            }
15752                        }
15753                    }
15754                }
15755                // didn't find it, so not being restored
15756                if (DEBUG_BACKUP) {
15757                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15758                }
15759                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15760            }
15761        });
15762    }
15763
15764    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15765        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15766                installerPkg, null, userIds);
15767    }
15768
15769    private abstract class HandlerParams {
15770        private static final int MAX_RETRIES = 4;
15771
15772        /**
15773         * Number of times startCopy() has been attempted and had a non-fatal
15774         * error.
15775         */
15776        private int mRetries = 0;
15777
15778        /** User handle for the user requesting the information or installation. */
15779        private final UserHandle mUser;
15780        String traceMethod;
15781        int traceCookie;
15782
15783        HandlerParams(UserHandle user) {
15784            mUser = user;
15785        }
15786
15787        UserHandle getUser() {
15788            return mUser;
15789        }
15790
15791        HandlerParams setTraceMethod(String traceMethod) {
15792            this.traceMethod = traceMethod;
15793            return this;
15794        }
15795
15796        HandlerParams setTraceCookie(int traceCookie) {
15797            this.traceCookie = traceCookie;
15798            return this;
15799        }
15800
15801        final boolean startCopy() {
15802            boolean res;
15803            try {
15804                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15805
15806                if (++mRetries > MAX_RETRIES) {
15807                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15808                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15809                    handleServiceError();
15810                    return false;
15811                } else {
15812                    handleStartCopy();
15813                    res = true;
15814                }
15815            } catch (RemoteException e) {
15816                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15817                mHandler.sendEmptyMessage(MCS_RECONNECT);
15818                res = false;
15819            }
15820            handleReturnCode();
15821            return res;
15822        }
15823
15824        final void serviceError() {
15825            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15826            handleServiceError();
15827            handleReturnCode();
15828        }
15829
15830        abstract void handleStartCopy() throws RemoteException;
15831        abstract void handleServiceError();
15832        abstract void handleReturnCode();
15833    }
15834
15835    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15836        for (File path : paths) {
15837            try {
15838                mcs.clearDirectory(path.getAbsolutePath());
15839            } catch (RemoteException e) {
15840            }
15841        }
15842    }
15843
15844    static class OriginInfo {
15845        /**
15846         * Location where install is coming from, before it has been
15847         * copied/renamed into place. This could be a single monolithic APK
15848         * file, or a cluster directory. This location may be untrusted.
15849         */
15850        final File file;
15851
15852        /**
15853         * Flag indicating that {@link #file} or {@link #cid} has already been
15854         * staged, meaning downstream users don't need to defensively copy the
15855         * contents.
15856         */
15857        final boolean staged;
15858
15859        /**
15860         * Flag indicating that {@link #file} or {@link #cid} is an already
15861         * installed app that is being moved.
15862         */
15863        final boolean existing;
15864
15865        final String resolvedPath;
15866        final File resolvedFile;
15867
15868        static OriginInfo fromNothing() {
15869            return new OriginInfo(null, false, false);
15870        }
15871
15872        static OriginInfo fromUntrustedFile(File file) {
15873            return new OriginInfo(file, false, false);
15874        }
15875
15876        static OriginInfo fromExistingFile(File file) {
15877            return new OriginInfo(file, false, true);
15878        }
15879
15880        static OriginInfo fromStagedFile(File file) {
15881            return new OriginInfo(file, true, false);
15882        }
15883
15884        private OriginInfo(File file, boolean staged, boolean existing) {
15885            this.file = file;
15886            this.staged = staged;
15887            this.existing = existing;
15888
15889            if (file != null) {
15890                resolvedPath = file.getAbsolutePath();
15891                resolvedFile = file;
15892            } else {
15893                resolvedPath = null;
15894                resolvedFile = null;
15895            }
15896        }
15897    }
15898
15899    static class MoveInfo {
15900        final int moveId;
15901        final String fromUuid;
15902        final String toUuid;
15903        final String packageName;
15904        final String dataAppName;
15905        final int appId;
15906        final String seinfo;
15907        final int targetSdkVersion;
15908
15909        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15910                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15911            this.moveId = moveId;
15912            this.fromUuid = fromUuid;
15913            this.toUuid = toUuid;
15914            this.packageName = packageName;
15915            this.dataAppName = dataAppName;
15916            this.appId = appId;
15917            this.seinfo = seinfo;
15918            this.targetSdkVersion = targetSdkVersion;
15919        }
15920    }
15921
15922    static class VerificationInfo {
15923        /** A constant used to indicate that a uid value is not present. */
15924        public static final int NO_UID = -1;
15925
15926        /** URI referencing where the package was downloaded from. */
15927        final Uri originatingUri;
15928
15929        /** HTTP referrer URI associated with the originatingURI. */
15930        final Uri referrer;
15931
15932        /** UID of the application that the install request originated from. */
15933        final int originatingUid;
15934
15935        /** UID of application requesting the install */
15936        final int installerUid;
15937
15938        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15939            this.originatingUri = originatingUri;
15940            this.referrer = referrer;
15941            this.originatingUid = originatingUid;
15942            this.installerUid = installerUid;
15943        }
15944    }
15945
15946    class InstallParams extends HandlerParams {
15947        final OriginInfo origin;
15948        final MoveInfo move;
15949        final IPackageInstallObserver2 observer;
15950        int installFlags;
15951        final String installerPackageName;
15952        final String volumeUuid;
15953        private InstallArgs mArgs;
15954        private int mRet;
15955        final String packageAbiOverride;
15956        final String[] grantedRuntimePermissions;
15957        final VerificationInfo verificationInfo;
15958        final Certificate[][] certificates;
15959        final int installReason;
15960
15961        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15962                int installFlags, String installerPackageName, String volumeUuid,
15963                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15964                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15965            super(user);
15966            this.origin = origin;
15967            this.move = move;
15968            this.observer = observer;
15969            this.installFlags = installFlags;
15970            this.installerPackageName = installerPackageName;
15971            this.volumeUuid = volumeUuid;
15972            this.verificationInfo = verificationInfo;
15973            this.packageAbiOverride = packageAbiOverride;
15974            this.grantedRuntimePermissions = grantedPermissions;
15975            this.certificates = certificates;
15976            this.installReason = installReason;
15977        }
15978
15979        @Override
15980        public String toString() {
15981            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15982                    + " file=" + origin.file + "}";
15983        }
15984
15985        private int installLocationPolicy(PackageInfoLite pkgLite) {
15986            String packageName = pkgLite.packageName;
15987            int installLocation = pkgLite.installLocation;
15988            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15989            // reader
15990            synchronized (mPackages) {
15991                // Currently installed package which the new package is attempting to replace or
15992                // null if no such package is installed.
15993                PackageParser.Package installedPkg = mPackages.get(packageName);
15994                // Package which currently owns the data which the new package will own if installed.
15995                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15996                // will be null whereas dataOwnerPkg will contain information about the package
15997                // which was uninstalled while keeping its data.
15998                PackageParser.Package dataOwnerPkg = installedPkg;
15999                if (dataOwnerPkg  == null) {
16000                    PackageSetting ps = mSettings.mPackages.get(packageName);
16001                    if (ps != null) {
16002                        dataOwnerPkg = ps.pkg;
16003                    }
16004                }
16005
16006                if (dataOwnerPkg != null) {
16007                    // If installed, the package will get access to data left on the device by its
16008                    // predecessor. As a security measure, this is permited only if this is not a
16009                    // version downgrade or if the predecessor package is marked as debuggable and
16010                    // a downgrade is explicitly requested.
16011                    //
16012                    // On debuggable platform builds, downgrades are permitted even for
16013                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16014                    // not offer security guarantees and thus it's OK to disable some security
16015                    // mechanisms to make debugging/testing easier on those builds. However, even on
16016                    // debuggable builds downgrades of packages are permitted only if requested via
16017                    // installFlags. This is because we aim to keep the behavior of debuggable
16018                    // platform builds as close as possible to the behavior of non-debuggable
16019                    // platform builds.
16020                    final boolean downgradeRequested =
16021                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16022                    final boolean packageDebuggable =
16023                                (dataOwnerPkg.applicationInfo.flags
16024                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16025                    final boolean downgradePermitted =
16026                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16027                    if (!downgradePermitted) {
16028                        try {
16029                            checkDowngrade(dataOwnerPkg, pkgLite);
16030                        } catch (PackageManagerException e) {
16031                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16032                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16033                        }
16034                    }
16035                }
16036
16037                if (installedPkg != null) {
16038                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16039                        // Check for updated system application.
16040                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16041                            if (onSd) {
16042                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16043                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16044                            }
16045                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16046                        } else {
16047                            if (onSd) {
16048                                // Install flag overrides everything.
16049                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16050                            }
16051                            // If current upgrade specifies particular preference
16052                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16053                                // Application explicitly specified internal.
16054                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16055                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16056                                // App explictly prefers external. Let policy decide
16057                            } else {
16058                                // Prefer previous location
16059                                if (isExternal(installedPkg)) {
16060                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16061                                }
16062                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16063                            }
16064                        }
16065                    } else {
16066                        // Invalid install. Return error code
16067                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16068                    }
16069                }
16070            }
16071            // All the special cases have been taken care of.
16072            // Return result based on recommended install location.
16073            if (onSd) {
16074                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16075            }
16076            return pkgLite.recommendedInstallLocation;
16077        }
16078
16079        /*
16080         * Invoke remote method to get package information and install
16081         * location values. Override install location based on default
16082         * policy if needed and then create install arguments based
16083         * on the install location.
16084         */
16085        public void handleStartCopy() throws RemoteException {
16086            int ret = PackageManager.INSTALL_SUCCEEDED;
16087
16088            // If we're already staged, we've firmly committed to an install location
16089            if (origin.staged) {
16090                if (origin.file != null) {
16091                    installFlags |= PackageManager.INSTALL_INTERNAL;
16092                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16093                } else {
16094                    throw new IllegalStateException("Invalid stage location");
16095                }
16096            }
16097
16098            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16099            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16100            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16101            PackageInfoLite pkgLite = null;
16102
16103            if (onInt && onSd) {
16104                // Check if both bits are set.
16105                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16106                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16107            } else if (onSd && ephemeral) {
16108                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16109                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16110            } else {
16111                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16112                        packageAbiOverride);
16113
16114                if (DEBUG_EPHEMERAL && ephemeral) {
16115                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16116                }
16117
16118                /*
16119                 * If we have too little free space, try to free cache
16120                 * before giving up.
16121                 */
16122                if (!origin.staged && pkgLite.recommendedInstallLocation
16123                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16124                    // TODO: focus freeing disk space on the target device
16125                    final StorageManager storage = StorageManager.from(mContext);
16126                    final long lowThreshold = storage.getStorageLowBytes(
16127                            Environment.getDataDirectory());
16128
16129                    final long sizeBytes = mContainerService.calculateInstalledSize(
16130                            origin.resolvedPath, packageAbiOverride);
16131
16132                    try {
16133                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16134                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16135                                installFlags, packageAbiOverride);
16136                    } catch (InstallerException e) {
16137                        Slog.w(TAG, "Failed to free cache", e);
16138                    }
16139
16140                    /*
16141                     * The cache free must have deleted the file we
16142                     * downloaded to install.
16143                     *
16144                     * TODO: fix the "freeCache" call to not delete
16145                     *       the file we care about.
16146                     */
16147                    if (pkgLite.recommendedInstallLocation
16148                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16149                        pkgLite.recommendedInstallLocation
16150                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16151                    }
16152                }
16153            }
16154
16155            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16156                int loc = pkgLite.recommendedInstallLocation;
16157                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16158                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16159                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16160                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16161                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16162                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16163                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16164                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16165                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16166                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16167                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16168                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16169                } else {
16170                    // Override with defaults if needed.
16171                    loc = installLocationPolicy(pkgLite);
16172                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16173                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16174                    } else if (!onSd && !onInt) {
16175                        // Override install location with flags
16176                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16177                            // Set the flag to install on external media.
16178                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16179                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16180                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16181                            if (DEBUG_EPHEMERAL) {
16182                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16183                            }
16184                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16185                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16186                                    |PackageManager.INSTALL_INTERNAL);
16187                        } else {
16188                            // Make sure the flag for installing on external
16189                            // media is unset
16190                            installFlags |= PackageManager.INSTALL_INTERNAL;
16191                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16192                        }
16193                    }
16194                }
16195            }
16196
16197            final InstallArgs args = createInstallArgs(this);
16198            mArgs = args;
16199
16200            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16201                // TODO: http://b/22976637
16202                // Apps installed for "all" users use the device owner to verify the app
16203                UserHandle verifierUser = getUser();
16204                if (verifierUser == UserHandle.ALL) {
16205                    verifierUser = UserHandle.SYSTEM;
16206                }
16207
16208                /*
16209                 * Determine if we have any installed package verifiers. If we
16210                 * do, then we'll defer to them to verify the packages.
16211                 */
16212                final int requiredUid = mRequiredVerifierPackage == null ? -1
16213                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16214                                verifierUser.getIdentifier());
16215                final int installerUid =
16216                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16217                if (!origin.existing && requiredUid != -1
16218                        && isVerificationEnabled(
16219                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16220                    final Intent verification = new Intent(
16221                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16222                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16223                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16224                            PACKAGE_MIME_TYPE);
16225                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16226
16227                    // Query all live verifiers based on current user state
16228                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16229                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16230                            false /*allowDynamicSplits*/);
16231
16232                    if (DEBUG_VERIFY) {
16233                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16234                                + verification.toString() + " with " + pkgLite.verifiers.length
16235                                + " optional verifiers");
16236                    }
16237
16238                    final int verificationId = mPendingVerificationToken++;
16239
16240                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16241
16242                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16243                            installerPackageName);
16244
16245                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16246                            installFlags);
16247
16248                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16249                            pkgLite.packageName);
16250
16251                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16252                            pkgLite.versionCode);
16253
16254                    if (verificationInfo != null) {
16255                        if (verificationInfo.originatingUri != null) {
16256                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16257                                    verificationInfo.originatingUri);
16258                        }
16259                        if (verificationInfo.referrer != null) {
16260                            verification.putExtra(Intent.EXTRA_REFERRER,
16261                                    verificationInfo.referrer);
16262                        }
16263                        if (verificationInfo.originatingUid >= 0) {
16264                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16265                                    verificationInfo.originatingUid);
16266                        }
16267                        if (verificationInfo.installerUid >= 0) {
16268                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16269                                    verificationInfo.installerUid);
16270                        }
16271                    }
16272
16273                    final PackageVerificationState verificationState = new PackageVerificationState(
16274                            requiredUid, args);
16275
16276                    mPendingVerification.append(verificationId, verificationState);
16277
16278                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16279                            receivers, verificationState);
16280
16281                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16282                    final long idleDuration = getVerificationTimeout();
16283
16284                    /*
16285                     * If any sufficient verifiers were listed in the package
16286                     * manifest, attempt to ask them.
16287                     */
16288                    if (sufficientVerifiers != null) {
16289                        final int N = sufficientVerifiers.size();
16290                        if (N == 0) {
16291                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16292                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16293                        } else {
16294                            for (int i = 0; i < N; i++) {
16295                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16296                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16297                                        verifierComponent.getPackageName(), idleDuration,
16298                                        verifierUser.getIdentifier(), false, "package verifier");
16299
16300                                final Intent sufficientIntent = new Intent(verification);
16301                                sufficientIntent.setComponent(verifierComponent);
16302                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16303                            }
16304                        }
16305                    }
16306
16307                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16308                            mRequiredVerifierPackage, receivers);
16309                    if (ret == PackageManager.INSTALL_SUCCEEDED
16310                            && mRequiredVerifierPackage != null) {
16311                        Trace.asyncTraceBegin(
16312                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16313                        /*
16314                         * Send the intent to the required verification agent,
16315                         * but only start the verification timeout after the
16316                         * target BroadcastReceivers have run.
16317                         */
16318                        verification.setComponent(requiredVerifierComponent);
16319                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16320                                mRequiredVerifierPackage, idleDuration,
16321                                verifierUser.getIdentifier(), false, "package verifier");
16322                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16323                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16324                                new BroadcastReceiver() {
16325                                    @Override
16326                                    public void onReceive(Context context, Intent intent) {
16327                                        final Message msg = mHandler
16328                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16329                                        msg.arg1 = verificationId;
16330                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16331                                    }
16332                                }, null, 0, null, null);
16333
16334                        /*
16335                         * We don't want the copy to proceed until verification
16336                         * succeeds, so null out this field.
16337                         */
16338                        mArgs = null;
16339                    }
16340                } else {
16341                    /*
16342                     * No package verification is enabled, so immediately start
16343                     * the remote call to initiate copy using temporary file.
16344                     */
16345                    ret = args.copyApk(mContainerService, true);
16346                }
16347            }
16348
16349            mRet = ret;
16350        }
16351
16352        @Override
16353        void handleReturnCode() {
16354            // If mArgs is null, then MCS couldn't be reached. When it
16355            // reconnects, it will try again to install. At that point, this
16356            // will succeed.
16357            if (mArgs != null) {
16358                processPendingInstall(mArgs, mRet);
16359            }
16360        }
16361
16362        @Override
16363        void handleServiceError() {
16364            mArgs = createInstallArgs(this);
16365            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16366        }
16367    }
16368
16369    private InstallArgs createInstallArgs(InstallParams params) {
16370        if (params.move != null) {
16371            return new MoveInstallArgs(params);
16372        } else {
16373            return new FileInstallArgs(params);
16374        }
16375    }
16376
16377    /**
16378     * Create args that describe an existing installed package. Typically used
16379     * when cleaning up old installs, or used as a move source.
16380     */
16381    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16382            String resourcePath, String[] instructionSets) {
16383        return new FileInstallArgs(codePath, resourcePath, instructionSets);
16384    }
16385
16386    static abstract class InstallArgs {
16387        /** @see InstallParams#origin */
16388        final OriginInfo origin;
16389        /** @see InstallParams#move */
16390        final MoveInfo move;
16391
16392        final IPackageInstallObserver2 observer;
16393        // Always refers to PackageManager flags only
16394        final int installFlags;
16395        final String installerPackageName;
16396        final String volumeUuid;
16397        final UserHandle user;
16398        final String abiOverride;
16399        final String[] installGrantPermissions;
16400        /** If non-null, drop an async trace when the install completes */
16401        final String traceMethod;
16402        final int traceCookie;
16403        final Certificate[][] certificates;
16404        final int installReason;
16405
16406        // The list of instruction sets supported by this app. This is currently
16407        // only used during the rmdex() phase to clean up resources. We can get rid of this
16408        // if we move dex files under the common app path.
16409        /* nullable */ String[] instructionSets;
16410
16411        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16412                int installFlags, String installerPackageName, String volumeUuid,
16413                UserHandle user, String[] instructionSets,
16414                String abiOverride, String[] installGrantPermissions,
16415                String traceMethod, int traceCookie, Certificate[][] certificates,
16416                int installReason) {
16417            this.origin = origin;
16418            this.move = move;
16419            this.installFlags = installFlags;
16420            this.observer = observer;
16421            this.installerPackageName = installerPackageName;
16422            this.volumeUuid = volumeUuid;
16423            this.user = user;
16424            this.instructionSets = instructionSets;
16425            this.abiOverride = abiOverride;
16426            this.installGrantPermissions = installGrantPermissions;
16427            this.traceMethod = traceMethod;
16428            this.traceCookie = traceCookie;
16429            this.certificates = certificates;
16430            this.installReason = installReason;
16431        }
16432
16433        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16434        abstract int doPreInstall(int status);
16435
16436        /**
16437         * Rename package into final resting place. All paths on the given
16438         * scanned package should be updated to reflect the rename.
16439         */
16440        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16441        abstract int doPostInstall(int status, int uid);
16442
16443        /** @see PackageSettingBase#codePathString */
16444        abstract String getCodePath();
16445        /** @see PackageSettingBase#resourcePathString */
16446        abstract String getResourcePath();
16447
16448        // Need installer lock especially for dex file removal.
16449        abstract void cleanUpResourcesLI();
16450        abstract boolean doPostDeleteLI(boolean delete);
16451
16452        /**
16453         * Called before the source arguments are copied. This is used mostly
16454         * for MoveParams when it needs to read the source file to put it in the
16455         * destination.
16456         */
16457        int doPreCopy() {
16458            return PackageManager.INSTALL_SUCCEEDED;
16459        }
16460
16461        /**
16462         * Called after the source arguments are copied. This is used mostly for
16463         * MoveParams when it needs to read the source file to put it in the
16464         * destination.
16465         */
16466        int doPostCopy(int uid) {
16467            return PackageManager.INSTALL_SUCCEEDED;
16468        }
16469
16470        protected boolean isFwdLocked() {
16471            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16472        }
16473
16474        protected boolean isExternalAsec() {
16475            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16476        }
16477
16478        protected boolean isEphemeral() {
16479            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16480        }
16481
16482        UserHandle getUser() {
16483            return user;
16484        }
16485    }
16486
16487    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16488        if (!allCodePaths.isEmpty()) {
16489            if (instructionSets == null) {
16490                throw new IllegalStateException("instructionSet == null");
16491            }
16492            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16493            for (String codePath : allCodePaths) {
16494                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16495                    try {
16496                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16497                    } catch (InstallerException ignored) {
16498                    }
16499                }
16500            }
16501        }
16502    }
16503
16504    /**
16505     * Logic to handle installation of non-ASEC applications, including copying
16506     * and renaming logic.
16507     */
16508    class FileInstallArgs extends InstallArgs {
16509        private File codeFile;
16510        private File resourceFile;
16511
16512        // Example topology:
16513        // /data/app/com.example/base.apk
16514        // /data/app/com.example/split_foo.apk
16515        // /data/app/com.example/lib/arm/libfoo.so
16516        // /data/app/com.example/lib/arm64/libfoo.so
16517        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16518
16519        /** New install */
16520        FileInstallArgs(InstallParams params) {
16521            super(params.origin, params.move, params.observer, params.installFlags,
16522                    params.installerPackageName, params.volumeUuid,
16523                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16524                    params.grantedRuntimePermissions,
16525                    params.traceMethod, params.traceCookie, params.certificates,
16526                    params.installReason);
16527            if (isFwdLocked()) {
16528                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16529            }
16530        }
16531
16532        /** Existing install */
16533        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16534            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16535                    null, null, null, 0, null /*certificates*/,
16536                    PackageManager.INSTALL_REASON_UNKNOWN);
16537            this.codeFile = (codePath != null) ? new File(codePath) : null;
16538            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16539        }
16540
16541        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16542            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16543            try {
16544                return doCopyApk(imcs, temp);
16545            } finally {
16546                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16547            }
16548        }
16549
16550        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16551            if (origin.staged) {
16552                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16553                codeFile = origin.file;
16554                resourceFile = origin.file;
16555                return PackageManager.INSTALL_SUCCEEDED;
16556            }
16557
16558            try {
16559                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16560                final File tempDir =
16561                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16562                codeFile = tempDir;
16563                resourceFile = tempDir;
16564            } catch (IOException e) {
16565                Slog.w(TAG, "Failed to create copy file: " + e);
16566                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16567            }
16568
16569            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16570                @Override
16571                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16572                    if (!FileUtils.isValidExtFilename(name)) {
16573                        throw new IllegalArgumentException("Invalid filename: " + name);
16574                    }
16575                    try {
16576                        final File file = new File(codeFile, name);
16577                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16578                                O_RDWR | O_CREAT, 0644);
16579                        Os.chmod(file.getAbsolutePath(), 0644);
16580                        return new ParcelFileDescriptor(fd);
16581                    } catch (ErrnoException e) {
16582                        throw new RemoteException("Failed to open: " + e.getMessage());
16583                    }
16584                }
16585            };
16586
16587            int ret = PackageManager.INSTALL_SUCCEEDED;
16588            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16589            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16590                Slog.e(TAG, "Failed to copy package");
16591                return ret;
16592            }
16593
16594            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16595            NativeLibraryHelper.Handle handle = null;
16596            try {
16597                handle = NativeLibraryHelper.Handle.create(codeFile);
16598                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16599                        abiOverride);
16600            } catch (IOException e) {
16601                Slog.e(TAG, "Copying native libraries failed", e);
16602                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16603            } finally {
16604                IoUtils.closeQuietly(handle);
16605            }
16606
16607            return ret;
16608        }
16609
16610        int doPreInstall(int status) {
16611            if (status != PackageManager.INSTALL_SUCCEEDED) {
16612                cleanUp();
16613            }
16614            return status;
16615        }
16616
16617        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16618            if (status != PackageManager.INSTALL_SUCCEEDED) {
16619                cleanUp();
16620                return false;
16621            }
16622
16623            final File targetDir = codeFile.getParentFile();
16624            final File beforeCodeFile = codeFile;
16625            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16626
16627            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16628            try {
16629                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16630            } catch (ErrnoException e) {
16631                Slog.w(TAG, "Failed to rename", e);
16632                return false;
16633            }
16634
16635            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16636                Slog.w(TAG, "Failed to restorecon");
16637                return false;
16638            }
16639
16640            // Reflect the rename internally
16641            codeFile = afterCodeFile;
16642            resourceFile = afterCodeFile;
16643
16644            // Reflect the rename in scanned details
16645            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16646            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16647                    afterCodeFile, pkg.baseCodePath));
16648            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16649                    afterCodeFile, pkg.splitCodePaths));
16650
16651            // Reflect the rename in app info
16652            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16653            pkg.setApplicationInfoCodePath(pkg.codePath);
16654            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16655            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16656            pkg.setApplicationInfoResourcePath(pkg.codePath);
16657            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16658            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16659
16660            return true;
16661        }
16662
16663        int doPostInstall(int status, int uid) {
16664            if (status != PackageManager.INSTALL_SUCCEEDED) {
16665                cleanUp();
16666            }
16667            return status;
16668        }
16669
16670        @Override
16671        String getCodePath() {
16672            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16673        }
16674
16675        @Override
16676        String getResourcePath() {
16677            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16678        }
16679
16680        private boolean cleanUp() {
16681            if (codeFile == null || !codeFile.exists()) {
16682                return false;
16683            }
16684
16685            removeCodePathLI(codeFile);
16686
16687            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16688                resourceFile.delete();
16689            }
16690
16691            return true;
16692        }
16693
16694        void cleanUpResourcesLI() {
16695            // Try enumerating all code paths before deleting
16696            List<String> allCodePaths = Collections.EMPTY_LIST;
16697            if (codeFile != null && codeFile.exists()) {
16698                try {
16699                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16700                    allCodePaths = pkg.getAllCodePaths();
16701                } catch (PackageParserException e) {
16702                    // Ignored; we tried our best
16703                }
16704            }
16705
16706            cleanUp();
16707            removeDexFiles(allCodePaths, instructionSets);
16708        }
16709
16710        boolean doPostDeleteLI(boolean delete) {
16711            // XXX err, shouldn't we respect the delete flag?
16712            cleanUpResourcesLI();
16713            return true;
16714        }
16715    }
16716
16717    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16718            PackageManagerException {
16719        if (copyRet < 0) {
16720            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16721                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16722                throw new PackageManagerException(copyRet, message);
16723            }
16724        }
16725    }
16726
16727    /**
16728     * Extract the StorageManagerService "container ID" from the full code path of an
16729     * .apk.
16730     */
16731    static String cidFromCodePath(String fullCodePath) {
16732        int eidx = fullCodePath.lastIndexOf("/");
16733        String subStr1 = fullCodePath.substring(0, eidx);
16734        int sidx = subStr1.lastIndexOf("/");
16735        return subStr1.substring(sidx+1, eidx);
16736    }
16737
16738    /**
16739     * Logic to handle movement of existing installed applications.
16740     */
16741    class MoveInstallArgs extends InstallArgs {
16742        private File codeFile;
16743        private File resourceFile;
16744
16745        /** New install */
16746        MoveInstallArgs(InstallParams params) {
16747            super(params.origin, params.move, params.observer, params.installFlags,
16748                    params.installerPackageName, params.volumeUuid,
16749                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16750                    params.grantedRuntimePermissions,
16751                    params.traceMethod, params.traceCookie, params.certificates,
16752                    params.installReason);
16753        }
16754
16755        int copyApk(IMediaContainerService imcs, boolean temp) {
16756            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16757                    + move.fromUuid + " to " + move.toUuid);
16758            synchronized (mInstaller) {
16759                try {
16760                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16761                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16762                } catch (InstallerException e) {
16763                    Slog.w(TAG, "Failed to move app", e);
16764                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16765                }
16766            }
16767
16768            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16769            resourceFile = codeFile;
16770            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16771
16772            return PackageManager.INSTALL_SUCCEEDED;
16773        }
16774
16775        int doPreInstall(int status) {
16776            if (status != PackageManager.INSTALL_SUCCEEDED) {
16777                cleanUp(move.toUuid);
16778            }
16779            return status;
16780        }
16781
16782        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16783            if (status != PackageManager.INSTALL_SUCCEEDED) {
16784                cleanUp(move.toUuid);
16785                return false;
16786            }
16787
16788            // Reflect the move in app info
16789            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16790            pkg.setApplicationInfoCodePath(pkg.codePath);
16791            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16792            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16793            pkg.setApplicationInfoResourcePath(pkg.codePath);
16794            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16795            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16796
16797            return true;
16798        }
16799
16800        int doPostInstall(int status, int uid) {
16801            if (status == PackageManager.INSTALL_SUCCEEDED) {
16802                cleanUp(move.fromUuid);
16803            } else {
16804                cleanUp(move.toUuid);
16805            }
16806            return status;
16807        }
16808
16809        @Override
16810        String getCodePath() {
16811            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16812        }
16813
16814        @Override
16815        String getResourcePath() {
16816            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16817        }
16818
16819        private boolean cleanUp(String volumeUuid) {
16820            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16821                    move.dataAppName);
16822            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16823            final int[] userIds = sUserManager.getUserIds();
16824            synchronized (mInstallLock) {
16825                // Clean up both app data and code
16826                // All package moves are frozen until finished
16827                for (int userId : userIds) {
16828                    try {
16829                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16830                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16831                    } catch (InstallerException e) {
16832                        Slog.w(TAG, String.valueOf(e));
16833                    }
16834                }
16835                removeCodePathLI(codeFile);
16836            }
16837            return true;
16838        }
16839
16840        void cleanUpResourcesLI() {
16841            throw new UnsupportedOperationException();
16842        }
16843
16844        boolean doPostDeleteLI(boolean delete) {
16845            throw new UnsupportedOperationException();
16846        }
16847    }
16848
16849    static String getAsecPackageName(String packageCid) {
16850        int idx = packageCid.lastIndexOf("-");
16851        if (idx == -1) {
16852            return packageCid;
16853        }
16854        return packageCid.substring(0, idx);
16855    }
16856
16857    // Utility method used to create code paths based on package name and available index.
16858    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16859        String idxStr = "";
16860        int idx = 1;
16861        // Fall back to default value of idx=1 if prefix is not
16862        // part of oldCodePath
16863        if (oldCodePath != null) {
16864            String subStr = oldCodePath;
16865            // Drop the suffix right away
16866            if (suffix != null && subStr.endsWith(suffix)) {
16867                subStr = subStr.substring(0, subStr.length() - suffix.length());
16868            }
16869            // If oldCodePath already contains prefix find out the
16870            // ending index to either increment or decrement.
16871            int sidx = subStr.lastIndexOf(prefix);
16872            if (sidx != -1) {
16873                subStr = subStr.substring(sidx + prefix.length());
16874                if (subStr != null) {
16875                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16876                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16877                    }
16878                    try {
16879                        idx = Integer.parseInt(subStr);
16880                        if (idx <= 1) {
16881                            idx++;
16882                        } else {
16883                            idx--;
16884                        }
16885                    } catch(NumberFormatException e) {
16886                    }
16887                }
16888            }
16889        }
16890        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16891        return prefix + idxStr;
16892    }
16893
16894    private File getNextCodePath(File targetDir, String packageName) {
16895        File result;
16896        SecureRandom random = new SecureRandom();
16897        byte[] bytes = new byte[16];
16898        do {
16899            random.nextBytes(bytes);
16900            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16901            result = new File(targetDir, packageName + "-" + suffix);
16902        } while (result.exists());
16903        return result;
16904    }
16905
16906    // Utility method that returns the relative package path with respect
16907    // to the installation directory. Like say for /data/data/com.test-1.apk
16908    // string com.test-1 is returned.
16909    static String deriveCodePathName(String codePath) {
16910        if (codePath == null) {
16911            return null;
16912        }
16913        final File codeFile = new File(codePath);
16914        final String name = codeFile.getName();
16915        if (codeFile.isDirectory()) {
16916            return name;
16917        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16918            final int lastDot = name.lastIndexOf('.');
16919            return name.substring(0, lastDot);
16920        } else {
16921            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16922            return null;
16923        }
16924    }
16925
16926    static class PackageInstalledInfo {
16927        String name;
16928        int uid;
16929        // The set of users that originally had this package installed.
16930        int[] origUsers;
16931        // The set of users that now have this package installed.
16932        int[] newUsers;
16933        PackageParser.Package pkg;
16934        int returnCode;
16935        String returnMsg;
16936        String installerPackageName;
16937        PackageRemovedInfo removedInfo;
16938        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16939
16940        public void setError(int code, String msg) {
16941            setReturnCode(code);
16942            setReturnMessage(msg);
16943            Slog.w(TAG, msg);
16944        }
16945
16946        public void setError(String msg, PackageParserException e) {
16947            setReturnCode(e.error);
16948            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16949            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16950            for (int i = 0; i < childCount; i++) {
16951                addedChildPackages.valueAt(i).setError(msg, e);
16952            }
16953            Slog.w(TAG, msg, e);
16954        }
16955
16956        public void setError(String msg, PackageManagerException e) {
16957            returnCode = e.error;
16958            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16959            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16960            for (int i = 0; i < childCount; i++) {
16961                addedChildPackages.valueAt(i).setError(msg, e);
16962            }
16963            Slog.w(TAG, msg, e);
16964        }
16965
16966        public void setReturnCode(int returnCode) {
16967            this.returnCode = returnCode;
16968            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16969            for (int i = 0; i < childCount; i++) {
16970                addedChildPackages.valueAt(i).returnCode = returnCode;
16971            }
16972        }
16973
16974        private void setReturnMessage(String returnMsg) {
16975            this.returnMsg = returnMsg;
16976            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16977            for (int i = 0; i < childCount; i++) {
16978                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16979            }
16980        }
16981
16982        // In some error cases we want to convey more info back to the observer
16983        String origPackage;
16984        String origPermission;
16985    }
16986
16987    /*
16988     * Install a non-existing package.
16989     */
16990    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16991            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16992            PackageInstalledInfo res, int installReason) {
16993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16994
16995        // Remember this for later, in case we need to rollback this install
16996        String pkgName = pkg.packageName;
16997
16998        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16999
17000        synchronized(mPackages) {
17001            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17002            if (renamedPackage != null) {
17003                // A package with the same name is already installed, though
17004                // it has been renamed to an older name.  The package we
17005                // are trying to install should be installed as an update to
17006                // the existing one, but that has not been requested, so bail.
17007                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17008                        + " without first uninstalling package running as "
17009                        + renamedPackage);
17010                return;
17011            }
17012            if (mPackages.containsKey(pkgName)) {
17013                // Don't allow installation over an existing package with the same name.
17014                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17015                        + " without first uninstalling.");
17016                return;
17017            }
17018        }
17019
17020        try {
17021            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17022                    System.currentTimeMillis(), user);
17023
17024            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17025
17026            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17027                prepareAppDataAfterInstallLIF(newPackage);
17028
17029            } else {
17030                // Remove package from internal structures, but keep around any
17031                // data that might have already existed
17032                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17033                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17034            }
17035        } catch (PackageManagerException e) {
17036            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17037        }
17038
17039        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17040    }
17041
17042    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
17043        // Can't rotate keys during boot or if sharedUser.
17044        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
17045                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17046            return false;
17047        }
17048        // app is using upgradeKeySets; make sure all are valid
17049        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17050        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17051        for (int i = 0; i < upgradeKeySets.length; i++) {
17052            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17053                Slog.wtf(TAG, "Package "
17054                         + (oldPs.name != null ? oldPs.name : "<null>")
17055                         + " contains upgrade-key-set reference to unknown key-set: "
17056                         + upgradeKeySets[i]
17057                         + " reverting to signatures check.");
17058                return false;
17059            }
17060        }
17061        return true;
17062    }
17063
17064    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
17065        // Upgrade keysets are being used.  Determine if new package has a superset of the
17066        // required keys.
17067        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17068        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17069        for (int i = 0; i < upgradeKeySets.length; i++) {
17070            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17071            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17072                return true;
17073            }
17074        }
17075        return false;
17076    }
17077
17078    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17079        try (DigestInputStream digestStream =
17080                new DigestInputStream(new FileInputStream(file), digest)) {
17081            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17082        }
17083    }
17084
17085    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17086            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17087            int installReason) {
17088        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17089
17090        final PackageParser.Package oldPackage;
17091        final PackageSetting ps;
17092        final String pkgName = pkg.packageName;
17093        final int[] allUsers;
17094        final int[] installedUsers;
17095
17096        synchronized(mPackages) {
17097            oldPackage = mPackages.get(pkgName);
17098            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17099
17100            // don't allow upgrade to target a release SDK from a pre-release SDK
17101            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17102                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17103            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17104                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17105            if (oldTargetsPreRelease
17106                    && !newTargetsPreRelease
17107                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17108                Slog.w(TAG, "Can't install package targeting released sdk");
17109                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17110                return;
17111            }
17112
17113            ps = mSettings.mPackages.get(pkgName);
17114
17115            // verify signatures are valid
17116            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17117                if (!checkUpgradeKeySetLP(ps, pkg)) {
17118                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17119                            "New package not signed by keys specified by upgrade-keysets: "
17120                                    + pkgName);
17121                    return;
17122                }
17123            } else {
17124                // default to original signature matching
17125                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17126                        != PackageManager.SIGNATURE_MATCH) {
17127                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17128                            "New package has a different signature: " + pkgName);
17129                    return;
17130                }
17131            }
17132
17133            // don't allow a system upgrade unless the upgrade hash matches
17134            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17135                byte[] digestBytes = null;
17136                try {
17137                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17138                    updateDigest(digest, new File(pkg.baseCodePath));
17139                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17140                        for (String path : pkg.splitCodePaths) {
17141                            updateDigest(digest, new File(path));
17142                        }
17143                    }
17144                    digestBytes = digest.digest();
17145                } catch (NoSuchAlgorithmException | IOException e) {
17146                    res.setError(INSTALL_FAILED_INVALID_APK,
17147                            "Could not compute hash: " + pkgName);
17148                    return;
17149                }
17150                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17151                    res.setError(INSTALL_FAILED_INVALID_APK,
17152                            "New package fails restrict-update check: " + pkgName);
17153                    return;
17154                }
17155                // retain upgrade restriction
17156                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17157            }
17158
17159            // Check for shared user id changes
17160            String invalidPackageName =
17161                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17162            if (invalidPackageName != null) {
17163                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17164                        "Package " + invalidPackageName + " tried to change user "
17165                                + oldPackage.mSharedUserId);
17166                return;
17167            }
17168
17169            // In case of rollback, remember per-user/profile install state
17170            allUsers = sUserManager.getUserIds();
17171            installedUsers = ps.queryInstalledUsers(allUsers, true);
17172
17173            // don't allow an upgrade from full to ephemeral
17174            if (isInstantApp) {
17175                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17176                    for (int currentUser : allUsers) {
17177                        if (!ps.getInstantApp(currentUser)) {
17178                            // can't downgrade from full to instant
17179                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17180                                    + " for user: " + currentUser);
17181                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17182                            return;
17183                        }
17184                    }
17185                } else if (!ps.getInstantApp(user.getIdentifier())) {
17186                    // can't downgrade from full to instant
17187                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17188                            + " for user: " + user.getIdentifier());
17189                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17190                    return;
17191                }
17192            }
17193        }
17194
17195        // Update what is removed
17196        res.removedInfo = new PackageRemovedInfo(this);
17197        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17198        res.removedInfo.removedPackage = oldPackage.packageName;
17199        res.removedInfo.installerPackageName = ps.installerPackageName;
17200        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17201        res.removedInfo.isUpdate = true;
17202        res.removedInfo.origUsers = installedUsers;
17203        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17204        for (int i = 0; i < installedUsers.length; i++) {
17205            final int userId = installedUsers[i];
17206            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17207        }
17208
17209        final int childCount = (oldPackage.childPackages != null)
17210                ? oldPackage.childPackages.size() : 0;
17211        for (int i = 0; i < childCount; i++) {
17212            boolean childPackageUpdated = false;
17213            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17214            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17215            if (res.addedChildPackages != null) {
17216                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17217                if (childRes != null) {
17218                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17219                    childRes.removedInfo.removedPackage = childPkg.packageName;
17220                    if (childPs != null) {
17221                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17222                    }
17223                    childRes.removedInfo.isUpdate = true;
17224                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17225                    childPackageUpdated = true;
17226                }
17227            }
17228            if (!childPackageUpdated) {
17229                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17230                childRemovedRes.removedPackage = childPkg.packageName;
17231                if (childPs != null) {
17232                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17233                }
17234                childRemovedRes.isUpdate = false;
17235                childRemovedRes.dataRemoved = true;
17236                synchronized (mPackages) {
17237                    if (childPs != null) {
17238                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17239                    }
17240                }
17241                if (res.removedInfo.removedChildPackages == null) {
17242                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17243                }
17244                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17245            }
17246        }
17247
17248        boolean sysPkg = (isSystemApp(oldPackage));
17249        if (sysPkg) {
17250            // Set the system/privileged/oem flags as needed
17251            final boolean privileged =
17252                    (oldPackage.applicationInfo.privateFlags
17253                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17254            final boolean oem =
17255                    (oldPackage.applicationInfo.privateFlags
17256                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17257            final int systemPolicyFlags = policyFlags
17258                    | PackageParser.PARSE_IS_SYSTEM
17259                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
17260                    | (oem ? PARSE_IS_OEM : 0);
17261
17262            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17263                    user, allUsers, installerPackageName, res, installReason);
17264        } else {
17265            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17266                    user, allUsers, installerPackageName, res, installReason);
17267        }
17268    }
17269
17270    @Override
17271    public List<String> getPreviousCodePaths(String packageName) {
17272        final int callingUid = Binder.getCallingUid();
17273        final List<String> result = new ArrayList<>();
17274        if (getInstantAppPackageName(callingUid) != null) {
17275            return result;
17276        }
17277        final PackageSetting ps = mSettings.mPackages.get(packageName);
17278        if (ps != null
17279                && ps.oldCodePaths != null
17280                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17281            result.addAll(ps.oldCodePaths);
17282        }
17283        return result;
17284    }
17285
17286    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17287            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17288            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17289            int installReason) {
17290        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17291                + deletedPackage);
17292
17293        String pkgName = deletedPackage.packageName;
17294        boolean deletedPkg = true;
17295        boolean addedPkg = false;
17296        boolean updatedSettings = false;
17297        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17298        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17299                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17300
17301        final long origUpdateTime = (pkg.mExtras != null)
17302                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17303
17304        // First delete the existing package while retaining the data directory
17305        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17306                res.removedInfo, true, pkg)) {
17307            // If the existing package wasn't successfully deleted
17308            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17309            deletedPkg = false;
17310        } else {
17311            // Successfully deleted the old package; proceed with replace.
17312
17313            // If deleted package lived in a container, give users a chance to
17314            // relinquish resources before killing.
17315            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17316                if (DEBUG_INSTALL) {
17317                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17318                }
17319                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17320                final ArrayList<String> pkgList = new ArrayList<String>(1);
17321                pkgList.add(deletedPackage.applicationInfo.packageName);
17322                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17323            }
17324
17325            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17326                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17327            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17328
17329            try {
17330                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17331                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17332                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17333                        installReason);
17334
17335                // Update the in-memory copy of the previous code paths.
17336                PackageSetting ps = mSettings.mPackages.get(pkgName);
17337                if (!killApp) {
17338                    if (ps.oldCodePaths == null) {
17339                        ps.oldCodePaths = new ArraySet<>();
17340                    }
17341                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17342                    if (deletedPackage.splitCodePaths != null) {
17343                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17344                    }
17345                } else {
17346                    ps.oldCodePaths = null;
17347                }
17348                if (ps.childPackageNames != null) {
17349                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17350                        final String childPkgName = ps.childPackageNames.get(i);
17351                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17352                        childPs.oldCodePaths = ps.oldCodePaths;
17353                    }
17354                }
17355                // set instant app status, but, only if it's explicitly specified
17356                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17357                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17358                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17359                prepareAppDataAfterInstallLIF(newPackage);
17360                addedPkg = true;
17361                mDexManager.notifyPackageUpdated(newPackage.packageName,
17362                        newPackage.baseCodePath, newPackage.splitCodePaths);
17363            } catch (PackageManagerException e) {
17364                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17365            }
17366        }
17367
17368        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17369            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17370
17371            // Revert all internal state mutations and added folders for the failed install
17372            if (addedPkg) {
17373                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17374                        res.removedInfo, true, null);
17375            }
17376
17377            // Restore the old package
17378            if (deletedPkg) {
17379                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17380                File restoreFile = new File(deletedPackage.codePath);
17381                // Parse old package
17382                boolean oldExternal = isExternal(deletedPackage);
17383                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17384                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17385                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17386                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17387                try {
17388                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17389                            null);
17390                } catch (PackageManagerException e) {
17391                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17392                            + e.getMessage());
17393                    return;
17394                }
17395
17396                synchronized (mPackages) {
17397                    // Ensure the installer package name up to date
17398                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17399
17400                    // Update permissions for restored package
17401                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17402
17403                    mSettings.writeLPr();
17404                }
17405
17406                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17407            }
17408        } else {
17409            synchronized (mPackages) {
17410                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17411                if (ps != null) {
17412                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17413                    if (res.removedInfo.removedChildPackages != null) {
17414                        final int childCount = res.removedInfo.removedChildPackages.size();
17415                        // Iterate in reverse as we may modify the collection
17416                        for (int i = childCount - 1; i >= 0; i--) {
17417                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17418                            if (res.addedChildPackages.containsKey(childPackageName)) {
17419                                res.removedInfo.removedChildPackages.removeAt(i);
17420                            } else {
17421                                PackageRemovedInfo childInfo = res.removedInfo
17422                                        .removedChildPackages.valueAt(i);
17423                                childInfo.removedForAllUsers = mPackages.get(
17424                                        childInfo.removedPackage) == null;
17425                            }
17426                        }
17427                    }
17428                }
17429            }
17430        }
17431    }
17432
17433    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17434            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17435            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17436            int installReason) {
17437        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17438                + ", old=" + deletedPackage);
17439
17440        final boolean disabledSystem;
17441
17442        // Remove existing system package
17443        removePackageLI(deletedPackage, true);
17444
17445        synchronized (mPackages) {
17446            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17447        }
17448        if (!disabledSystem) {
17449            // We didn't need to disable the .apk as a current system package,
17450            // which means we are replacing another update that is already
17451            // installed.  We need to make sure to delete the older one's .apk.
17452            res.removedInfo.args = createInstallArgsForExisting(0,
17453                    deletedPackage.applicationInfo.getCodePath(),
17454                    deletedPackage.applicationInfo.getResourcePath(),
17455                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17456        } else {
17457            res.removedInfo.args = null;
17458        }
17459
17460        // Successfully disabled the old package. Now proceed with re-installation
17461        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17462                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17463        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17464
17465        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17466        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17467                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17468
17469        PackageParser.Package newPackage = null;
17470        try {
17471            // Add the package to the internal data structures
17472            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17473
17474            // Set the update and install times
17475            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17476            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17477                    System.currentTimeMillis());
17478
17479            // Update the package dynamic state if succeeded
17480            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17481                // Now that the install succeeded make sure we remove data
17482                // directories for any child package the update removed.
17483                final int deletedChildCount = (deletedPackage.childPackages != null)
17484                        ? deletedPackage.childPackages.size() : 0;
17485                final int newChildCount = (newPackage.childPackages != null)
17486                        ? newPackage.childPackages.size() : 0;
17487                for (int i = 0; i < deletedChildCount; i++) {
17488                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17489                    boolean childPackageDeleted = true;
17490                    for (int j = 0; j < newChildCount; j++) {
17491                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17492                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17493                            childPackageDeleted = false;
17494                            break;
17495                        }
17496                    }
17497                    if (childPackageDeleted) {
17498                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17499                                deletedChildPkg.packageName);
17500                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17501                            PackageRemovedInfo removedChildRes = res.removedInfo
17502                                    .removedChildPackages.get(deletedChildPkg.packageName);
17503                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17504                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17505                        }
17506                    }
17507                }
17508
17509                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17510                        installReason);
17511                prepareAppDataAfterInstallLIF(newPackage);
17512
17513                mDexManager.notifyPackageUpdated(newPackage.packageName,
17514                            newPackage.baseCodePath, newPackage.splitCodePaths);
17515            }
17516        } catch (PackageManagerException e) {
17517            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17518            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17519        }
17520
17521        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17522            // Re installation failed. Restore old information
17523            // Remove new pkg information
17524            if (newPackage != null) {
17525                removeInstalledPackageLI(newPackage, true);
17526            }
17527            // Add back the old system package
17528            try {
17529                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17530            } catch (PackageManagerException e) {
17531                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17532            }
17533
17534            synchronized (mPackages) {
17535                if (disabledSystem) {
17536                    enableSystemPackageLPw(deletedPackage);
17537                }
17538
17539                // Ensure the installer package name up to date
17540                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17541
17542                // Update permissions for restored package
17543                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17544
17545                mSettings.writeLPr();
17546            }
17547
17548            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17549                    + " after failed upgrade");
17550        }
17551    }
17552
17553    /**
17554     * Checks whether the parent or any of the child packages have a change shared
17555     * user. For a package to be a valid update the shred users of the parent and
17556     * the children should match. We may later support changing child shared users.
17557     * @param oldPkg The updated package.
17558     * @param newPkg The update package.
17559     * @return The shared user that change between the versions.
17560     */
17561    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17562            PackageParser.Package newPkg) {
17563        // Check parent shared user
17564        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17565            return newPkg.packageName;
17566        }
17567        // Check child shared users
17568        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17569        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17570        for (int i = 0; i < newChildCount; i++) {
17571            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17572            // If this child was present, did it have the same shared user?
17573            for (int j = 0; j < oldChildCount; j++) {
17574                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17575                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17576                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17577                    return newChildPkg.packageName;
17578                }
17579            }
17580        }
17581        return null;
17582    }
17583
17584    private void removeNativeBinariesLI(PackageSetting ps) {
17585        // Remove the lib path for the parent package
17586        if (ps != null) {
17587            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17588            // Remove the lib path for the child packages
17589            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17590            for (int i = 0; i < childCount; i++) {
17591                PackageSetting childPs = null;
17592                synchronized (mPackages) {
17593                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17594                }
17595                if (childPs != null) {
17596                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17597                            .legacyNativeLibraryPathString);
17598                }
17599            }
17600        }
17601    }
17602
17603    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17604        // Enable the parent package
17605        mSettings.enableSystemPackageLPw(pkg.packageName);
17606        // Enable the child packages
17607        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17608        for (int i = 0; i < childCount; i++) {
17609            PackageParser.Package childPkg = pkg.childPackages.get(i);
17610            mSettings.enableSystemPackageLPw(childPkg.packageName);
17611        }
17612    }
17613
17614    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17615            PackageParser.Package newPkg) {
17616        // Disable the parent package (parent always replaced)
17617        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17618        // Disable the child packages
17619        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17620        for (int i = 0; i < childCount; i++) {
17621            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17622            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17623            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17624        }
17625        return disabled;
17626    }
17627
17628    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17629            String installerPackageName) {
17630        // Enable the parent package
17631        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17632        // Enable the child packages
17633        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17634        for (int i = 0; i < childCount; i++) {
17635            PackageParser.Package childPkg = pkg.childPackages.get(i);
17636            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17637        }
17638    }
17639
17640    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17641        // Collect all used permissions in the UID
17642        ArraySet<String> usedPermissions = new ArraySet<>();
17643        final int packageCount = su.packages.size();
17644        for (int i = 0; i < packageCount; i++) {
17645            PackageSetting ps = su.packages.valueAt(i);
17646            if (ps.pkg == null) {
17647                continue;
17648            }
17649            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17650            for (int j = 0; j < requestedPermCount; j++) {
17651                String permission = ps.pkg.requestedPermissions.get(j);
17652                BasePermission bp = mSettings.mPermissions.get(permission);
17653                if (bp != null) {
17654                    usedPermissions.add(permission);
17655                }
17656            }
17657        }
17658
17659        PermissionsState permissionsState = su.getPermissionsState();
17660        // Prune install permissions
17661        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17662        final int installPermCount = installPermStates.size();
17663        for (int i = installPermCount - 1; i >= 0;  i--) {
17664            PermissionState permissionState = installPermStates.get(i);
17665            if (!usedPermissions.contains(permissionState.getName())) {
17666                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17667                if (bp != null) {
17668                    permissionsState.revokeInstallPermission(bp);
17669                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17670                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17671                }
17672            }
17673        }
17674
17675        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17676
17677        // Prune runtime permissions
17678        for (int userId : allUserIds) {
17679            List<PermissionState> runtimePermStates = permissionsState
17680                    .getRuntimePermissionStates(userId);
17681            final int runtimePermCount = runtimePermStates.size();
17682            for (int i = runtimePermCount - 1; i >= 0; i--) {
17683                PermissionState permissionState = runtimePermStates.get(i);
17684                if (!usedPermissions.contains(permissionState.getName())) {
17685                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17686                    if (bp != null) {
17687                        permissionsState.revokeRuntimePermission(bp, userId);
17688                        permissionsState.updatePermissionFlags(bp, userId,
17689                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17690                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17691                                runtimePermissionChangedUserIds, userId);
17692                    }
17693                }
17694            }
17695        }
17696
17697        return runtimePermissionChangedUserIds;
17698    }
17699
17700    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17701            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17702        // Update the parent package setting
17703        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17704                res, user, installReason);
17705        // Update the child packages setting
17706        final int childCount = (newPackage.childPackages != null)
17707                ? newPackage.childPackages.size() : 0;
17708        for (int i = 0; i < childCount; i++) {
17709            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17710            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17711            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17712                    childRes.origUsers, childRes, user, installReason);
17713        }
17714    }
17715
17716    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17717            String installerPackageName, int[] allUsers, int[] installedForUsers,
17718            PackageInstalledInfo res, UserHandle user, int installReason) {
17719        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17720
17721        String pkgName = newPackage.packageName;
17722        synchronized (mPackages) {
17723            //write settings. the installStatus will be incomplete at this stage.
17724            //note that the new package setting would have already been
17725            //added to mPackages. It hasn't been persisted yet.
17726            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17727            // TODO: Remove this write? It's also written at the end of this method
17728            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17729            mSettings.writeLPr();
17730            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17731        }
17732
17733        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17734        synchronized (mPackages) {
17735            updatePermissionsLPw(newPackage.packageName, newPackage,
17736                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17737                            ? UPDATE_PERMISSIONS_ALL : 0));
17738            // For system-bundled packages, we assume that installing an upgraded version
17739            // of the package implies that the user actually wants to run that new code,
17740            // so we enable the package.
17741            PackageSetting ps = mSettings.mPackages.get(pkgName);
17742            final int userId = user.getIdentifier();
17743            if (ps != null) {
17744                if (isSystemApp(newPackage)) {
17745                    if (DEBUG_INSTALL) {
17746                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17747                    }
17748                    // Enable system package for requested users
17749                    if (res.origUsers != null) {
17750                        for (int origUserId : res.origUsers) {
17751                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17752                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17753                                        origUserId, installerPackageName);
17754                            }
17755                        }
17756                    }
17757                    // Also convey the prior install/uninstall state
17758                    if (allUsers != null && installedForUsers != null) {
17759                        for (int currentUserId : allUsers) {
17760                            final boolean installed = ArrayUtils.contains(
17761                                    installedForUsers, currentUserId);
17762                            if (DEBUG_INSTALL) {
17763                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17764                            }
17765                            ps.setInstalled(installed, currentUserId);
17766                        }
17767                        // these install state changes will be persisted in the
17768                        // upcoming call to mSettings.writeLPr().
17769                    }
17770                }
17771                // It's implied that when a user requests installation, they want the app to be
17772                // installed and enabled.
17773                if (userId != UserHandle.USER_ALL) {
17774                    ps.setInstalled(true, userId);
17775                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17776                }
17777
17778                // When replacing an existing package, preserve the original install reason for all
17779                // users that had the package installed before.
17780                final Set<Integer> previousUserIds = new ArraySet<>();
17781                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17782                    final int installReasonCount = res.removedInfo.installReasons.size();
17783                    for (int i = 0; i < installReasonCount; i++) {
17784                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17785                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17786                        ps.setInstallReason(previousInstallReason, previousUserId);
17787                        previousUserIds.add(previousUserId);
17788                    }
17789                }
17790
17791                // Set install reason for users that are having the package newly installed.
17792                if (userId == UserHandle.USER_ALL) {
17793                    for (int currentUserId : sUserManager.getUserIds()) {
17794                        if (!previousUserIds.contains(currentUserId)) {
17795                            ps.setInstallReason(installReason, currentUserId);
17796                        }
17797                    }
17798                } else if (!previousUserIds.contains(userId)) {
17799                    ps.setInstallReason(installReason, userId);
17800                }
17801                mSettings.writeKernelMappingLPr(ps);
17802            }
17803            res.name = pkgName;
17804            res.uid = newPackage.applicationInfo.uid;
17805            res.pkg = newPackage;
17806            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17807            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17808            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17809            //to update install status
17810            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17811            mSettings.writeLPr();
17812            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17813        }
17814
17815        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17816    }
17817
17818    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17819        try {
17820            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17821            installPackageLI(args, res);
17822        } finally {
17823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17824        }
17825    }
17826
17827    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17828        final int installFlags = args.installFlags;
17829        final String installerPackageName = args.installerPackageName;
17830        final String volumeUuid = args.volumeUuid;
17831        final File tmpPackageFile = new File(args.getCodePath());
17832        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17833        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17834                || (args.volumeUuid != null));
17835        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17836        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17837        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17838        final boolean virtualPreload =
17839                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17840        boolean replace = false;
17841        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17842        if (args.move != null) {
17843            // moving a complete application; perform an initial scan on the new install location
17844            scanFlags |= SCAN_INITIAL;
17845        }
17846        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17847            scanFlags |= SCAN_DONT_KILL_APP;
17848        }
17849        if (instantApp) {
17850            scanFlags |= SCAN_AS_INSTANT_APP;
17851        }
17852        if (fullApp) {
17853            scanFlags |= SCAN_AS_FULL_APP;
17854        }
17855        if (virtualPreload) {
17856            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17857        }
17858
17859        // Result object to be returned
17860        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17861        res.installerPackageName = installerPackageName;
17862
17863        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17864
17865        // Sanity check
17866        if (instantApp && (forwardLocked || onExternal)) {
17867            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17868                    + " external=" + onExternal);
17869            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17870            return;
17871        }
17872
17873        // Retrieve PackageSettings and parse package
17874        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17875                | PackageParser.PARSE_ENFORCE_CODE
17876                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17877                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17878                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17879                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17880        PackageParser pp = new PackageParser();
17881        pp.setSeparateProcesses(mSeparateProcesses);
17882        pp.setDisplayMetrics(mMetrics);
17883        pp.setCallback(mPackageParserCallback);
17884
17885        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17886        final PackageParser.Package pkg;
17887        try {
17888            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17889        } catch (PackageParserException e) {
17890            res.setError("Failed parse during installPackageLI", e);
17891            return;
17892        } finally {
17893            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17894        }
17895
17896        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17897        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17898            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17899            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17900                    "Instant app package must target O");
17901            return;
17902        }
17903        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17904            Slog.w(TAG, "Instant app package " + pkg.packageName
17905                    + " does not target targetSandboxVersion 2");
17906            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17907                    "Instant app package must use targetSanboxVersion 2");
17908            return;
17909        }
17910
17911        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17912            // Static shared libraries have synthetic package names
17913            renameStaticSharedLibraryPackage(pkg);
17914
17915            // No static shared libs on external storage
17916            if (onExternal) {
17917                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17918                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17919                        "Packages declaring static-shared libs cannot be updated");
17920                return;
17921            }
17922        }
17923
17924        // If we are installing a clustered package add results for the children
17925        if (pkg.childPackages != null) {
17926            synchronized (mPackages) {
17927                final int childCount = pkg.childPackages.size();
17928                for (int i = 0; i < childCount; i++) {
17929                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17930                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17931                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17932                    childRes.pkg = childPkg;
17933                    childRes.name = childPkg.packageName;
17934                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17935                    if (childPs != null) {
17936                        childRes.origUsers = childPs.queryInstalledUsers(
17937                                sUserManager.getUserIds(), true);
17938                    }
17939                    if ((mPackages.containsKey(childPkg.packageName))) {
17940                        childRes.removedInfo = new PackageRemovedInfo(this);
17941                        childRes.removedInfo.removedPackage = childPkg.packageName;
17942                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17943                    }
17944                    if (res.addedChildPackages == null) {
17945                        res.addedChildPackages = new ArrayMap<>();
17946                    }
17947                    res.addedChildPackages.put(childPkg.packageName, childRes);
17948                }
17949            }
17950        }
17951
17952        // If package doesn't declare API override, mark that we have an install
17953        // time CPU ABI override.
17954        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17955            pkg.cpuAbiOverride = args.abiOverride;
17956        }
17957
17958        String pkgName = res.name = pkg.packageName;
17959        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17960            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17961                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17962                return;
17963            }
17964        }
17965
17966        try {
17967            // either use what we've been given or parse directly from the APK
17968            if (args.certificates != null) {
17969                try {
17970                    PackageParser.populateCertificates(pkg, args.certificates);
17971                } catch (PackageParserException e) {
17972                    // there was something wrong with the certificates we were given;
17973                    // try to pull them from the APK
17974                    PackageParser.collectCertificates(pkg, parseFlags);
17975                }
17976            } else {
17977                PackageParser.collectCertificates(pkg, parseFlags);
17978            }
17979        } catch (PackageParserException e) {
17980            res.setError("Failed collect during installPackageLI", e);
17981            return;
17982        }
17983
17984        // Get rid of all references to package scan path via parser.
17985        pp = null;
17986        String oldCodePath = null;
17987        boolean systemApp = false;
17988        synchronized (mPackages) {
17989            // Check if installing already existing package
17990            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17991                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17992                if (pkg.mOriginalPackages != null
17993                        && pkg.mOriginalPackages.contains(oldName)
17994                        && mPackages.containsKey(oldName)) {
17995                    // This package is derived from an original package,
17996                    // and this device has been updating from that original
17997                    // name.  We must continue using the original name, so
17998                    // rename the new package here.
17999                    pkg.setPackageName(oldName);
18000                    pkgName = pkg.packageName;
18001                    replace = true;
18002                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18003                            + oldName + " pkgName=" + pkgName);
18004                } else if (mPackages.containsKey(pkgName)) {
18005                    // This package, under its official name, already exists
18006                    // on the device; we should replace it.
18007                    replace = true;
18008                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18009                }
18010
18011                // Child packages are installed through the parent package
18012                if (pkg.parentPackage != null) {
18013                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18014                            "Package " + pkg.packageName + " is child of package "
18015                                    + pkg.parentPackage.parentPackage + ". Child packages "
18016                                    + "can be updated only through the parent package.");
18017                    return;
18018                }
18019
18020                if (replace) {
18021                    // Prevent apps opting out from runtime permissions
18022                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18023                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18024                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18025                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18026                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18027                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18028                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18029                                        + " doesn't support runtime permissions but the old"
18030                                        + " target SDK " + oldTargetSdk + " does.");
18031                        return;
18032                    }
18033                    // Prevent apps from downgrading their targetSandbox.
18034                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18035                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18036                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18037                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18038                                "Package " + pkg.packageName + " new target sandbox "
18039                                + newTargetSandbox + " is incompatible with the previous value of"
18040                                + oldTargetSandbox + ".");
18041                        return;
18042                    }
18043
18044                    // Prevent installing of child packages
18045                    if (oldPackage.parentPackage != null) {
18046                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18047                                "Package " + pkg.packageName + " is child of package "
18048                                        + oldPackage.parentPackage + ". Child packages "
18049                                        + "can be updated only through the parent package.");
18050                        return;
18051                    }
18052                }
18053            }
18054
18055            PackageSetting ps = mSettings.mPackages.get(pkgName);
18056            if (ps != null) {
18057                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18058
18059                // Static shared libs have same package with different versions where
18060                // we internally use a synthetic package name to allow multiple versions
18061                // of the same package, therefore we need to compare signatures against
18062                // the package setting for the latest library version.
18063                PackageSetting signatureCheckPs = ps;
18064                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18065                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18066                    if (libraryEntry != null) {
18067                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18068                    }
18069                }
18070
18071                // Quick sanity check that we're signed correctly if updating;
18072                // we'll check this again later when scanning, but we want to
18073                // bail early here before tripping over redefined permissions.
18074                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18075                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18076                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18077                                + pkg.packageName + " upgrade keys do not match the "
18078                                + "previously installed version");
18079                        return;
18080                    }
18081                } else {
18082                    try {
18083                        verifySignaturesLP(signatureCheckPs, pkg);
18084                    } catch (PackageManagerException e) {
18085                        res.setError(e.error, e.getMessage());
18086                        return;
18087                    }
18088                }
18089
18090                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18091                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18092                    systemApp = (ps.pkg.applicationInfo.flags &
18093                            ApplicationInfo.FLAG_SYSTEM) != 0;
18094                }
18095                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18096            }
18097
18098            int N = pkg.permissions.size();
18099            for (int i = N-1; i >= 0; i--) {
18100                PackageParser.Permission perm = pkg.permissions.get(i);
18101                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18102
18103                // Don't allow anyone but the system to define ephemeral permissions.
18104                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18105                        && !systemApp) {
18106                    Slog.w(TAG, "Non-System package " + pkg.packageName
18107                            + " attempting to delcare ephemeral permission "
18108                            + perm.info.name + "; Removing ephemeral.");
18109                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18110                }
18111
18112                // Check whether the newly-scanned package wants to define an already-defined perm
18113                if (bp != null) {
18114                    // If the defining package is signed with our cert, it's okay.  This
18115                    // also includes the "updating the same package" case, of course.
18116                    // "updating same package" could also involve key-rotation.
18117                    final boolean sigsOk;
18118                    final String sourcePackageName = bp.getSourcePackageName();
18119                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
18120                    if (sourcePackageName.equals(pkg.packageName)
18121                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
18122                                    scanFlags))) {
18123                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
18124                    } else {
18125                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
18126                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18127                    }
18128                    if (!sigsOk) {
18129                        // If the owning package is the system itself, we log but allow
18130                        // install to proceed; we fail the install on all other permission
18131                        // redefinitions.
18132                        if (!sourcePackageName.equals("android")) {
18133                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18134                                    + pkg.packageName + " attempting to redeclare permission "
18135                                    + perm.info.name + " already owned by " + sourcePackageName);
18136                            res.origPermission = perm.info.name;
18137                            res.origPackage = sourcePackageName;
18138                            return;
18139                        } else {
18140                            Slog.w(TAG, "Package " + pkg.packageName
18141                                    + " attempting to redeclare system permission "
18142                                    + perm.info.name + "; ignoring new declaration");
18143                            pkg.permissions.remove(i);
18144                        }
18145                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18146                        // Prevent apps to change protection level to dangerous from any other
18147                        // type as this would allow a privilege escalation where an app adds a
18148                        // normal/signature permission in other app's group and later redefines
18149                        // it as dangerous leading to the group auto-grant.
18150                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18151                                == PermissionInfo.PROTECTION_DANGEROUS) {
18152                            if (bp != null && !bp.isRuntime()) {
18153                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18154                                        + "non-runtime permission " + perm.info.name
18155                                        + " to runtime; keeping old protection level");
18156                                perm.info.protectionLevel = bp.getProtectionLevel();
18157                            }
18158                        }
18159                    }
18160                }
18161            }
18162        }
18163
18164        if (systemApp) {
18165            if (onExternal) {
18166                // Abort update; system app can't be replaced with app on sdcard
18167                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18168                        "Cannot install updates to system apps on sdcard");
18169                return;
18170            } else if (instantApp) {
18171                // Abort update; system app can't be replaced with an instant app
18172                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18173                        "Cannot update a system app with an instant app");
18174                return;
18175            }
18176        }
18177
18178        if (args.move != null) {
18179            // We did an in-place move, so dex is ready to roll
18180            scanFlags |= SCAN_NO_DEX;
18181            scanFlags |= SCAN_MOVE;
18182
18183            synchronized (mPackages) {
18184                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18185                if (ps == null) {
18186                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18187                            "Missing settings for moved package " + pkgName);
18188                }
18189
18190                // We moved the entire application as-is, so bring over the
18191                // previously derived ABI information.
18192                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18193                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18194            }
18195
18196        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18197            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18198            scanFlags |= SCAN_NO_DEX;
18199
18200            try {
18201                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18202                    args.abiOverride : pkg.cpuAbiOverride);
18203                final boolean extractNativeLibs = !pkg.isLibrary();
18204                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18205                        extractNativeLibs, mAppLib32InstallDir);
18206            } catch (PackageManagerException pme) {
18207                Slog.e(TAG, "Error deriving application ABI", pme);
18208                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18209                return;
18210            }
18211
18212            // Shared libraries for the package need to be updated.
18213            synchronized (mPackages) {
18214                try {
18215                    updateSharedLibrariesLPr(pkg, null);
18216                } catch (PackageManagerException e) {
18217                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18218                }
18219            }
18220        }
18221
18222        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18223            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18224            return;
18225        }
18226
18227        // Verify if we need to dexopt the app.
18228        //
18229        // NOTE: it is *important* to call dexopt after doRename which will sync the
18230        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18231        //
18232        // We only need to dexopt if the package meets ALL of the following conditions:
18233        //   1) it is not forward locked.
18234        //   2) it is not on on an external ASEC container.
18235        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18236        //
18237        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18238        // complete, so we skip this step during installation. Instead, we'll take extra time
18239        // the first time the instant app starts. It's preferred to do it this way to provide
18240        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18241        // middle of running an instant app. The default behaviour can be overridden
18242        // via gservices.
18243        final boolean performDexopt = !forwardLocked
18244            && !pkg.applicationInfo.isExternalAsec()
18245            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18246                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18247
18248        if (performDexopt) {
18249            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18250            // Do not run PackageDexOptimizer through the local performDexOpt
18251            // method because `pkg` may not be in `mPackages` yet.
18252            //
18253            // Also, don't fail application installs if the dexopt step fails.
18254            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18255                REASON_INSTALL,
18256                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18257            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18258                null /* instructionSets */,
18259                getOrCreateCompilerPackageStats(pkg),
18260                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18261                dexoptOptions);
18262            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18263        }
18264
18265        // Notify BackgroundDexOptService that the package has been changed.
18266        // If this is an update of a package which used to fail to compile,
18267        // BackgroundDexOptService will remove it from its blacklist.
18268        // TODO: Layering violation
18269        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18270
18271        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18272
18273        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18274                "installPackageLI")) {
18275            if (replace) {
18276                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18277                    // Static libs have a synthetic package name containing the version
18278                    // and cannot be updated as an update would get a new package name,
18279                    // unless this is the exact same version code which is useful for
18280                    // development.
18281                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18282                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18283                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18284                                + "static-shared libs cannot be updated");
18285                        return;
18286                    }
18287                }
18288                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18289                        installerPackageName, res, args.installReason);
18290            } else {
18291                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18292                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18293            }
18294        }
18295
18296        synchronized (mPackages) {
18297            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18298            if (ps != null) {
18299                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18300                ps.setUpdateAvailable(false /*updateAvailable*/);
18301            }
18302
18303            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18304            for (int i = 0; i < childCount; i++) {
18305                PackageParser.Package childPkg = pkg.childPackages.get(i);
18306                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18307                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18308                if (childPs != null) {
18309                    childRes.newUsers = childPs.queryInstalledUsers(
18310                            sUserManager.getUserIds(), true);
18311                }
18312            }
18313
18314            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18315                updateSequenceNumberLP(ps, res.newUsers);
18316                updateInstantAppInstallerLocked(pkgName);
18317            }
18318        }
18319    }
18320
18321    private void startIntentFilterVerifications(int userId, boolean replacing,
18322            PackageParser.Package pkg) {
18323        if (mIntentFilterVerifierComponent == null) {
18324            Slog.w(TAG, "No IntentFilter verification will not be done as "
18325                    + "there is no IntentFilterVerifier available!");
18326            return;
18327        }
18328
18329        final int verifierUid = getPackageUid(
18330                mIntentFilterVerifierComponent.getPackageName(),
18331                MATCH_DEBUG_TRIAGED_MISSING,
18332                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18333
18334        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18335        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18336        mHandler.sendMessage(msg);
18337
18338        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18339        for (int i = 0; i < childCount; i++) {
18340            PackageParser.Package childPkg = pkg.childPackages.get(i);
18341            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18342            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18343            mHandler.sendMessage(msg);
18344        }
18345    }
18346
18347    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18348            PackageParser.Package pkg) {
18349        int size = pkg.activities.size();
18350        if (size == 0) {
18351            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18352                    "No activity, so no need to verify any IntentFilter!");
18353            return;
18354        }
18355
18356        final boolean hasDomainURLs = hasDomainURLs(pkg);
18357        if (!hasDomainURLs) {
18358            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18359                    "No domain URLs, so no need to verify any IntentFilter!");
18360            return;
18361        }
18362
18363        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18364                + " if any IntentFilter from the " + size
18365                + " Activities needs verification ...");
18366
18367        int count = 0;
18368        final String packageName = pkg.packageName;
18369
18370        synchronized (mPackages) {
18371            // If this is a new install and we see that we've already run verification for this
18372            // package, we have nothing to do: it means the state was restored from backup.
18373            if (!replacing) {
18374                IntentFilterVerificationInfo ivi =
18375                        mSettings.getIntentFilterVerificationLPr(packageName);
18376                if (ivi != null) {
18377                    if (DEBUG_DOMAIN_VERIFICATION) {
18378                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18379                                + ivi.getStatusString());
18380                    }
18381                    return;
18382                }
18383            }
18384
18385            // If any filters need to be verified, then all need to be.
18386            boolean needToVerify = false;
18387            for (PackageParser.Activity a : pkg.activities) {
18388                for (ActivityIntentInfo filter : a.intents) {
18389                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18390                        if (DEBUG_DOMAIN_VERIFICATION) {
18391                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18392                        }
18393                        needToVerify = true;
18394                        break;
18395                    }
18396                }
18397            }
18398
18399            if (needToVerify) {
18400                final int verificationId = mIntentFilterVerificationToken++;
18401                for (PackageParser.Activity a : pkg.activities) {
18402                    for (ActivityIntentInfo filter : a.intents) {
18403                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18404                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18405                                    "Verification needed for IntentFilter:" + filter.toString());
18406                            mIntentFilterVerifier.addOneIntentFilterVerification(
18407                                    verifierUid, userId, verificationId, filter, packageName);
18408                            count++;
18409                        }
18410                    }
18411                }
18412            }
18413        }
18414
18415        if (count > 0) {
18416            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18417                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18418                    +  " for userId:" + userId);
18419            mIntentFilterVerifier.startVerifications(userId);
18420        } else {
18421            if (DEBUG_DOMAIN_VERIFICATION) {
18422                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18423            }
18424        }
18425    }
18426
18427    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18428        final ComponentName cn  = filter.activity.getComponentName();
18429        final String packageName = cn.getPackageName();
18430
18431        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18432                packageName);
18433        if (ivi == null) {
18434            return true;
18435        }
18436        int status = ivi.getStatus();
18437        switch (status) {
18438            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18439            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18440                return true;
18441
18442            default:
18443                // Nothing to do
18444                return false;
18445        }
18446    }
18447
18448    private static boolean isMultiArch(ApplicationInfo info) {
18449        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18450    }
18451
18452    private static boolean isExternal(PackageParser.Package pkg) {
18453        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18454    }
18455
18456    private static boolean isExternal(PackageSetting ps) {
18457        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18458    }
18459
18460    private static boolean isSystemApp(PackageParser.Package pkg) {
18461        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18462    }
18463
18464    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18465        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18466    }
18467
18468    private static boolean isOemApp(PackageParser.Package pkg) {
18469        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
18470    }
18471
18472    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18473        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18474    }
18475
18476    private static boolean isSystemApp(PackageSetting ps) {
18477        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18478    }
18479
18480    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18481        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18482    }
18483
18484    private int packageFlagsToInstallFlags(PackageSetting ps) {
18485        int installFlags = 0;
18486        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18487            // This existing package was an external ASEC install when we have
18488            // the external flag without a UUID
18489            installFlags |= PackageManager.INSTALL_EXTERNAL;
18490        }
18491        if (ps.isForwardLocked()) {
18492            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18493        }
18494        return installFlags;
18495    }
18496
18497    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18498        if (isExternal(pkg)) {
18499            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18500                return StorageManager.UUID_PRIMARY_PHYSICAL;
18501            } else {
18502                return pkg.volumeUuid;
18503            }
18504        } else {
18505            return StorageManager.UUID_PRIVATE_INTERNAL;
18506        }
18507    }
18508
18509    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18510        if (isExternal(pkg)) {
18511            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18512                return mSettings.getExternalVersion();
18513            } else {
18514                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18515            }
18516        } else {
18517            return mSettings.getInternalVersion();
18518        }
18519    }
18520
18521    private void deleteTempPackageFiles() {
18522        final FilenameFilter filter = new FilenameFilter() {
18523            public boolean accept(File dir, String name) {
18524                return name.startsWith("vmdl") && name.endsWith(".tmp");
18525            }
18526        };
18527        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18528            file.delete();
18529        }
18530    }
18531
18532    @Override
18533    public void deletePackageAsUser(String packageName, int versionCode,
18534            IPackageDeleteObserver observer, int userId, int flags) {
18535        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18536                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18537    }
18538
18539    @Override
18540    public void deletePackageVersioned(VersionedPackage versionedPackage,
18541            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18542        final int callingUid = Binder.getCallingUid();
18543        mContext.enforceCallingOrSelfPermission(
18544                android.Manifest.permission.DELETE_PACKAGES, null);
18545        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18546        Preconditions.checkNotNull(versionedPackage);
18547        Preconditions.checkNotNull(observer);
18548        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18549                PackageManager.VERSION_CODE_HIGHEST,
18550                Integer.MAX_VALUE, "versionCode must be >= -1");
18551
18552        final String packageName = versionedPackage.getPackageName();
18553        final int versionCode = versionedPackage.getVersionCode();
18554        final String internalPackageName;
18555        synchronized (mPackages) {
18556            // Normalize package name to handle renamed packages and static libs
18557            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18558                    versionedPackage.getVersionCode());
18559        }
18560
18561        final int uid = Binder.getCallingUid();
18562        if (!isOrphaned(internalPackageName)
18563                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18564            try {
18565                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18566                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18567                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18568                observer.onUserActionRequired(intent);
18569            } catch (RemoteException re) {
18570            }
18571            return;
18572        }
18573        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18574        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18575        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18576            mContext.enforceCallingOrSelfPermission(
18577                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18578                    "deletePackage for user " + userId);
18579        }
18580
18581        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18582            try {
18583                observer.onPackageDeleted(packageName,
18584                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18585            } catch (RemoteException re) {
18586            }
18587            return;
18588        }
18589
18590        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18591            try {
18592                observer.onPackageDeleted(packageName,
18593                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18594            } catch (RemoteException re) {
18595            }
18596            return;
18597        }
18598
18599        if (DEBUG_REMOVE) {
18600            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18601                    + " deleteAllUsers: " + deleteAllUsers + " version="
18602                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18603                    ? "VERSION_CODE_HIGHEST" : versionCode));
18604        }
18605        // Queue up an async operation since the package deletion may take a little while.
18606        mHandler.post(new Runnable() {
18607            public void run() {
18608                mHandler.removeCallbacks(this);
18609                int returnCode;
18610                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18611                boolean doDeletePackage = true;
18612                if (ps != null) {
18613                    final boolean targetIsInstantApp =
18614                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18615                    doDeletePackage = !targetIsInstantApp
18616                            || canViewInstantApps;
18617                }
18618                if (doDeletePackage) {
18619                    if (!deleteAllUsers) {
18620                        returnCode = deletePackageX(internalPackageName, versionCode,
18621                                userId, deleteFlags);
18622                    } else {
18623                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18624                                internalPackageName, users);
18625                        // If nobody is blocking uninstall, proceed with delete for all users
18626                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18627                            returnCode = deletePackageX(internalPackageName, versionCode,
18628                                    userId, deleteFlags);
18629                        } else {
18630                            // Otherwise uninstall individually for users with blockUninstalls=false
18631                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18632                            for (int userId : users) {
18633                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18634                                    returnCode = deletePackageX(internalPackageName, versionCode,
18635                                            userId, userFlags);
18636                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18637                                        Slog.w(TAG, "Package delete failed for user " + userId
18638                                                + ", returnCode " + returnCode);
18639                                    }
18640                                }
18641                            }
18642                            // The app has only been marked uninstalled for certain users.
18643                            // We still need to report that delete was blocked
18644                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18645                        }
18646                    }
18647                } else {
18648                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18649                }
18650                try {
18651                    observer.onPackageDeleted(packageName, returnCode, null);
18652                } catch (RemoteException e) {
18653                    Log.i(TAG, "Observer no longer exists.");
18654                } //end catch
18655            } //end run
18656        });
18657    }
18658
18659    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18660        if (pkg.staticSharedLibName != null) {
18661            return pkg.manifestPackageName;
18662        }
18663        return pkg.packageName;
18664    }
18665
18666    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18667        // Handle renamed packages
18668        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18669        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18670
18671        // Is this a static library?
18672        SparseArray<SharedLibraryEntry> versionedLib =
18673                mStaticLibsByDeclaringPackage.get(packageName);
18674        if (versionedLib == null || versionedLib.size() <= 0) {
18675            return packageName;
18676        }
18677
18678        // Figure out which lib versions the caller can see
18679        SparseIntArray versionsCallerCanSee = null;
18680        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18681        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18682                && callingAppId != Process.ROOT_UID) {
18683            versionsCallerCanSee = new SparseIntArray();
18684            String libName = versionedLib.valueAt(0).info.getName();
18685            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18686            if (uidPackages != null) {
18687                for (String uidPackage : uidPackages) {
18688                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18689                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18690                    if (libIdx >= 0) {
18691                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18692                        versionsCallerCanSee.append(libVersion, libVersion);
18693                    }
18694                }
18695            }
18696        }
18697
18698        // Caller can see nothing - done
18699        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18700            return packageName;
18701        }
18702
18703        // Find the version the caller can see and the app version code
18704        SharedLibraryEntry highestVersion = null;
18705        final int versionCount = versionedLib.size();
18706        for (int i = 0; i < versionCount; i++) {
18707            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18708            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18709                    libEntry.info.getVersion()) < 0) {
18710                continue;
18711            }
18712            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18713            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18714                if (libVersionCode == versionCode) {
18715                    return libEntry.apk;
18716                }
18717            } else if (highestVersion == null) {
18718                highestVersion = libEntry;
18719            } else if (libVersionCode  > highestVersion.info
18720                    .getDeclaringPackage().getVersionCode()) {
18721                highestVersion = libEntry;
18722            }
18723        }
18724
18725        if (highestVersion != null) {
18726            return highestVersion.apk;
18727        }
18728
18729        return packageName;
18730    }
18731
18732    boolean isCallerVerifier(int callingUid) {
18733        final int callingUserId = UserHandle.getUserId(callingUid);
18734        return mRequiredVerifierPackage != null &&
18735                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18736    }
18737
18738    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18739        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18740              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18741            return true;
18742        }
18743        final int callingUserId = UserHandle.getUserId(callingUid);
18744        // If the caller installed the pkgName, then allow it to silently uninstall.
18745        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18746            return true;
18747        }
18748
18749        // Allow package verifier to silently uninstall.
18750        if (mRequiredVerifierPackage != null &&
18751                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18752            return true;
18753        }
18754
18755        // Allow package uninstaller to silently uninstall.
18756        if (mRequiredUninstallerPackage != null &&
18757                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18758            return true;
18759        }
18760
18761        // Allow storage manager to silently uninstall.
18762        if (mStorageManagerPackage != null &&
18763                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18764            return true;
18765        }
18766
18767        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18768        // uninstall for device owner provisioning.
18769        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18770                == PERMISSION_GRANTED) {
18771            return true;
18772        }
18773
18774        return false;
18775    }
18776
18777    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18778        int[] result = EMPTY_INT_ARRAY;
18779        for (int userId : userIds) {
18780            if (getBlockUninstallForUser(packageName, userId)) {
18781                result = ArrayUtils.appendInt(result, userId);
18782            }
18783        }
18784        return result;
18785    }
18786
18787    @Override
18788    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18789        final int callingUid = Binder.getCallingUid();
18790        if (getInstantAppPackageName(callingUid) != null
18791                && !isCallerSameApp(packageName, callingUid)) {
18792            return false;
18793        }
18794        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18795    }
18796
18797    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18798        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18799                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18800        try {
18801            if (dpm != null) {
18802                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18803                        /* callingUserOnly =*/ false);
18804                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18805                        : deviceOwnerComponentName.getPackageName();
18806                // Does the package contains the device owner?
18807                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18808                // this check is probably not needed, since DO should be registered as a device
18809                // admin on some user too. (Original bug for this: b/17657954)
18810                if (packageName.equals(deviceOwnerPackageName)) {
18811                    return true;
18812                }
18813                // Does it contain a device admin for any user?
18814                int[] users;
18815                if (userId == UserHandle.USER_ALL) {
18816                    users = sUserManager.getUserIds();
18817                } else {
18818                    users = new int[]{userId};
18819                }
18820                for (int i = 0; i < users.length; ++i) {
18821                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18822                        return true;
18823                    }
18824                }
18825            }
18826        } catch (RemoteException e) {
18827        }
18828        return false;
18829    }
18830
18831    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18832        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18833    }
18834
18835    /**
18836     *  This method is an internal method that could be get invoked either
18837     *  to delete an installed package or to clean up a failed installation.
18838     *  After deleting an installed package, a broadcast is sent to notify any
18839     *  listeners that the package has been removed. For cleaning up a failed
18840     *  installation, the broadcast is not necessary since the package's
18841     *  installation wouldn't have sent the initial broadcast either
18842     *  The key steps in deleting a package are
18843     *  deleting the package information in internal structures like mPackages,
18844     *  deleting the packages base directories through installd
18845     *  updating mSettings to reflect current status
18846     *  persisting settings for later use
18847     *  sending a broadcast if necessary
18848     */
18849    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18850        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18851        final boolean res;
18852
18853        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18854                ? UserHandle.USER_ALL : userId;
18855
18856        if (isPackageDeviceAdmin(packageName, removeUser)) {
18857            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18858            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18859        }
18860
18861        PackageSetting uninstalledPs = null;
18862        PackageParser.Package pkg = null;
18863
18864        // for the uninstall-updates case and restricted profiles, remember the per-
18865        // user handle installed state
18866        int[] allUsers;
18867        synchronized (mPackages) {
18868            uninstalledPs = mSettings.mPackages.get(packageName);
18869            if (uninstalledPs == null) {
18870                Slog.w(TAG, "Not removing non-existent package " + packageName);
18871                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18872            }
18873
18874            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18875                    && uninstalledPs.versionCode != versionCode) {
18876                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18877                        + uninstalledPs.versionCode + " != " + versionCode);
18878                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18879            }
18880
18881            // Static shared libs can be declared by any package, so let us not
18882            // allow removing a package if it provides a lib others depend on.
18883            pkg = mPackages.get(packageName);
18884
18885            allUsers = sUserManager.getUserIds();
18886
18887            if (pkg != null && pkg.staticSharedLibName != null) {
18888                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18889                        pkg.staticSharedLibVersion);
18890                if (libEntry != null) {
18891                    for (int currUserId : allUsers) {
18892                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18893                            continue;
18894                        }
18895                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18896                                libEntry.info, 0, currUserId);
18897                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18898                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18899                                    + " hosting lib " + libEntry.info.getName() + " version "
18900                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18901                                    + " for user " + currUserId);
18902                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18903                        }
18904                    }
18905                }
18906            }
18907
18908            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18909        }
18910
18911        final int freezeUser;
18912        if (isUpdatedSystemApp(uninstalledPs)
18913                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18914            // We're downgrading a system app, which will apply to all users, so
18915            // freeze them all during the downgrade
18916            freezeUser = UserHandle.USER_ALL;
18917        } else {
18918            freezeUser = removeUser;
18919        }
18920
18921        synchronized (mInstallLock) {
18922            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18923            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18924                    deleteFlags, "deletePackageX")) {
18925                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18926                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18927            }
18928            synchronized (mPackages) {
18929                if (res) {
18930                    if (pkg != null) {
18931                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18932                    }
18933                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18934                    updateInstantAppInstallerLocked(packageName);
18935                }
18936            }
18937        }
18938
18939        if (res) {
18940            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18941            info.sendPackageRemovedBroadcasts(killApp);
18942            info.sendSystemPackageUpdatedBroadcasts();
18943            info.sendSystemPackageAppearedBroadcasts();
18944        }
18945        // Force a gc here.
18946        Runtime.getRuntime().gc();
18947        // Delete the resources here after sending the broadcast to let
18948        // other processes clean up before deleting resources.
18949        if (info.args != null) {
18950            synchronized (mInstallLock) {
18951                info.args.doPostDeleteLI(true);
18952            }
18953        }
18954
18955        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18956    }
18957
18958    static class PackageRemovedInfo {
18959        final PackageSender packageSender;
18960        String removedPackage;
18961        String installerPackageName;
18962        int uid = -1;
18963        int removedAppId = -1;
18964        int[] origUsers;
18965        int[] removedUsers = null;
18966        int[] broadcastUsers = null;
18967        SparseArray<Integer> installReasons;
18968        boolean isRemovedPackageSystemUpdate = false;
18969        boolean isUpdate;
18970        boolean dataRemoved;
18971        boolean removedForAllUsers;
18972        boolean isStaticSharedLib;
18973        // Clean up resources deleted packages.
18974        InstallArgs args = null;
18975        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18976        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18977
18978        PackageRemovedInfo(PackageSender packageSender) {
18979            this.packageSender = packageSender;
18980        }
18981
18982        void sendPackageRemovedBroadcasts(boolean killApp) {
18983            sendPackageRemovedBroadcastInternal(killApp);
18984            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18985            for (int i = 0; i < childCount; i++) {
18986                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18987                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18988            }
18989        }
18990
18991        void sendSystemPackageUpdatedBroadcasts() {
18992            if (isRemovedPackageSystemUpdate) {
18993                sendSystemPackageUpdatedBroadcastsInternal();
18994                final int childCount = (removedChildPackages != null)
18995                        ? removedChildPackages.size() : 0;
18996                for (int i = 0; i < childCount; i++) {
18997                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18998                    if (childInfo.isRemovedPackageSystemUpdate) {
18999                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19000                    }
19001                }
19002            }
19003        }
19004
19005        void sendSystemPackageAppearedBroadcasts() {
19006            final int packageCount = (appearedChildPackages != null)
19007                    ? appearedChildPackages.size() : 0;
19008            for (int i = 0; i < packageCount; i++) {
19009                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19010                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19011                    true /*sendBootCompleted*/, false /*startReceiver*/,
19012                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19013            }
19014        }
19015
19016        private void sendSystemPackageUpdatedBroadcastsInternal() {
19017            Bundle extras = new Bundle(2);
19018            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19019            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19020            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19021                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19022            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19023                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19024            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19025                null, null, 0, removedPackage, null, null);
19026            if (installerPackageName != null) {
19027                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19028                        removedPackage, extras, 0 /*flags*/,
19029                        installerPackageName, null, null);
19030                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19031                        removedPackage, extras, 0 /*flags*/,
19032                        installerPackageName, null, null);
19033            }
19034        }
19035
19036        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19037            // Don't send static shared library removal broadcasts as these
19038            // libs are visible only the the apps that depend on them an one
19039            // cannot remove the library if it has a dependency.
19040            if (isStaticSharedLib) {
19041                return;
19042            }
19043            Bundle extras = new Bundle(2);
19044            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19045            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19046            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19047            if (isUpdate || isRemovedPackageSystemUpdate) {
19048                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19049            }
19050            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19051            if (removedPackage != null) {
19052                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19053                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19054                if (installerPackageName != null) {
19055                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19056                            removedPackage, extras, 0 /*flags*/,
19057                            installerPackageName, null, broadcastUsers);
19058                }
19059                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19060                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19061                        removedPackage, extras,
19062                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19063                        null, null, broadcastUsers);
19064                }
19065            }
19066            if (removedAppId >= 0) {
19067                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19068                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19069                    null, null, broadcastUsers);
19070            }
19071        }
19072
19073        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19074            removedUsers = userIds;
19075            if (removedUsers == null) {
19076                broadcastUsers = null;
19077                return;
19078            }
19079
19080            broadcastUsers = EMPTY_INT_ARRAY;
19081            for (int i = userIds.length - 1; i >= 0; --i) {
19082                final int userId = userIds[i];
19083                if (deletedPackageSetting.getInstantApp(userId)) {
19084                    continue;
19085                }
19086                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19087            }
19088        }
19089    }
19090
19091    /*
19092     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19093     * flag is not set, the data directory is removed as well.
19094     * make sure this flag is set for partially installed apps. If not its meaningless to
19095     * delete a partially installed application.
19096     */
19097    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19098            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19099        String packageName = ps.name;
19100        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19101        // Retrieve object to delete permissions for shared user later on
19102        final PackageParser.Package deletedPkg;
19103        final PackageSetting deletedPs;
19104        // reader
19105        synchronized (mPackages) {
19106            deletedPkg = mPackages.get(packageName);
19107            deletedPs = mSettings.mPackages.get(packageName);
19108            if (outInfo != null) {
19109                outInfo.removedPackage = packageName;
19110                outInfo.installerPackageName = ps.installerPackageName;
19111                outInfo.isStaticSharedLib = deletedPkg != null
19112                        && deletedPkg.staticSharedLibName != null;
19113                outInfo.populateUsers(deletedPs == null ? null
19114                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19115            }
19116        }
19117
19118        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19119
19120        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19121            final PackageParser.Package resolvedPkg;
19122            if (deletedPkg != null) {
19123                resolvedPkg = deletedPkg;
19124            } else {
19125                // We don't have a parsed package when it lives on an ejected
19126                // adopted storage device, so fake something together
19127                resolvedPkg = new PackageParser.Package(ps.name);
19128                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19129            }
19130            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19131                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19132            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19133            if (outInfo != null) {
19134                outInfo.dataRemoved = true;
19135            }
19136            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19137        }
19138
19139        int removedAppId = -1;
19140
19141        // writer
19142        synchronized (mPackages) {
19143            boolean installedStateChanged = false;
19144            if (deletedPs != null) {
19145                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19146                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19147                    clearDefaultBrowserIfNeeded(packageName);
19148                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19149                    removedAppId = mSettings.removePackageLPw(packageName);
19150                    if (outInfo != null) {
19151                        outInfo.removedAppId = removedAppId;
19152                    }
19153                    updatePermissionsLPw(deletedPs.name, null, 0);
19154                    if (deletedPs.sharedUser != null) {
19155                        // Remove permissions associated with package. Since runtime
19156                        // permissions are per user we have to kill the removed package
19157                        // or packages running under the shared user of the removed
19158                        // package if revoking the permissions requested only by the removed
19159                        // package is successful and this causes a change in gids.
19160                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19161                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19162                                    userId);
19163                            if (userIdToKill == UserHandle.USER_ALL
19164                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19165                                // If gids changed for this user, kill all affected packages.
19166                                mHandler.post(new Runnable() {
19167                                    @Override
19168                                    public void run() {
19169                                        // This has to happen with no lock held.
19170                                        killApplication(deletedPs.name, deletedPs.appId,
19171                                                KILL_APP_REASON_GIDS_CHANGED);
19172                                    }
19173                                });
19174                                break;
19175                            }
19176                        }
19177                    }
19178                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19179                }
19180                // make sure to preserve per-user disabled state if this removal was just
19181                // a downgrade of a system app to the factory package
19182                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19183                    if (DEBUG_REMOVE) {
19184                        Slog.d(TAG, "Propagating install state across downgrade");
19185                    }
19186                    for (int userId : allUserHandles) {
19187                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19188                        if (DEBUG_REMOVE) {
19189                            Slog.d(TAG, "    user " + userId + " => " + installed);
19190                        }
19191                        if (installed != ps.getInstalled(userId)) {
19192                            installedStateChanged = true;
19193                        }
19194                        ps.setInstalled(installed, userId);
19195                    }
19196                }
19197            }
19198            // can downgrade to reader
19199            if (writeSettings) {
19200                // Save settings now
19201                mSettings.writeLPr();
19202            }
19203            if (installedStateChanged) {
19204                mSettings.writeKernelMappingLPr(ps);
19205            }
19206        }
19207        if (removedAppId != -1) {
19208            // A user ID was deleted here. Go through all users and remove it
19209            // from KeyStore.
19210            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19211        }
19212    }
19213
19214    static boolean locationIsPrivileged(File path) {
19215        try {
19216            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19217                    .getCanonicalPath();
19218            return path.getCanonicalPath().startsWith(privilegedAppDir);
19219        } catch (IOException e) {
19220            Slog.e(TAG, "Unable to access code path " + path);
19221        }
19222        return false;
19223    }
19224
19225    static boolean locationIsOem(File path) {
19226        try {
19227            return path.getCanonicalPath().startsWith(
19228                    Environment.getOemDirectory().getCanonicalPath());
19229        } catch (IOException e) {
19230            Slog.e(TAG, "Unable to access code path " + path);
19231        }
19232        return false;
19233    }
19234
19235    /*
19236     * Tries to delete system package.
19237     */
19238    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19239            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19240            boolean writeSettings) {
19241        if (deletedPs.parentPackageName != null) {
19242            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19243            return false;
19244        }
19245
19246        final boolean applyUserRestrictions
19247                = (allUserHandles != null) && (outInfo.origUsers != null);
19248        final PackageSetting disabledPs;
19249        // Confirm if the system package has been updated
19250        // An updated system app can be deleted. This will also have to restore
19251        // the system pkg from system partition
19252        // reader
19253        synchronized (mPackages) {
19254            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19255        }
19256
19257        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19258                + " disabledPs=" + disabledPs);
19259
19260        if (disabledPs == null) {
19261            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19262            return false;
19263        } else if (DEBUG_REMOVE) {
19264            Slog.d(TAG, "Deleting system pkg from data partition");
19265        }
19266
19267        if (DEBUG_REMOVE) {
19268            if (applyUserRestrictions) {
19269                Slog.d(TAG, "Remembering install states:");
19270                for (int userId : allUserHandles) {
19271                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19272                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19273                }
19274            }
19275        }
19276
19277        // Delete the updated package
19278        outInfo.isRemovedPackageSystemUpdate = true;
19279        if (outInfo.removedChildPackages != null) {
19280            final int childCount = (deletedPs.childPackageNames != null)
19281                    ? deletedPs.childPackageNames.size() : 0;
19282            for (int i = 0; i < childCount; i++) {
19283                String childPackageName = deletedPs.childPackageNames.get(i);
19284                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19285                        .contains(childPackageName)) {
19286                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19287                            childPackageName);
19288                    if (childInfo != null) {
19289                        childInfo.isRemovedPackageSystemUpdate = true;
19290                    }
19291                }
19292            }
19293        }
19294
19295        if (disabledPs.versionCode < deletedPs.versionCode) {
19296            // Delete data for downgrades
19297            flags &= ~PackageManager.DELETE_KEEP_DATA;
19298        } else {
19299            // Preserve data by setting flag
19300            flags |= PackageManager.DELETE_KEEP_DATA;
19301        }
19302
19303        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19304                outInfo, writeSettings, disabledPs.pkg);
19305        if (!ret) {
19306            return false;
19307        }
19308
19309        // writer
19310        synchronized (mPackages) {
19311            // NOTE: The system package always needs to be enabled; even if it's for
19312            // a compressed stub. If we don't, installing the system package fails
19313            // during scan [scanning checks the disabled packages]. We will reverse
19314            // this later, after we've "installed" the stub.
19315            // Reinstate the old system package
19316            enableSystemPackageLPw(disabledPs.pkg);
19317            // Remove any native libraries from the upgraded package.
19318            removeNativeBinariesLI(deletedPs);
19319        }
19320
19321        // Install the system package
19322        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19323        try {
19324            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19325                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19326        } catch (PackageManagerException e) {
19327            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19328                    + e.getMessage());
19329            return false;
19330        } finally {
19331            if (disabledPs.pkg.isStub) {
19332                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19333            }
19334        }
19335        return true;
19336    }
19337
19338    /**
19339     * Installs a package that's already on the system partition.
19340     */
19341    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19342            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19343            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19344                    throws PackageManagerException {
19345        int parseFlags = mDefParseFlags
19346                | PackageParser.PARSE_MUST_BE_APK
19347                | PackageParser.PARSE_IS_SYSTEM
19348                | PackageParser.PARSE_IS_SYSTEM_DIR;
19349        if (isPrivileged || locationIsPrivileged(codePath)) {
19350            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19351        }
19352        if (locationIsOem(codePath)) {
19353            parseFlags |= PackageParser.PARSE_IS_OEM;
19354        }
19355
19356        final PackageParser.Package newPkg =
19357                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19358
19359        try {
19360            // update shared libraries for the newly re-installed system package
19361            updateSharedLibrariesLPr(newPkg, null);
19362        } catch (PackageManagerException e) {
19363            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19364        }
19365
19366        prepareAppDataAfterInstallLIF(newPkg);
19367
19368        // writer
19369        synchronized (mPackages) {
19370            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19371
19372            // Propagate the permissions state as we do not want to drop on the floor
19373            // runtime permissions. The update permissions method below will take
19374            // care of removing obsolete permissions and grant install permissions.
19375            if (origPermissionState != null) {
19376                ps.getPermissionsState().copyFrom(origPermissionState);
19377            }
19378            updatePermissionsLPw(newPkg.packageName, newPkg,
19379                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19380
19381            final boolean applyUserRestrictions
19382                    = (allUserHandles != null) && (origUserHandles != null);
19383            if (applyUserRestrictions) {
19384                boolean installedStateChanged = false;
19385                if (DEBUG_REMOVE) {
19386                    Slog.d(TAG, "Propagating install state across reinstall");
19387                }
19388                for (int userId : allUserHandles) {
19389                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19390                    if (DEBUG_REMOVE) {
19391                        Slog.d(TAG, "    user " + userId + " => " + installed);
19392                    }
19393                    if (installed != ps.getInstalled(userId)) {
19394                        installedStateChanged = true;
19395                    }
19396                    ps.setInstalled(installed, userId);
19397
19398                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19399                }
19400                // Regardless of writeSettings we need to ensure that this restriction
19401                // state propagation is persisted
19402                mSettings.writeAllUsersPackageRestrictionsLPr();
19403                if (installedStateChanged) {
19404                    mSettings.writeKernelMappingLPr(ps);
19405                }
19406            }
19407            // can downgrade to reader here
19408            if (writeSettings) {
19409                mSettings.writeLPr();
19410            }
19411        }
19412        return newPkg;
19413    }
19414
19415    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19416            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19417            PackageRemovedInfo outInfo, boolean writeSettings,
19418            PackageParser.Package replacingPackage) {
19419        synchronized (mPackages) {
19420            if (outInfo != null) {
19421                outInfo.uid = ps.appId;
19422            }
19423
19424            if (outInfo != null && outInfo.removedChildPackages != null) {
19425                final int childCount = (ps.childPackageNames != null)
19426                        ? ps.childPackageNames.size() : 0;
19427                for (int i = 0; i < childCount; i++) {
19428                    String childPackageName = ps.childPackageNames.get(i);
19429                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19430                    if (childPs == null) {
19431                        return false;
19432                    }
19433                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19434                            childPackageName);
19435                    if (childInfo != null) {
19436                        childInfo.uid = childPs.appId;
19437                    }
19438                }
19439            }
19440        }
19441
19442        // Delete package data from internal structures and also remove data if flag is set
19443        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19444
19445        // Delete the child packages data
19446        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19447        for (int i = 0; i < childCount; i++) {
19448            PackageSetting childPs;
19449            synchronized (mPackages) {
19450                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19451            }
19452            if (childPs != null) {
19453                PackageRemovedInfo childOutInfo = (outInfo != null
19454                        && outInfo.removedChildPackages != null)
19455                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19456                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19457                        && (replacingPackage != null
19458                        && !replacingPackage.hasChildPackage(childPs.name))
19459                        ? flags & ~DELETE_KEEP_DATA : flags;
19460                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19461                        deleteFlags, writeSettings);
19462            }
19463        }
19464
19465        // Delete application code and resources only for parent packages
19466        if (ps.parentPackageName == null) {
19467            if (deleteCodeAndResources && (outInfo != null)) {
19468                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19469                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19470                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19471            }
19472        }
19473
19474        return true;
19475    }
19476
19477    @Override
19478    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19479            int userId) {
19480        mContext.enforceCallingOrSelfPermission(
19481                android.Manifest.permission.DELETE_PACKAGES, null);
19482        synchronized (mPackages) {
19483            // Cannot block uninstall of static shared libs as they are
19484            // considered a part of the using app (emulating static linking).
19485            // Also static libs are installed always on internal storage.
19486            PackageParser.Package pkg = mPackages.get(packageName);
19487            if (pkg != null && pkg.staticSharedLibName != null) {
19488                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19489                        + " providing static shared library: " + pkg.staticSharedLibName);
19490                return false;
19491            }
19492            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19493            mSettings.writePackageRestrictionsLPr(userId);
19494        }
19495        return true;
19496    }
19497
19498    @Override
19499    public boolean getBlockUninstallForUser(String packageName, int userId) {
19500        synchronized (mPackages) {
19501            final PackageSetting ps = mSettings.mPackages.get(packageName);
19502            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19503                return false;
19504            }
19505            return mSettings.getBlockUninstallLPr(userId, packageName);
19506        }
19507    }
19508
19509    @Override
19510    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19511        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19512        synchronized (mPackages) {
19513            PackageSetting ps = mSettings.mPackages.get(packageName);
19514            if (ps == null) {
19515                Log.w(TAG, "Package doesn't exist: " + packageName);
19516                return false;
19517            }
19518            if (systemUserApp) {
19519                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19520            } else {
19521                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19522            }
19523            mSettings.writeLPr();
19524        }
19525        return true;
19526    }
19527
19528    /*
19529     * This method handles package deletion in general
19530     */
19531    private boolean deletePackageLIF(String packageName, UserHandle user,
19532            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19533            PackageRemovedInfo outInfo, boolean writeSettings,
19534            PackageParser.Package replacingPackage) {
19535        if (packageName == null) {
19536            Slog.w(TAG, "Attempt to delete null packageName.");
19537            return false;
19538        }
19539
19540        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19541
19542        PackageSetting ps;
19543        synchronized (mPackages) {
19544            ps = mSettings.mPackages.get(packageName);
19545            if (ps == null) {
19546                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19547                return false;
19548            }
19549
19550            if (ps.parentPackageName != null && (!isSystemApp(ps)
19551                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19552                if (DEBUG_REMOVE) {
19553                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19554                            + ((user == null) ? UserHandle.USER_ALL : user));
19555                }
19556                final int removedUserId = (user != null) ? user.getIdentifier()
19557                        : UserHandle.USER_ALL;
19558                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19559                    return false;
19560                }
19561                markPackageUninstalledForUserLPw(ps, user);
19562                scheduleWritePackageRestrictionsLocked(user);
19563                return true;
19564            }
19565        }
19566
19567        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19568                && user.getIdentifier() != UserHandle.USER_ALL)) {
19569            // The caller is asking that the package only be deleted for a single
19570            // user.  To do this, we just mark its uninstalled state and delete
19571            // its data. If this is a system app, we only allow this to happen if
19572            // they have set the special DELETE_SYSTEM_APP which requests different
19573            // semantics than normal for uninstalling system apps.
19574            markPackageUninstalledForUserLPw(ps, user);
19575
19576            if (!isSystemApp(ps)) {
19577                // Do not uninstall the APK if an app should be cached
19578                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19579                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19580                    // Other user still have this package installed, so all
19581                    // we need to do is clear this user's data and save that
19582                    // it is uninstalled.
19583                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19584                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19585                        return false;
19586                    }
19587                    scheduleWritePackageRestrictionsLocked(user);
19588                    return true;
19589                } else {
19590                    // We need to set it back to 'installed' so the uninstall
19591                    // broadcasts will be sent correctly.
19592                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19593                    ps.setInstalled(true, user.getIdentifier());
19594                    mSettings.writeKernelMappingLPr(ps);
19595                }
19596            } else {
19597                // This is a system app, so we assume that the
19598                // other users still have this package installed, so all
19599                // we need to do is clear this user's data and save that
19600                // it is uninstalled.
19601                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19602                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19603                    return false;
19604                }
19605                scheduleWritePackageRestrictionsLocked(user);
19606                return true;
19607            }
19608        }
19609
19610        // If we are deleting a composite package for all users, keep track
19611        // of result for each child.
19612        if (ps.childPackageNames != null && outInfo != null) {
19613            synchronized (mPackages) {
19614                final int childCount = ps.childPackageNames.size();
19615                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19616                for (int i = 0; i < childCount; i++) {
19617                    String childPackageName = ps.childPackageNames.get(i);
19618                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19619                    childInfo.removedPackage = childPackageName;
19620                    childInfo.installerPackageName = ps.installerPackageName;
19621                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19622                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19623                    if (childPs != null) {
19624                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19625                    }
19626                }
19627            }
19628        }
19629
19630        boolean ret = false;
19631        if (isSystemApp(ps)) {
19632            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19633            // When an updated system application is deleted we delete the existing resources
19634            // as well and fall back to existing code in system partition
19635            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19636        } else {
19637            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19638            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19639                    outInfo, writeSettings, replacingPackage);
19640        }
19641
19642        // Take a note whether we deleted the package for all users
19643        if (outInfo != null) {
19644            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19645            if (outInfo.removedChildPackages != null) {
19646                synchronized (mPackages) {
19647                    final int childCount = outInfo.removedChildPackages.size();
19648                    for (int i = 0; i < childCount; i++) {
19649                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19650                        if (childInfo != null) {
19651                            childInfo.removedForAllUsers = mPackages.get(
19652                                    childInfo.removedPackage) == null;
19653                        }
19654                    }
19655                }
19656            }
19657            // If we uninstalled an update to a system app there may be some
19658            // child packages that appeared as they are declared in the system
19659            // app but were not declared in the update.
19660            if (isSystemApp(ps)) {
19661                synchronized (mPackages) {
19662                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19663                    final int childCount = (updatedPs.childPackageNames != null)
19664                            ? updatedPs.childPackageNames.size() : 0;
19665                    for (int i = 0; i < childCount; i++) {
19666                        String childPackageName = updatedPs.childPackageNames.get(i);
19667                        if (outInfo.removedChildPackages == null
19668                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19669                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19670                            if (childPs == null) {
19671                                continue;
19672                            }
19673                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19674                            installRes.name = childPackageName;
19675                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19676                            installRes.pkg = mPackages.get(childPackageName);
19677                            installRes.uid = childPs.pkg.applicationInfo.uid;
19678                            if (outInfo.appearedChildPackages == null) {
19679                                outInfo.appearedChildPackages = new ArrayMap<>();
19680                            }
19681                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19682                        }
19683                    }
19684                }
19685            }
19686        }
19687
19688        return ret;
19689    }
19690
19691    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19692        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19693                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19694        for (int nextUserId : userIds) {
19695            if (DEBUG_REMOVE) {
19696                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19697            }
19698            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19699                    false /*installed*/,
19700                    true /*stopped*/,
19701                    true /*notLaunched*/,
19702                    false /*hidden*/,
19703                    false /*suspended*/,
19704                    false /*instantApp*/,
19705                    false /*virtualPreload*/,
19706                    null /*lastDisableAppCaller*/,
19707                    null /*enabledComponents*/,
19708                    null /*disabledComponents*/,
19709                    ps.readUserState(nextUserId).domainVerificationStatus,
19710                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19711        }
19712        mSettings.writeKernelMappingLPr(ps);
19713    }
19714
19715    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19716            PackageRemovedInfo outInfo) {
19717        final PackageParser.Package pkg;
19718        synchronized (mPackages) {
19719            pkg = mPackages.get(ps.name);
19720        }
19721
19722        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19723                : new int[] {userId};
19724        for (int nextUserId : userIds) {
19725            if (DEBUG_REMOVE) {
19726                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19727                        + nextUserId);
19728            }
19729
19730            destroyAppDataLIF(pkg, userId,
19731                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19732            destroyAppProfilesLIF(pkg, userId);
19733            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19734            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19735            schedulePackageCleaning(ps.name, nextUserId, false);
19736            synchronized (mPackages) {
19737                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19738                    scheduleWritePackageRestrictionsLocked(nextUserId);
19739                }
19740                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19741            }
19742        }
19743
19744        if (outInfo != null) {
19745            outInfo.removedPackage = ps.name;
19746            outInfo.installerPackageName = ps.installerPackageName;
19747            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19748            outInfo.removedAppId = ps.appId;
19749            outInfo.removedUsers = userIds;
19750            outInfo.broadcastUsers = userIds;
19751        }
19752
19753        return true;
19754    }
19755
19756    private final class ClearStorageConnection implements ServiceConnection {
19757        IMediaContainerService mContainerService;
19758
19759        @Override
19760        public void onServiceConnected(ComponentName name, IBinder service) {
19761            synchronized (this) {
19762                mContainerService = IMediaContainerService.Stub
19763                        .asInterface(Binder.allowBlocking(service));
19764                notifyAll();
19765            }
19766        }
19767
19768        @Override
19769        public void onServiceDisconnected(ComponentName name) {
19770        }
19771    }
19772
19773    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19774        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19775
19776        final boolean mounted;
19777        if (Environment.isExternalStorageEmulated()) {
19778            mounted = true;
19779        } else {
19780            final String status = Environment.getExternalStorageState();
19781
19782            mounted = status.equals(Environment.MEDIA_MOUNTED)
19783                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19784        }
19785
19786        if (!mounted) {
19787            return;
19788        }
19789
19790        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19791        int[] users;
19792        if (userId == UserHandle.USER_ALL) {
19793            users = sUserManager.getUserIds();
19794        } else {
19795            users = new int[] { userId };
19796        }
19797        final ClearStorageConnection conn = new ClearStorageConnection();
19798        if (mContext.bindServiceAsUser(
19799                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19800            try {
19801                for (int curUser : users) {
19802                    long timeout = SystemClock.uptimeMillis() + 5000;
19803                    synchronized (conn) {
19804                        long now;
19805                        while (conn.mContainerService == null &&
19806                                (now = SystemClock.uptimeMillis()) < timeout) {
19807                            try {
19808                                conn.wait(timeout - now);
19809                            } catch (InterruptedException e) {
19810                            }
19811                        }
19812                    }
19813                    if (conn.mContainerService == null) {
19814                        return;
19815                    }
19816
19817                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19818                    clearDirectory(conn.mContainerService,
19819                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19820                    if (allData) {
19821                        clearDirectory(conn.mContainerService,
19822                                userEnv.buildExternalStorageAppDataDirs(packageName));
19823                        clearDirectory(conn.mContainerService,
19824                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19825                    }
19826                }
19827            } finally {
19828                mContext.unbindService(conn);
19829            }
19830        }
19831    }
19832
19833    @Override
19834    public void clearApplicationProfileData(String packageName) {
19835        enforceSystemOrRoot("Only the system can clear all profile data");
19836
19837        final PackageParser.Package pkg;
19838        synchronized (mPackages) {
19839            pkg = mPackages.get(packageName);
19840        }
19841
19842        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19843            synchronized (mInstallLock) {
19844                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19845            }
19846        }
19847    }
19848
19849    @Override
19850    public void clearApplicationUserData(final String packageName,
19851            final IPackageDataObserver observer, final int userId) {
19852        mContext.enforceCallingOrSelfPermission(
19853                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19854
19855        final int callingUid = Binder.getCallingUid();
19856        enforceCrossUserPermission(callingUid, userId,
19857                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19858
19859        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19860        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19861        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19862            throw new SecurityException("Cannot clear data for a protected package: "
19863                    + packageName);
19864        }
19865        // Queue up an async operation since the package deletion may take a little while.
19866        mHandler.post(new Runnable() {
19867            public void run() {
19868                mHandler.removeCallbacks(this);
19869                final boolean succeeded;
19870                if (!filterApp) {
19871                    try (PackageFreezer freezer = freezePackage(packageName,
19872                            "clearApplicationUserData")) {
19873                        synchronized (mInstallLock) {
19874                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19875                        }
19876                        clearExternalStorageDataSync(packageName, userId, true);
19877                        synchronized (mPackages) {
19878                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19879                                    packageName, userId);
19880                        }
19881                    }
19882                    if (succeeded) {
19883                        // invoke DeviceStorageMonitor's update method to clear any notifications
19884                        DeviceStorageMonitorInternal dsm = LocalServices
19885                                .getService(DeviceStorageMonitorInternal.class);
19886                        if (dsm != null) {
19887                            dsm.checkMemory();
19888                        }
19889                    }
19890                } else {
19891                    succeeded = false;
19892                }
19893                if (observer != null) {
19894                    try {
19895                        observer.onRemoveCompleted(packageName, succeeded);
19896                    } catch (RemoteException e) {
19897                        Log.i(TAG, "Observer no longer exists.");
19898                    }
19899                } //end if observer
19900            } //end run
19901        });
19902    }
19903
19904    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19905        if (packageName == null) {
19906            Slog.w(TAG, "Attempt to delete null packageName.");
19907            return false;
19908        }
19909
19910        // Try finding details about the requested package
19911        PackageParser.Package pkg;
19912        synchronized (mPackages) {
19913            pkg = mPackages.get(packageName);
19914            if (pkg == null) {
19915                final PackageSetting ps = mSettings.mPackages.get(packageName);
19916                if (ps != null) {
19917                    pkg = ps.pkg;
19918                }
19919            }
19920
19921            if (pkg == null) {
19922                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19923                return false;
19924            }
19925
19926            PackageSetting ps = (PackageSetting) pkg.mExtras;
19927            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19928        }
19929
19930        clearAppDataLIF(pkg, userId,
19931                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19932
19933        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19934        removeKeystoreDataIfNeeded(userId, appId);
19935
19936        UserManagerInternal umInternal = getUserManagerInternal();
19937        final int flags;
19938        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19939            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19940        } else if (umInternal.isUserRunning(userId)) {
19941            flags = StorageManager.FLAG_STORAGE_DE;
19942        } else {
19943            flags = 0;
19944        }
19945        prepareAppDataContentsLIF(pkg, userId, flags);
19946
19947        return true;
19948    }
19949
19950    /**
19951     * Reverts user permission state changes (permissions and flags) in
19952     * all packages for a given user.
19953     *
19954     * @param userId The device user for which to do a reset.
19955     */
19956    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19957        final int packageCount = mPackages.size();
19958        for (int i = 0; i < packageCount; i++) {
19959            PackageParser.Package pkg = mPackages.valueAt(i);
19960            PackageSetting ps = (PackageSetting) pkg.mExtras;
19961            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19962        }
19963    }
19964
19965    private void resetNetworkPolicies(int userId) {
19966        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19967    }
19968
19969    /**
19970     * Reverts user permission state changes (permissions and flags).
19971     *
19972     * @param ps The package for which to reset.
19973     * @param userId The device user for which to do a reset.
19974     */
19975    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19976            final PackageSetting ps, final int userId) {
19977        if (ps.pkg == null) {
19978            return;
19979        }
19980
19981        // These are flags that can change base on user actions.
19982        final int userSettableMask = FLAG_PERMISSION_USER_SET
19983                | FLAG_PERMISSION_USER_FIXED
19984                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19985                | FLAG_PERMISSION_REVIEW_REQUIRED;
19986
19987        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19988                | FLAG_PERMISSION_POLICY_FIXED;
19989
19990        boolean writeInstallPermissions = false;
19991        boolean writeRuntimePermissions = false;
19992
19993        final int permissionCount = ps.pkg.requestedPermissions.size();
19994        for (int i = 0; i < permissionCount; i++) {
19995            final String permissionName = ps.pkg.requestedPermissions.get(i);
19996            final BasePermission bp = mSettings.mPermissions.get(permissionName);
19997            if (bp == null) {
19998                continue;
19999            }
20000
20001            // If shared user we just reset the state to which only this app contributed.
20002            if (ps.sharedUser != null) {
20003                boolean used = false;
20004                final int packageCount = ps.sharedUser.packages.size();
20005                for (int j = 0; j < packageCount; j++) {
20006                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20007                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20008                            && pkg.pkg.requestedPermissions.contains(permissionName)) {
20009                        used = true;
20010                        break;
20011                    }
20012                }
20013                if (used) {
20014                    continue;
20015                }
20016            }
20017
20018            final PermissionsState permissionsState = ps.getPermissionsState();
20019
20020            final int oldFlags = permissionsState.getPermissionFlags(permissionName, userId);
20021
20022            // Always clear the user settable flags.
20023            final boolean hasInstallState =
20024                    permissionsState.getInstallPermissionState(permissionName) != null;
20025            // If permission review is enabled and this is a legacy app, mark the
20026            // permission as requiring a review as this is the initial state.
20027            int flags = 0;
20028            if (mPermissionReviewRequired
20029                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20030                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20031            }
20032            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20033                if (hasInstallState) {
20034                    writeInstallPermissions = true;
20035                } else {
20036                    writeRuntimePermissions = true;
20037                }
20038            }
20039
20040            // Below is only runtime permission handling.
20041            if (!bp.isRuntime()) {
20042                continue;
20043            }
20044
20045            // Never clobber system or policy.
20046            if ((oldFlags & policyOrSystemFlags) != 0) {
20047                continue;
20048            }
20049
20050            // If this permission was granted by default, make sure it is.
20051            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20052                if (permissionsState.grantRuntimePermission(bp, userId)
20053                        != PERMISSION_OPERATION_FAILURE) {
20054                    writeRuntimePermissions = true;
20055                }
20056            // If permission review is enabled the permissions for a legacy apps
20057            // are represented as constantly granted runtime ones, so don't revoke.
20058            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20059                // Otherwise, reset the permission.
20060                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20061                switch (revokeResult) {
20062                    case PERMISSION_OPERATION_SUCCESS:
20063                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20064                        writeRuntimePermissions = true;
20065                        final int appId = ps.appId;
20066                        mHandler.post(new Runnable() {
20067                            @Override
20068                            public void run() {
20069                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20070                            }
20071                        });
20072                    } break;
20073                }
20074            }
20075        }
20076
20077        // Synchronously write as we are taking permissions away.
20078        if (writeRuntimePermissions) {
20079            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20080        }
20081
20082        // Synchronously write as we are taking permissions away.
20083        if (writeInstallPermissions) {
20084            mSettings.writeLPr();
20085        }
20086    }
20087
20088    /**
20089     * Remove entries from the keystore daemon. Will only remove it if the
20090     * {@code appId} is valid.
20091     */
20092    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20093        if (appId < 0) {
20094            return;
20095        }
20096
20097        final KeyStore keyStore = KeyStore.getInstance();
20098        if (keyStore != null) {
20099            if (userId == UserHandle.USER_ALL) {
20100                for (final int individual : sUserManager.getUserIds()) {
20101                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20102                }
20103            } else {
20104                keyStore.clearUid(UserHandle.getUid(userId, appId));
20105            }
20106        } else {
20107            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20108        }
20109    }
20110
20111    @Override
20112    public void deleteApplicationCacheFiles(final String packageName,
20113            final IPackageDataObserver observer) {
20114        final int userId = UserHandle.getCallingUserId();
20115        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20116    }
20117
20118    @Override
20119    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20120            final IPackageDataObserver observer) {
20121        final int callingUid = Binder.getCallingUid();
20122        mContext.enforceCallingOrSelfPermission(
20123                android.Manifest.permission.DELETE_CACHE_FILES, null);
20124        enforceCrossUserPermission(callingUid, userId,
20125                /* requireFullPermission= */ true, /* checkShell= */ false,
20126                "delete application cache files");
20127        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20128                android.Manifest.permission.ACCESS_INSTANT_APPS);
20129
20130        final PackageParser.Package pkg;
20131        synchronized (mPackages) {
20132            pkg = mPackages.get(packageName);
20133        }
20134
20135        // Queue up an async operation since the package deletion may take a little while.
20136        mHandler.post(new Runnable() {
20137            public void run() {
20138                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20139                boolean doClearData = true;
20140                if (ps != null) {
20141                    final boolean targetIsInstantApp =
20142                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20143                    doClearData = !targetIsInstantApp
20144                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20145                }
20146                if (doClearData) {
20147                    synchronized (mInstallLock) {
20148                        final int flags = StorageManager.FLAG_STORAGE_DE
20149                                | StorageManager.FLAG_STORAGE_CE;
20150                        // We're only clearing cache files, so we don't care if the
20151                        // app is unfrozen and still able to run
20152                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20153                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20154                    }
20155                    clearExternalStorageDataSync(packageName, userId, false);
20156                }
20157                if (observer != null) {
20158                    try {
20159                        observer.onRemoveCompleted(packageName, true);
20160                    } catch (RemoteException e) {
20161                        Log.i(TAG, "Observer no longer exists.");
20162                    }
20163                }
20164            }
20165        });
20166    }
20167
20168    @Override
20169    public void getPackageSizeInfo(final String packageName, int userHandle,
20170            final IPackageStatsObserver observer) {
20171        throw new UnsupportedOperationException(
20172                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20173    }
20174
20175    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20176        final PackageSetting ps;
20177        synchronized (mPackages) {
20178            ps = mSettings.mPackages.get(packageName);
20179            if (ps == null) {
20180                Slog.w(TAG, "Failed to find settings for " + packageName);
20181                return false;
20182            }
20183        }
20184
20185        final String[] packageNames = { packageName };
20186        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20187        final String[] codePaths = { ps.codePathString };
20188
20189        try {
20190            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20191                    ps.appId, ceDataInodes, codePaths, stats);
20192
20193            // For now, ignore code size of packages on system partition
20194            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20195                stats.codeSize = 0;
20196            }
20197
20198            // External clients expect these to be tracked separately
20199            stats.dataSize -= stats.cacheSize;
20200
20201        } catch (InstallerException e) {
20202            Slog.w(TAG, String.valueOf(e));
20203            return false;
20204        }
20205
20206        return true;
20207    }
20208
20209    private int getUidTargetSdkVersionLockedLPr(int uid) {
20210        Object obj = mSettings.getUserIdLPr(uid);
20211        if (obj instanceof SharedUserSetting) {
20212            final SharedUserSetting sus = (SharedUserSetting) obj;
20213            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20214            final Iterator<PackageSetting> it = sus.packages.iterator();
20215            while (it.hasNext()) {
20216                final PackageSetting ps = it.next();
20217                if (ps.pkg != null) {
20218                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20219                    if (v < vers) vers = v;
20220                }
20221            }
20222            return vers;
20223        } else if (obj instanceof PackageSetting) {
20224            final PackageSetting ps = (PackageSetting) obj;
20225            if (ps.pkg != null) {
20226                return ps.pkg.applicationInfo.targetSdkVersion;
20227            }
20228        }
20229        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20230    }
20231
20232    @Override
20233    public void addPreferredActivity(IntentFilter filter, int match,
20234            ComponentName[] set, ComponentName activity, int userId) {
20235        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20236                "Adding preferred");
20237    }
20238
20239    private void addPreferredActivityInternal(IntentFilter filter, int match,
20240            ComponentName[] set, ComponentName activity, boolean always, int userId,
20241            String opname) {
20242        // writer
20243        int callingUid = Binder.getCallingUid();
20244        enforceCrossUserPermission(callingUid, userId,
20245                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20246        if (filter.countActions() == 0) {
20247            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20248            return;
20249        }
20250        synchronized (mPackages) {
20251            if (mContext.checkCallingOrSelfPermission(
20252                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20253                    != PackageManager.PERMISSION_GRANTED) {
20254                if (getUidTargetSdkVersionLockedLPr(callingUid)
20255                        < Build.VERSION_CODES.FROYO) {
20256                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20257                            + callingUid);
20258                    return;
20259                }
20260                mContext.enforceCallingOrSelfPermission(
20261                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20262            }
20263
20264            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20265            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20266                    + userId + ":");
20267            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20268            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20269            scheduleWritePackageRestrictionsLocked(userId);
20270            postPreferredActivityChangedBroadcast(userId);
20271        }
20272    }
20273
20274    private void postPreferredActivityChangedBroadcast(int userId) {
20275        mHandler.post(() -> {
20276            final IActivityManager am = ActivityManager.getService();
20277            if (am == null) {
20278                return;
20279            }
20280
20281            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20282            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20283            try {
20284                am.broadcastIntent(null, intent, null, null,
20285                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20286                        null, false, false, userId);
20287            } catch (RemoteException e) {
20288            }
20289        });
20290    }
20291
20292    @Override
20293    public void replacePreferredActivity(IntentFilter filter, int match,
20294            ComponentName[] set, ComponentName activity, int userId) {
20295        if (filter.countActions() != 1) {
20296            throw new IllegalArgumentException(
20297                    "replacePreferredActivity expects filter to have only 1 action.");
20298        }
20299        if (filter.countDataAuthorities() != 0
20300                || filter.countDataPaths() != 0
20301                || filter.countDataSchemes() > 1
20302                || filter.countDataTypes() != 0) {
20303            throw new IllegalArgumentException(
20304                    "replacePreferredActivity expects filter to have no data authorities, " +
20305                    "paths, or types; and at most one scheme.");
20306        }
20307
20308        final int callingUid = Binder.getCallingUid();
20309        enforceCrossUserPermission(callingUid, userId,
20310                true /* requireFullPermission */, false /* checkShell */,
20311                "replace preferred activity");
20312        synchronized (mPackages) {
20313            if (mContext.checkCallingOrSelfPermission(
20314                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20315                    != PackageManager.PERMISSION_GRANTED) {
20316                if (getUidTargetSdkVersionLockedLPr(callingUid)
20317                        < Build.VERSION_CODES.FROYO) {
20318                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20319                            + Binder.getCallingUid());
20320                    return;
20321                }
20322                mContext.enforceCallingOrSelfPermission(
20323                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20324            }
20325
20326            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20327            if (pir != null) {
20328                // Get all of the existing entries that exactly match this filter.
20329                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20330                if (existing != null && existing.size() == 1) {
20331                    PreferredActivity cur = existing.get(0);
20332                    if (DEBUG_PREFERRED) {
20333                        Slog.i(TAG, "Checking replace of preferred:");
20334                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20335                        if (!cur.mPref.mAlways) {
20336                            Slog.i(TAG, "  -- CUR; not mAlways!");
20337                        } else {
20338                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20339                            Slog.i(TAG, "  -- CUR: mSet="
20340                                    + Arrays.toString(cur.mPref.mSetComponents));
20341                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20342                            Slog.i(TAG, "  -- NEW: mMatch="
20343                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20344                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20345                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20346                        }
20347                    }
20348                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20349                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20350                            && cur.mPref.sameSet(set)) {
20351                        // Setting the preferred activity to what it happens to be already
20352                        if (DEBUG_PREFERRED) {
20353                            Slog.i(TAG, "Replacing with same preferred activity "
20354                                    + cur.mPref.mShortComponent + " for user "
20355                                    + userId + ":");
20356                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20357                        }
20358                        return;
20359                    }
20360                }
20361
20362                if (existing != null) {
20363                    if (DEBUG_PREFERRED) {
20364                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20365                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20366                    }
20367                    for (int i = 0; i < existing.size(); i++) {
20368                        PreferredActivity pa = existing.get(i);
20369                        if (DEBUG_PREFERRED) {
20370                            Slog.i(TAG, "Removing existing preferred activity "
20371                                    + pa.mPref.mComponent + ":");
20372                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20373                        }
20374                        pir.removeFilter(pa);
20375                    }
20376                }
20377            }
20378            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20379                    "Replacing preferred");
20380        }
20381    }
20382
20383    @Override
20384    public void clearPackagePreferredActivities(String packageName) {
20385        final int callingUid = Binder.getCallingUid();
20386        if (getInstantAppPackageName(callingUid) != null) {
20387            return;
20388        }
20389        // writer
20390        synchronized (mPackages) {
20391            PackageParser.Package pkg = mPackages.get(packageName);
20392            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20393                if (mContext.checkCallingOrSelfPermission(
20394                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20395                        != PackageManager.PERMISSION_GRANTED) {
20396                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20397                            < Build.VERSION_CODES.FROYO) {
20398                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20399                                + callingUid);
20400                        return;
20401                    }
20402                    mContext.enforceCallingOrSelfPermission(
20403                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20404                }
20405            }
20406            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20407            if (ps != null
20408                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20409                return;
20410            }
20411            int user = UserHandle.getCallingUserId();
20412            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20413                scheduleWritePackageRestrictionsLocked(user);
20414            }
20415        }
20416    }
20417
20418    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20419    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20420        ArrayList<PreferredActivity> removed = null;
20421        boolean changed = false;
20422        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20423            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20424            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20425            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20426                continue;
20427            }
20428            Iterator<PreferredActivity> it = pir.filterIterator();
20429            while (it.hasNext()) {
20430                PreferredActivity pa = it.next();
20431                // Mark entry for removal only if it matches the package name
20432                // and the entry is of type "always".
20433                if (packageName == null ||
20434                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20435                                && pa.mPref.mAlways)) {
20436                    if (removed == null) {
20437                        removed = new ArrayList<PreferredActivity>();
20438                    }
20439                    removed.add(pa);
20440                }
20441            }
20442            if (removed != null) {
20443                for (int j=0; j<removed.size(); j++) {
20444                    PreferredActivity pa = removed.get(j);
20445                    pir.removeFilter(pa);
20446                }
20447                changed = true;
20448            }
20449        }
20450        if (changed) {
20451            postPreferredActivityChangedBroadcast(userId);
20452        }
20453        return changed;
20454    }
20455
20456    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20457    private void clearIntentFilterVerificationsLPw(int userId) {
20458        final int packageCount = mPackages.size();
20459        for (int i = 0; i < packageCount; i++) {
20460            PackageParser.Package pkg = mPackages.valueAt(i);
20461            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20462        }
20463    }
20464
20465    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20466    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20467        if (userId == UserHandle.USER_ALL) {
20468            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20469                    sUserManager.getUserIds())) {
20470                for (int oneUserId : sUserManager.getUserIds()) {
20471                    scheduleWritePackageRestrictionsLocked(oneUserId);
20472                }
20473            }
20474        } else {
20475            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20476                scheduleWritePackageRestrictionsLocked(userId);
20477            }
20478        }
20479    }
20480
20481    /** Clears state for all users, and touches intent filter verification policy */
20482    void clearDefaultBrowserIfNeeded(String packageName) {
20483        for (int oneUserId : sUserManager.getUserIds()) {
20484            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20485        }
20486    }
20487
20488    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20489        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20490        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20491            if (packageName.equals(defaultBrowserPackageName)) {
20492                setDefaultBrowserPackageName(null, userId);
20493            }
20494        }
20495    }
20496
20497    @Override
20498    public void resetApplicationPreferences(int userId) {
20499        mContext.enforceCallingOrSelfPermission(
20500                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20501        final long identity = Binder.clearCallingIdentity();
20502        // writer
20503        try {
20504            synchronized (mPackages) {
20505                clearPackagePreferredActivitiesLPw(null, userId);
20506                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20507                // TODO: We have to reset the default SMS and Phone. This requires
20508                // significant refactoring to keep all default apps in the package
20509                // manager (cleaner but more work) or have the services provide
20510                // callbacks to the package manager to request a default app reset.
20511                applyFactoryDefaultBrowserLPw(userId);
20512                clearIntentFilterVerificationsLPw(userId);
20513                primeDomainVerificationsLPw(userId);
20514                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20515                scheduleWritePackageRestrictionsLocked(userId);
20516            }
20517            resetNetworkPolicies(userId);
20518        } finally {
20519            Binder.restoreCallingIdentity(identity);
20520        }
20521    }
20522
20523    @Override
20524    public int getPreferredActivities(List<IntentFilter> outFilters,
20525            List<ComponentName> outActivities, String packageName) {
20526        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20527            return 0;
20528        }
20529        int num = 0;
20530        final int userId = UserHandle.getCallingUserId();
20531        // reader
20532        synchronized (mPackages) {
20533            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20534            if (pir != null) {
20535                final Iterator<PreferredActivity> it = pir.filterIterator();
20536                while (it.hasNext()) {
20537                    final PreferredActivity pa = it.next();
20538                    if (packageName == null
20539                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20540                                    && pa.mPref.mAlways)) {
20541                        if (outFilters != null) {
20542                            outFilters.add(new IntentFilter(pa));
20543                        }
20544                        if (outActivities != null) {
20545                            outActivities.add(pa.mPref.mComponent);
20546                        }
20547                    }
20548                }
20549            }
20550        }
20551
20552        return num;
20553    }
20554
20555    @Override
20556    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20557            int userId) {
20558        int callingUid = Binder.getCallingUid();
20559        if (callingUid != Process.SYSTEM_UID) {
20560            throw new SecurityException(
20561                    "addPersistentPreferredActivity can only be run by the system");
20562        }
20563        if (filter.countActions() == 0) {
20564            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20565            return;
20566        }
20567        synchronized (mPackages) {
20568            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20569                    ":");
20570            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20571            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20572                    new PersistentPreferredActivity(filter, activity));
20573            scheduleWritePackageRestrictionsLocked(userId);
20574            postPreferredActivityChangedBroadcast(userId);
20575        }
20576    }
20577
20578    @Override
20579    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20580        int callingUid = Binder.getCallingUid();
20581        if (callingUid != Process.SYSTEM_UID) {
20582            throw new SecurityException(
20583                    "clearPackagePersistentPreferredActivities can only be run by the system");
20584        }
20585        ArrayList<PersistentPreferredActivity> removed = null;
20586        boolean changed = false;
20587        synchronized (mPackages) {
20588            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20589                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20590                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20591                        .valueAt(i);
20592                if (userId != thisUserId) {
20593                    continue;
20594                }
20595                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20596                while (it.hasNext()) {
20597                    PersistentPreferredActivity ppa = it.next();
20598                    // Mark entry for removal only if it matches the package name.
20599                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20600                        if (removed == null) {
20601                            removed = new ArrayList<PersistentPreferredActivity>();
20602                        }
20603                        removed.add(ppa);
20604                    }
20605                }
20606                if (removed != null) {
20607                    for (int j=0; j<removed.size(); j++) {
20608                        PersistentPreferredActivity ppa = removed.get(j);
20609                        ppir.removeFilter(ppa);
20610                    }
20611                    changed = true;
20612                }
20613            }
20614
20615            if (changed) {
20616                scheduleWritePackageRestrictionsLocked(userId);
20617                postPreferredActivityChangedBroadcast(userId);
20618            }
20619        }
20620    }
20621
20622    /**
20623     * Common machinery for picking apart a restored XML blob and passing
20624     * it to a caller-supplied functor to be applied to the running system.
20625     */
20626    private void restoreFromXml(XmlPullParser parser, int userId,
20627            String expectedStartTag, BlobXmlRestorer functor)
20628            throws IOException, XmlPullParserException {
20629        int type;
20630        while ((type = parser.next()) != XmlPullParser.START_TAG
20631                && type != XmlPullParser.END_DOCUMENT) {
20632        }
20633        if (type != XmlPullParser.START_TAG) {
20634            // oops didn't find a start tag?!
20635            if (DEBUG_BACKUP) {
20636                Slog.e(TAG, "Didn't find start tag during restore");
20637            }
20638            return;
20639        }
20640Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20641        // this is supposed to be TAG_PREFERRED_BACKUP
20642        if (!expectedStartTag.equals(parser.getName())) {
20643            if (DEBUG_BACKUP) {
20644                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20645            }
20646            return;
20647        }
20648
20649        // skip interfering stuff, then we're aligned with the backing implementation
20650        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20651Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20652        functor.apply(parser, userId);
20653    }
20654
20655    private interface BlobXmlRestorer {
20656        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20657    }
20658
20659    /**
20660     * Non-Binder method, support for the backup/restore mechanism: write the
20661     * full set of preferred activities in its canonical XML format.  Returns the
20662     * XML output as a byte array, or null if there is none.
20663     */
20664    @Override
20665    public byte[] getPreferredActivityBackup(int userId) {
20666        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20667            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20668        }
20669
20670        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20671        try {
20672            final XmlSerializer serializer = new FastXmlSerializer();
20673            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20674            serializer.startDocument(null, true);
20675            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20676
20677            synchronized (mPackages) {
20678                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20679            }
20680
20681            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20682            serializer.endDocument();
20683            serializer.flush();
20684        } catch (Exception e) {
20685            if (DEBUG_BACKUP) {
20686                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20687            }
20688            return null;
20689        }
20690
20691        return dataStream.toByteArray();
20692    }
20693
20694    @Override
20695    public void restorePreferredActivities(byte[] backup, int userId) {
20696        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20697            throw new SecurityException("Only the system may call restorePreferredActivities()");
20698        }
20699
20700        try {
20701            final XmlPullParser parser = Xml.newPullParser();
20702            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20703            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20704                    new BlobXmlRestorer() {
20705                        @Override
20706                        public void apply(XmlPullParser parser, int userId)
20707                                throws XmlPullParserException, IOException {
20708                            synchronized (mPackages) {
20709                                mSettings.readPreferredActivitiesLPw(parser, userId);
20710                            }
20711                        }
20712                    } );
20713        } catch (Exception e) {
20714            if (DEBUG_BACKUP) {
20715                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20716            }
20717        }
20718    }
20719
20720    /**
20721     * Non-Binder method, support for the backup/restore mechanism: write the
20722     * default browser (etc) settings in its canonical XML format.  Returns the default
20723     * browser XML representation as a byte array, or null if there is none.
20724     */
20725    @Override
20726    public byte[] getDefaultAppsBackup(int userId) {
20727        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20728            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20729        }
20730
20731        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20732        try {
20733            final XmlSerializer serializer = new FastXmlSerializer();
20734            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20735            serializer.startDocument(null, true);
20736            serializer.startTag(null, TAG_DEFAULT_APPS);
20737
20738            synchronized (mPackages) {
20739                mSettings.writeDefaultAppsLPr(serializer, userId);
20740            }
20741
20742            serializer.endTag(null, TAG_DEFAULT_APPS);
20743            serializer.endDocument();
20744            serializer.flush();
20745        } catch (Exception e) {
20746            if (DEBUG_BACKUP) {
20747                Slog.e(TAG, "Unable to write default apps for backup", e);
20748            }
20749            return null;
20750        }
20751
20752        return dataStream.toByteArray();
20753    }
20754
20755    @Override
20756    public void restoreDefaultApps(byte[] backup, int userId) {
20757        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20758            throw new SecurityException("Only the system may call restoreDefaultApps()");
20759        }
20760
20761        try {
20762            final XmlPullParser parser = Xml.newPullParser();
20763            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20764            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20765                    new BlobXmlRestorer() {
20766                        @Override
20767                        public void apply(XmlPullParser parser, int userId)
20768                                throws XmlPullParserException, IOException {
20769                            synchronized (mPackages) {
20770                                mSettings.readDefaultAppsLPw(parser, userId);
20771                            }
20772                        }
20773                    } );
20774        } catch (Exception e) {
20775            if (DEBUG_BACKUP) {
20776                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20777            }
20778        }
20779    }
20780
20781    @Override
20782    public byte[] getIntentFilterVerificationBackup(int userId) {
20783        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20784            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20785        }
20786
20787        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20788        try {
20789            final XmlSerializer serializer = new FastXmlSerializer();
20790            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20791            serializer.startDocument(null, true);
20792            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20793
20794            synchronized (mPackages) {
20795                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20796            }
20797
20798            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20799            serializer.endDocument();
20800            serializer.flush();
20801        } catch (Exception e) {
20802            if (DEBUG_BACKUP) {
20803                Slog.e(TAG, "Unable to write default apps for backup", e);
20804            }
20805            return null;
20806        }
20807
20808        return dataStream.toByteArray();
20809    }
20810
20811    @Override
20812    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20813        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20814            throw new SecurityException("Only the system may call restorePreferredActivities()");
20815        }
20816
20817        try {
20818            final XmlPullParser parser = Xml.newPullParser();
20819            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20820            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20821                    new BlobXmlRestorer() {
20822                        @Override
20823                        public void apply(XmlPullParser parser, int userId)
20824                                throws XmlPullParserException, IOException {
20825                            synchronized (mPackages) {
20826                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20827                                mSettings.writeLPr();
20828                            }
20829                        }
20830                    } );
20831        } catch (Exception e) {
20832            if (DEBUG_BACKUP) {
20833                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20834            }
20835        }
20836    }
20837
20838    @Override
20839    public byte[] getPermissionGrantBackup(int userId) {
20840        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20841            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20842        }
20843
20844        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20845        try {
20846            final XmlSerializer serializer = new FastXmlSerializer();
20847            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20848            serializer.startDocument(null, true);
20849            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20850
20851            synchronized (mPackages) {
20852                serializeRuntimePermissionGrantsLPr(serializer, userId);
20853            }
20854
20855            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20856            serializer.endDocument();
20857            serializer.flush();
20858        } catch (Exception e) {
20859            if (DEBUG_BACKUP) {
20860                Slog.e(TAG, "Unable to write default apps for backup", e);
20861            }
20862            return null;
20863        }
20864
20865        return dataStream.toByteArray();
20866    }
20867
20868    @Override
20869    public void restorePermissionGrants(byte[] backup, int userId) {
20870        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20871            throw new SecurityException("Only the system may call restorePermissionGrants()");
20872        }
20873
20874        try {
20875            final XmlPullParser parser = Xml.newPullParser();
20876            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20877            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20878                    new BlobXmlRestorer() {
20879                        @Override
20880                        public void apply(XmlPullParser parser, int userId)
20881                                throws XmlPullParserException, IOException {
20882                            synchronized (mPackages) {
20883                                processRestoredPermissionGrantsLPr(parser, userId);
20884                            }
20885                        }
20886                    } );
20887        } catch (Exception e) {
20888            if (DEBUG_BACKUP) {
20889                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20890            }
20891        }
20892    }
20893
20894    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20895            throws IOException {
20896        serializer.startTag(null, TAG_ALL_GRANTS);
20897
20898        final int N = mSettings.mPackages.size();
20899        for (int i = 0; i < N; i++) {
20900            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20901            boolean pkgGrantsKnown = false;
20902
20903            PermissionsState packagePerms = ps.getPermissionsState();
20904
20905            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20906                final int grantFlags = state.getFlags();
20907                // only look at grants that are not system/policy fixed
20908                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20909                    final boolean isGranted = state.isGranted();
20910                    // And only back up the user-twiddled state bits
20911                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20912                        final String packageName = mSettings.mPackages.keyAt(i);
20913                        if (!pkgGrantsKnown) {
20914                            serializer.startTag(null, TAG_GRANT);
20915                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20916                            pkgGrantsKnown = true;
20917                        }
20918
20919                        final boolean userSet =
20920                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20921                        final boolean userFixed =
20922                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20923                        final boolean revoke =
20924                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20925
20926                        serializer.startTag(null, TAG_PERMISSION);
20927                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20928                        if (isGranted) {
20929                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20930                        }
20931                        if (userSet) {
20932                            serializer.attribute(null, ATTR_USER_SET, "true");
20933                        }
20934                        if (userFixed) {
20935                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20936                        }
20937                        if (revoke) {
20938                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20939                        }
20940                        serializer.endTag(null, TAG_PERMISSION);
20941                    }
20942                }
20943            }
20944
20945            if (pkgGrantsKnown) {
20946                serializer.endTag(null, TAG_GRANT);
20947            }
20948        }
20949
20950        serializer.endTag(null, TAG_ALL_GRANTS);
20951    }
20952
20953    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20954            throws XmlPullParserException, IOException {
20955        String pkgName = null;
20956        int outerDepth = parser.getDepth();
20957        int type;
20958        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20959                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20960            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20961                continue;
20962            }
20963
20964            final String tagName = parser.getName();
20965            if (tagName.equals(TAG_GRANT)) {
20966                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20967                if (DEBUG_BACKUP) {
20968                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20969                }
20970            } else if (tagName.equals(TAG_PERMISSION)) {
20971
20972                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20973                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20974
20975                int newFlagSet = 0;
20976                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20977                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20978                }
20979                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20980                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20981                }
20982                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20983                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20984                }
20985                if (DEBUG_BACKUP) {
20986                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20987                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20988                }
20989                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20990                if (ps != null) {
20991                    // Already installed so we apply the grant immediately
20992                    if (DEBUG_BACKUP) {
20993                        Slog.v(TAG, "        + already installed; applying");
20994                    }
20995                    PermissionsState perms = ps.getPermissionsState();
20996                    BasePermission bp = mSettings.mPermissions.get(permName);
20997                    if (bp != null) {
20998                        if (isGranted) {
20999                            perms.grantRuntimePermission(bp, userId);
21000                        }
21001                        if (newFlagSet != 0) {
21002                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21003                        }
21004                    }
21005                } else {
21006                    // Need to wait for post-restore install to apply the grant
21007                    if (DEBUG_BACKUP) {
21008                        Slog.v(TAG, "        - not yet installed; saving for later");
21009                    }
21010                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21011                            isGranted, newFlagSet, userId);
21012                }
21013            } else {
21014                PackageManagerService.reportSettingsProblem(Log.WARN,
21015                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21016                XmlUtils.skipCurrentTag(parser);
21017            }
21018        }
21019
21020        scheduleWriteSettingsLocked();
21021        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21022    }
21023
21024    @Override
21025    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21026            int sourceUserId, int targetUserId, int flags) {
21027        mContext.enforceCallingOrSelfPermission(
21028                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21029        int callingUid = Binder.getCallingUid();
21030        enforceOwnerRights(ownerPackage, callingUid);
21031        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21032        if (intentFilter.countActions() == 0) {
21033            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21034            return;
21035        }
21036        synchronized (mPackages) {
21037            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21038                    ownerPackage, targetUserId, flags);
21039            CrossProfileIntentResolver resolver =
21040                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21041            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21042            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21043            if (existing != null) {
21044                int size = existing.size();
21045                for (int i = 0; i < size; i++) {
21046                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21047                        return;
21048                    }
21049                }
21050            }
21051            resolver.addFilter(newFilter);
21052            scheduleWritePackageRestrictionsLocked(sourceUserId);
21053        }
21054    }
21055
21056    @Override
21057    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21058        mContext.enforceCallingOrSelfPermission(
21059                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21060        final int callingUid = Binder.getCallingUid();
21061        enforceOwnerRights(ownerPackage, callingUid);
21062        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21063        synchronized (mPackages) {
21064            CrossProfileIntentResolver resolver =
21065                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21066            ArraySet<CrossProfileIntentFilter> set =
21067                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21068            for (CrossProfileIntentFilter filter : set) {
21069                if (filter.getOwnerPackage().equals(ownerPackage)) {
21070                    resolver.removeFilter(filter);
21071                }
21072            }
21073            scheduleWritePackageRestrictionsLocked(sourceUserId);
21074        }
21075    }
21076
21077    // Enforcing that callingUid is owning pkg on userId
21078    private void enforceOwnerRights(String pkg, int callingUid) {
21079        // The system owns everything.
21080        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21081            return;
21082        }
21083        final int callingUserId = UserHandle.getUserId(callingUid);
21084        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21085        if (pi == null) {
21086            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21087                    + callingUserId);
21088        }
21089        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21090            throw new SecurityException("Calling uid " + callingUid
21091                    + " does not own package " + pkg);
21092        }
21093    }
21094
21095    @Override
21096    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21097        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21098            return null;
21099        }
21100        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21101    }
21102
21103    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21104        UserManagerService ums = UserManagerService.getInstance();
21105        if (ums != null) {
21106            final UserInfo parent = ums.getProfileParent(userId);
21107            final int launcherUid = (parent != null) ? parent.id : userId;
21108            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21109            if (launcherComponent != null) {
21110                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21111                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21112                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21113                        .setPackage(launcherComponent.getPackageName());
21114                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21115            }
21116        }
21117    }
21118
21119    /**
21120     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21121     * then reports the most likely home activity or null if there are more than one.
21122     */
21123    private ComponentName getDefaultHomeActivity(int userId) {
21124        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21125        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21126        if (cn != null) {
21127            return cn;
21128        }
21129
21130        // Find the launcher with the highest priority and return that component if there are no
21131        // other home activity with the same priority.
21132        int lastPriority = Integer.MIN_VALUE;
21133        ComponentName lastComponent = null;
21134        final int size = allHomeCandidates.size();
21135        for (int i = 0; i < size; i++) {
21136            final ResolveInfo ri = allHomeCandidates.get(i);
21137            if (ri.priority > lastPriority) {
21138                lastComponent = ri.activityInfo.getComponentName();
21139                lastPriority = ri.priority;
21140            } else if (ri.priority == lastPriority) {
21141                // Two components found with same priority.
21142                lastComponent = null;
21143            }
21144        }
21145        return lastComponent;
21146    }
21147
21148    private Intent getHomeIntent() {
21149        Intent intent = new Intent(Intent.ACTION_MAIN);
21150        intent.addCategory(Intent.CATEGORY_HOME);
21151        intent.addCategory(Intent.CATEGORY_DEFAULT);
21152        return intent;
21153    }
21154
21155    private IntentFilter getHomeFilter() {
21156        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21157        filter.addCategory(Intent.CATEGORY_HOME);
21158        filter.addCategory(Intent.CATEGORY_DEFAULT);
21159        return filter;
21160    }
21161
21162    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21163            int userId) {
21164        Intent intent  = getHomeIntent();
21165        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21166                PackageManager.GET_META_DATA, userId);
21167        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21168                true, false, false, userId);
21169
21170        allHomeCandidates.clear();
21171        if (list != null) {
21172            for (ResolveInfo ri : list) {
21173                allHomeCandidates.add(ri);
21174            }
21175        }
21176        return (preferred == null || preferred.activityInfo == null)
21177                ? null
21178                : new ComponentName(preferred.activityInfo.packageName,
21179                        preferred.activityInfo.name);
21180    }
21181
21182    @Override
21183    public void setHomeActivity(ComponentName comp, int userId) {
21184        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21185            return;
21186        }
21187        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21188        getHomeActivitiesAsUser(homeActivities, userId);
21189
21190        boolean found = false;
21191
21192        final int size = homeActivities.size();
21193        final ComponentName[] set = new ComponentName[size];
21194        for (int i = 0; i < size; i++) {
21195            final ResolveInfo candidate = homeActivities.get(i);
21196            final ActivityInfo info = candidate.activityInfo;
21197            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21198            set[i] = activityName;
21199            if (!found && activityName.equals(comp)) {
21200                found = true;
21201            }
21202        }
21203        if (!found) {
21204            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21205                    + userId);
21206        }
21207        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21208                set, comp, userId);
21209    }
21210
21211    private @Nullable String getSetupWizardPackageName() {
21212        final Intent intent = new Intent(Intent.ACTION_MAIN);
21213        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21214
21215        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21216                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21217                        | MATCH_DISABLED_COMPONENTS,
21218                UserHandle.myUserId());
21219        if (matches.size() == 1) {
21220            return matches.get(0).getComponentInfo().packageName;
21221        } else {
21222            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21223                    + ": matches=" + matches);
21224            return null;
21225        }
21226    }
21227
21228    private @Nullable String getStorageManagerPackageName() {
21229        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21230
21231        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21232                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21233                        | MATCH_DISABLED_COMPONENTS,
21234                UserHandle.myUserId());
21235        if (matches.size() == 1) {
21236            return matches.get(0).getComponentInfo().packageName;
21237        } else {
21238            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21239                    + matches.size() + ": matches=" + matches);
21240            return null;
21241        }
21242    }
21243
21244    @Override
21245    public void setApplicationEnabledSetting(String appPackageName,
21246            int newState, int flags, int userId, String callingPackage) {
21247        if (!sUserManager.exists(userId)) return;
21248        if (callingPackage == null) {
21249            callingPackage = Integer.toString(Binder.getCallingUid());
21250        }
21251        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21252    }
21253
21254    @Override
21255    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21256        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21257        synchronized (mPackages) {
21258            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21259            if (pkgSetting != null) {
21260                pkgSetting.setUpdateAvailable(updateAvailable);
21261            }
21262        }
21263    }
21264
21265    @Override
21266    public void setComponentEnabledSetting(ComponentName componentName,
21267            int newState, int flags, int userId) {
21268        if (!sUserManager.exists(userId)) return;
21269        setEnabledSetting(componentName.getPackageName(),
21270                componentName.getClassName(), newState, flags, userId, null);
21271    }
21272
21273    private void setEnabledSetting(final String packageName, String className, int newState,
21274            final int flags, int userId, String callingPackage) {
21275        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21276              || newState == COMPONENT_ENABLED_STATE_ENABLED
21277              || newState == COMPONENT_ENABLED_STATE_DISABLED
21278              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21279              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21280            throw new IllegalArgumentException("Invalid new component state: "
21281                    + newState);
21282        }
21283        PackageSetting pkgSetting;
21284        final int callingUid = Binder.getCallingUid();
21285        final int permission;
21286        if (callingUid == Process.SYSTEM_UID) {
21287            permission = PackageManager.PERMISSION_GRANTED;
21288        } else {
21289            permission = mContext.checkCallingOrSelfPermission(
21290                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21291        }
21292        enforceCrossUserPermission(callingUid, userId,
21293                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21294        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21295        boolean sendNow = false;
21296        boolean isApp = (className == null);
21297        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21298        String componentName = isApp ? packageName : className;
21299        int packageUid = -1;
21300        ArrayList<String> components;
21301
21302        // reader
21303        synchronized (mPackages) {
21304            pkgSetting = mSettings.mPackages.get(packageName);
21305            if (pkgSetting == null) {
21306                if (!isCallerInstantApp) {
21307                    if (className == null) {
21308                        throw new IllegalArgumentException("Unknown package: " + packageName);
21309                    }
21310                    throw new IllegalArgumentException(
21311                            "Unknown component: " + packageName + "/" + className);
21312                } else {
21313                    // throw SecurityException to prevent leaking package information
21314                    throw new SecurityException(
21315                            "Attempt to change component state; "
21316                            + "pid=" + Binder.getCallingPid()
21317                            + ", uid=" + callingUid
21318                            + (className == null
21319                                    ? ", package=" + packageName
21320                                    : ", component=" + packageName + "/" + className));
21321                }
21322            }
21323        }
21324
21325        // Limit who can change which apps
21326        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21327            // Don't allow apps that don't have permission to modify other apps
21328            if (!allowedByPermission
21329                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21330                throw new SecurityException(
21331                        "Attempt to change component state; "
21332                        + "pid=" + Binder.getCallingPid()
21333                        + ", uid=" + callingUid
21334                        + (className == null
21335                                ? ", package=" + packageName
21336                                : ", component=" + packageName + "/" + className));
21337            }
21338            // Don't allow changing protected packages.
21339            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21340                throw new SecurityException("Cannot disable a protected package: " + packageName);
21341            }
21342        }
21343
21344        synchronized (mPackages) {
21345            if (callingUid == Process.SHELL_UID
21346                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21347                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21348                // unless it is a test package.
21349                int oldState = pkgSetting.getEnabled(userId);
21350                if (className == null
21351                        &&
21352                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21353                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21354                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21355                        &&
21356                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21357                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21358                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21359                    // ok
21360                } else {
21361                    throw new SecurityException(
21362                            "Shell cannot change component state for " + packageName + "/"
21363                                    + className + " to " + newState);
21364                }
21365            }
21366        }
21367        if (className == null) {
21368            // We're dealing with an application/package level state change
21369            synchronized (mPackages) {
21370                if (pkgSetting.getEnabled(userId) == newState) {
21371                    // Nothing to do
21372                    return;
21373                }
21374            }
21375            // If we're enabling a system stub, there's a little more work to do.
21376            // Prior to enabling the package, we need to decompress the APK(s) to the
21377            // data partition and then replace the version on the system partition.
21378            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21379            final boolean isSystemStub = deletedPkg.isStub
21380                    && deletedPkg.isSystemApp();
21381            if (isSystemStub
21382                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21383                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21384                final File codePath = decompressPackage(deletedPkg);
21385                if (codePath == null) {
21386                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21387                    return;
21388                }
21389                // TODO remove direct parsing of the package object during internal cleanup
21390                // of scan package
21391                // We need to call parse directly here for no other reason than we need
21392                // the new package in order to disable the old one [we use the information
21393                // for some internal optimization to optionally create a new package setting
21394                // object on replace]. However, we can't get the package from the scan
21395                // because the scan modifies live structures and we need to remove the
21396                // old [system] package from the system before a scan can be attempted.
21397                // Once scan is indempotent we can remove this parse and use the package
21398                // object we scanned, prior to adding it to package settings.
21399                final PackageParser pp = new PackageParser();
21400                pp.setSeparateProcesses(mSeparateProcesses);
21401                pp.setDisplayMetrics(mMetrics);
21402                pp.setCallback(mPackageParserCallback);
21403                final PackageParser.Package tmpPkg;
21404                try {
21405                    final int parseFlags = mDefParseFlags
21406                            | PackageParser.PARSE_MUST_BE_APK
21407                            | PackageParser.PARSE_IS_SYSTEM
21408                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21409                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21410                } catch (PackageParserException e) {
21411                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21412                    return;
21413                }
21414                synchronized (mInstallLock) {
21415                    // Disable the stub and remove any package entries
21416                    removePackageLI(deletedPkg, true);
21417                    synchronized (mPackages) {
21418                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21419                    }
21420                    final PackageParser.Package newPkg;
21421                    try (PackageFreezer freezer =
21422                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21423                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21424                                | PackageParser.PARSE_ENFORCE_CODE;
21425                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21426                                0 /*currentTime*/, null /*user*/);
21427                        prepareAppDataAfterInstallLIF(newPkg);
21428                        synchronized (mPackages) {
21429                            try {
21430                                updateSharedLibrariesLPr(newPkg, null);
21431                            } catch (PackageManagerException e) {
21432                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21433                            }
21434                            updatePermissionsLPw(newPkg.packageName, newPkg,
21435                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21436                            mSettings.writeLPr();
21437                        }
21438                    } catch (PackageManagerException e) {
21439                        // Whoops! Something went wrong; try to roll back to the stub
21440                        Slog.w(TAG, "Failed to install compressed system package:"
21441                                + pkgSetting.name, e);
21442                        // Remove the failed install
21443                        removeCodePathLI(codePath);
21444
21445                        // Install the system package
21446                        try (PackageFreezer freezer =
21447                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21448                            synchronized (mPackages) {
21449                                // NOTE: The system package always needs to be enabled; even
21450                                // if it's for a compressed stub. If we don't, installing the
21451                                // system package fails during scan [scanning checks the disabled
21452                                // packages]. We will reverse this later, after we've "installed"
21453                                // the stub.
21454                                // This leaves us in a fragile state; the stub should never be
21455                                // enabled, so, cross your fingers and hope nothing goes wrong
21456                                // until we can disable the package later.
21457                                enableSystemPackageLPw(deletedPkg);
21458                            }
21459                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21460                                    false /*isPrivileged*/, null /*allUserHandles*/,
21461                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21462                                    true /*writeSettings*/);
21463                        } catch (PackageManagerException pme) {
21464                            Slog.w(TAG, "Failed to restore system package:"
21465                                    + deletedPkg.packageName, pme);
21466                        } finally {
21467                            synchronized (mPackages) {
21468                                mSettings.disableSystemPackageLPw(
21469                                        deletedPkg.packageName, true /*replaced*/);
21470                                mSettings.writeLPr();
21471                            }
21472                        }
21473                        return;
21474                    }
21475                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21476                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21477                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21478                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21479                            newPkg.baseCodePath, newPkg.splitCodePaths);
21480                }
21481            }
21482            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21483                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21484                // Don't care about who enables an app.
21485                callingPackage = null;
21486            }
21487            synchronized (mPackages) {
21488                pkgSetting.setEnabled(newState, userId, callingPackage);
21489            }
21490        } else {
21491            synchronized (mPackages) {
21492                // We're dealing with a component level state change
21493                // First, verify that this is a valid class name.
21494                PackageParser.Package pkg = pkgSetting.pkg;
21495                if (pkg == null || !pkg.hasComponentClassName(className)) {
21496                    if (pkg != null &&
21497                            pkg.applicationInfo.targetSdkVersion >=
21498                                    Build.VERSION_CODES.JELLY_BEAN) {
21499                        throw new IllegalArgumentException("Component class " + className
21500                                + " does not exist in " + packageName);
21501                    } else {
21502                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21503                                + className + " does not exist in " + packageName);
21504                    }
21505                }
21506                switch (newState) {
21507                    case COMPONENT_ENABLED_STATE_ENABLED:
21508                        if (!pkgSetting.enableComponentLPw(className, userId)) {
21509                            return;
21510                        }
21511                        break;
21512                    case COMPONENT_ENABLED_STATE_DISABLED:
21513                        if (!pkgSetting.disableComponentLPw(className, userId)) {
21514                            return;
21515                        }
21516                        break;
21517                    case COMPONENT_ENABLED_STATE_DEFAULT:
21518                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
21519                            return;
21520                        }
21521                        break;
21522                    default:
21523                        Slog.e(TAG, "Invalid new component state: " + newState);
21524                        return;
21525                }
21526            }
21527        }
21528        synchronized (mPackages) {
21529            scheduleWritePackageRestrictionsLocked(userId);
21530            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21531            final long callingId = Binder.clearCallingIdentity();
21532            try {
21533                updateInstantAppInstallerLocked(packageName);
21534            } finally {
21535                Binder.restoreCallingIdentity(callingId);
21536            }
21537            components = mPendingBroadcasts.get(userId, packageName);
21538            final boolean newPackage = components == null;
21539            if (newPackage) {
21540                components = new ArrayList<String>();
21541            }
21542            if (!components.contains(componentName)) {
21543                components.add(componentName);
21544            }
21545            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21546                sendNow = true;
21547                // Purge entry from pending broadcast list if another one exists already
21548                // since we are sending one right away.
21549                mPendingBroadcasts.remove(userId, packageName);
21550            } else {
21551                if (newPackage) {
21552                    mPendingBroadcasts.put(userId, packageName, components);
21553                }
21554                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21555                    // Schedule a message
21556                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21557                }
21558            }
21559        }
21560
21561        long callingId = Binder.clearCallingIdentity();
21562        try {
21563            if (sendNow) {
21564                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21565                sendPackageChangedBroadcast(packageName,
21566                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21567            }
21568        } finally {
21569            Binder.restoreCallingIdentity(callingId);
21570        }
21571    }
21572
21573    @Override
21574    public void flushPackageRestrictionsAsUser(int userId) {
21575        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21576            return;
21577        }
21578        if (!sUserManager.exists(userId)) {
21579            return;
21580        }
21581        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21582                false /* checkShell */, "flushPackageRestrictions");
21583        synchronized (mPackages) {
21584            mSettings.writePackageRestrictionsLPr(userId);
21585            mDirtyUsers.remove(userId);
21586            if (mDirtyUsers.isEmpty()) {
21587                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21588            }
21589        }
21590    }
21591
21592    private void sendPackageChangedBroadcast(String packageName,
21593            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21594        if (DEBUG_INSTALL)
21595            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21596                    + componentNames);
21597        Bundle extras = new Bundle(4);
21598        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21599        String nameList[] = new String[componentNames.size()];
21600        componentNames.toArray(nameList);
21601        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21602        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21603        extras.putInt(Intent.EXTRA_UID, packageUid);
21604        // If this is not reporting a change of the overall package, then only send it
21605        // to registered receivers.  We don't want to launch a swath of apps for every
21606        // little component state change.
21607        final int flags = !componentNames.contains(packageName)
21608                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21609        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21610                new int[] {UserHandle.getUserId(packageUid)});
21611    }
21612
21613    @Override
21614    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21615        if (!sUserManager.exists(userId)) return;
21616        final int callingUid = Binder.getCallingUid();
21617        if (getInstantAppPackageName(callingUid) != null) {
21618            return;
21619        }
21620        final int permission = mContext.checkCallingOrSelfPermission(
21621                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21622        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21623        enforceCrossUserPermission(callingUid, userId,
21624                true /* requireFullPermission */, true /* checkShell */, "stop package");
21625        // writer
21626        synchronized (mPackages) {
21627            final PackageSetting ps = mSettings.mPackages.get(packageName);
21628            if (!filterAppAccessLPr(ps, callingUid, userId)
21629                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21630                            allowedByPermission, callingUid, userId)) {
21631                scheduleWritePackageRestrictionsLocked(userId);
21632            }
21633        }
21634    }
21635
21636    @Override
21637    public String getInstallerPackageName(String packageName) {
21638        final int callingUid = Binder.getCallingUid();
21639        if (getInstantAppPackageName(callingUid) != null) {
21640            return null;
21641        }
21642        // reader
21643        synchronized (mPackages) {
21644            final PackageSetting ps = mSettings.mPackages.get(packageName);
21645            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21646                return null;
21647            }
21648            return mSettings.getInstallerPackageNameLPr(packageName);
21649        }
21650    }
21651
21652    public boolean isOrphaned(String packageName) {
21653        // reader
21654        synchronized (mPackages) {
21655            return mSettings.isOrphaned(packageName);
21656        }
21657    }
21658
21659    @Override
21660    public int getApplicationEnabledSetting(String packageName, int userId) {
21661        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21662        int callingUid = Binder.getCallingUid();
21663        enforceCrossUserPermission(callingUid, userId,
21664                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21665        // reader
21666        synchronized (mPackages) {
21667            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21668                return COMPONENT_ENABLED_STATE_DISABLED;
21669            }
21670            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21671        }
21672    }
21673
21674    @Override
21675    public int getComponentEnabledSetting(ComponentName component, int userId) {
21676        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21677        int callingUid = Binder.getCallingUid();
21678        enforceCrossUserPermission(callingUid, userId,
21679                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21680        synchronized (mPackages) {
21681            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21682                    component, TYPE_UNKNOWN, userId)) {
21683                return COMPONENT_ENABLED_STATE_DISABLED;
21684            }
21685            return mSettings.getComponentEnabledSettingLPr(component, userId);
21686        }
21687    }
21688
21689    @Override
21690    public void enterSafeMode() {
21691        enforceSystemOrRoot("Only the system can request entering safe mode");
21692
21693        if (!mSystemReady) {
21694            mSafeMode = true;
21695        }
21696    }
21697
21698    @Override
21699    public void systemReady() {
21700        enforceSystemOrRoot("Only the system can claim the system is ready");
21701
21702        mSystemReady = true;
21703        final ContentResolver resolver = mContext.getContentResolver();
21704        ContentObserver co = new ContentObserver(mHandler) {
21705            @Override
21706            public void onChange(boolean selfChange) {
21707                mEphemeralAppsDisabled =
21708                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21709                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21710            }
21711        };
21712        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21713                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21714                false, co, UserHandle.USER_SYSTEM);
21715        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21716                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21717        co.onChange(true);
21718
21719        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21720        // disabled after already being started.
21721        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21722                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21723
21724        // Read the compatibilty setting when the system is ready.
21725        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21726                mContext.getContentResolver(),
21727                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21728        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21729        if (DEBUG_SETTINGS) {
21730            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21731        }
21732
21733        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21734
21735        synchronized (mPackages) {
21736            // Verify that all of the preferred activity components actually
21737            // exist.  It is possible for applications to be updated and at
21738            // that point remove a previously declared activity component that
21739            // had been set as a preferred activity.  We try to clean this up
21740            // the next time we encounter that preferred activity, but it is
21741            // possible for the user flow to never be able to return to that
21742            // situation so here we do a sanity check to make sure we haven't
21743            // left any junk around.
21744            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21745            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21746                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21747                removed.clear();
21748                for (PreferredActivity pa : pir.filterSet()) {
21749                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21750                        removed.add(pa);
21751                    }
21752                }
21753                if (removed.size() > 0) {
21754                    for (int r=0; r<removed.size(); r++) {
21755                        PreferredActivity pa = removed.get(r);
21756                        Slog.w(TAG, "Removing dangling preferred activity: "
21757                                + pa.mPref.mComponent);
21758                        pir.removeFilter(pa);
21759                    }
21760                    mSettings.writePackageRestrictionsLPr(
21761                            mSettings.mPreferredActivities.keyAt(i));
21762                }
21763            }
21764
21765            for (int userId : UserManagerService.getInstance().getUserIds()) {
21766                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21767                    grantPermissionsUserIds = ArrayUtils.appendInt(
21768                            grantPermissionsUserIds, userId);
21769                }
21770            }
21771        }
21772        sUserManager.systemReady();
21773
21774        // If we upgraded grant all default permissions before kicking off.
21775        for (int userId : grantPermissionsUserIds) {
21776            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21777        }
21778
21779        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21780            // If we did not grant default permissions, we preload from this the
21781            // default permission exceptions lazily to ensure we don't hit the
21782            // disk on a new user creation.
21783            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21784        }
21785
21786        // Now that we've scanned all packages, and granted any default
21787        // permissions, ensure permissions are updated. Beware of dragons if you
21788        // try optimizing this.
21789        synchronized (mPackages) {
21790            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21791                    UPDATE_PERMISSIONS_ALL);
21792        }
21793
21794        // Kick off any messages waiting for system ready
21795        if (mPostSystemReadyMessages != null) {
21796            for (Message msg : mPostSystemReadyMessages) {
21797                msg.sendToTarget();
21798            }
21799            mPostSystemReadyMessages = null;
21800        }
21801
21802        // Watch for external volumes that come and go over time
21803        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21804        storage.registerListener(mStorageListener);
21805
21806        mInstallerService.systemReady();
21807        mPackageDexOptimizer.systemReady();
21808
21809        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21810                StorageManagerInternal.class);
21811        StorageManagerInternal.addExternalStoragePolicy(
21812                new StorageManagerInternal.ExternalStorageMountPolicy() {
21813            @Override
21814            public int getMountMode(int uid, String packageName) {
21815                if (Process.isIsolated(uid)) {
21816                    return Zygote.MOUNT_EXTERNAL_NONE;
21817                }
21818                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21819                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21820                }
21821                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21822                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21823                }
21824                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21825                    return Zygote.MOUNT_EXTERNAL_READ;
21826                }
21827                return Zygote.MOUNT_EXTERNAL_WRITE;
21828            }
21829
21830            @Override
21831            public boolean hasExternalStorage(int uid, String packageName) {
21832                return true;
21833            }
21834        });
21835
21836        // Now that we're mostly running, clean up stale users and apps
21837        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21838        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21839
21840        if (mPrivappPermissionsViolations != null) {
21841            Slog.wtf(TAG,"Signature|privileged permissions not in "
21842                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21843            mPrivappPermissionsViolations = null;
21844        }
21845    }
21846
21847    public void waitForAppDataPrepared() {
21848        if (mPrepareAppDataFuture == null) {
21849            return;
21850        }
21851        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21852        mPrepareAppDataFuture = null;
21853    }
21854
21855    @Override
21856    public boolean isSafeMode() {
21857        // allow instant applications
21858        return mSafeMode;
21859    }
21860
21861    @Override
21862    public boolean hasSystemUidErrors() {
21863        // allow instant applications
21864        return mHasSystemUidErrors;
21865    }
21866
21867    static String arrayToString(int[] array) {
21868        StringBuffer buf = new StringBuffer(128);
21869        buf.append('[');
21870        if (array != null) {
21871            for (int i=0; i<array.length; i++) {
21872                if (i > 0) buf.append(", ");
21873                buf.append(array[i]);
21874            }
21875        }
21876        buf.append(']');
21877        return buf.toString();
21878    }
21879
21880    @Override
21881    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21882            FileDescriptor err, String[] args, ShellCallback callback,
21883            ResultReceiver resultReceiver) {
21884        (new PackageManagerShellCommand(this)).exec(
21885                this, in, out, err, args, callback, resultReceiver);
21886    }
21887
21888    @Override
21889    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21890        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21891
21892        DumpState dumpState = new DumpState();
21893        boolean fullPreferred = false;
21894        boolean checkin = false;
21895
21896        String packageName = null;
21897        ArraySet<String> permissionNames = null;
21898
21899        int opti = 0;
21900        while (opti < args.length) {
21901            String opt = args[opti];
21902            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21903                break;
21904            }
21905            opti++;
21906
21907            if ("-a".equals(opt)) {
21908                // Right now we only know how to print all.
21909            } else if ("-h".equals(opt)) {
21910                pw.println("Package manager dump options:");
21911                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21912                pw.println("    --checkin: dump for a checkin");
21913                pw.println("    -f: print details of intent filters");
21914                pw.println("    -h: print this help");
21915                pw.println("  cmd may be one of:");
21916                pw.println("    l[ibraries]: list known shared libraries");
21917                pw.println("    f[eatures]: list device features");
21918                pw.println("    k[eysets]: print known keysets");
21919                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21920                pw.println("    perm[issions]: dump permissions");
21921                pw.println("    permission [name ...]: dump declaration and use of given permission");
21922                pw.println("    pref[erred]: print preferred package settings");
21923                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21924                pw.println("    prov[iders]: dump content providers");
21925                pw.println("    p[ackages]: dump installed packages");
21926                pw.println("    s[hared-users]: dump shared user IDs");
21927                pw.println("    m[essages]: print collected runtime messages");
21928                pw.println("    v[erifiers]: print package verifier info");
21929                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21930                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21931                pw.println("    version: print database version info");
21932                pw.println("    write: write current settings now");
21933                pw.println("    installs: details about install sessions");
21934                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21935                pw.println("    dexopt: dump dexopt state");
21936                pw.println("    compiler-stats: dump compiler statistics");
21937                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21938                pw.println("    <package.name>: info about given package");
21939                return;
21940            } else if ("--checkin".equals(opt)) {
21941                checkin = true;
21942            } else if ("-f".equals(opt)) {
21943                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21944            } else if ("--proto".equals(opt)) {
21945                dumpProto(fd);
21946                return;
21947            } else {
21948                pw.println("Unknown argument: " + opt + "; use -h for help");
21949            }
21950        }
21951
21952        // Is the caller requesting to dump a particular piece of data?
21953        if (opti < args.length) {
21954            String cmd = args[opti];
21955            opti++;
21956            // Is this a package name?
21957            if ("android".equals(cmd) || cmd.contains(".")) {
21958                packageName = cmd;
21959                // When dumping a single package, we always dump all of its
21960                // filter information since the amount of data will be reasonable.
21961                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21962            } else if ("check-permission".equals(cmd)) {
21963                if (opti >= args.length) {
21964                    pw.println("Error: check-permission missing permission argument");
21965                    return;
21966                }
21967                String perm = args[opti];
21968                opti++;
21969                if (opti >= args.length) {
21970                    pw.println("Error: check-permission missing package argument");
21971                    return;
21972                }
21973
21974                String pkg = args[opti];
21975                opti++;
21976                int user = UserHandle.getUserId(Binder.getCallingUid());
21977                if (opti < args.length) {
21978                    try {
21979                        user = Integer.parseInt(args[opti]);
21980                    } catch (NumberFormatException e) {
21981                        pw.println("Error: check-permission user argument is not a number: "
21982                                + args[opti]);
21983                        return;
21984                    }
21985                }
21986
21987                // Normalize package name to handle renamed packages and static libs
21988                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21989
21990                pw.println(checkPermission(perm, pkg, user));
21991                return;
21992            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21993                dumpState.setDump(DumpState.DUMP_LIBS);
21994            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21995                dumpState.setDump(DumpState.DUMP_FEATURES);
21996            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21997                if (opti >= args.length) {
21998                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21999                            | DumpState.DUMP_SERVICE_RESOLVERS
22000                            | DumpState.DUMP_RECEIVER_RESOLVERS
22001                            | DumpState.DUMP_CONTENT_RESOLVERS);
22002                } else {
22003                    while (opti < args.length) {
22004                        String name = args[opti];
22005                        if ("a".equals(name) || "activity".equals(name)) {
22006                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22007                        } else if ("s".equals(name) || "service".equals(name)) {
22008                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22009                        } else if ("r".equals(name) || "receiver".equals(name)) {
22010                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22011                        } else if ("c".equals(name) || "content".equals(name)) {
22012                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22013                        } else {
22014                            pw.println("Error: unknown resolver table type: " + name);
22015                            return;
22016                        }
22017                        opti++;
22018                    }
22019                }
22020            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22021                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22022            } else if ("permission".equals(cmd)) {
22023                if (opti >= args.length) {
22024                    pw.println("Error: permission requires permission name");
22025                    return;
22026                }
22027                permissionNames = new ArraySet<>();
22028                while (opti < args.length) {
22029                    permissionNames.add(args[opti]);
22030                    opti++;
22031                }
22032                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22033                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22034            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22035                dumpState.setDump(DumpState.DUMP_PREFERRED);
22036            } else if ("preferred-xml".equals(cmd)) {
22037                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22038                if (opti < args.length && "--full".equals(args[opti])) {
22039                    fullPreferred = true;
22040                    opti++;
22041                }
22042            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22043                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22044            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22045                dumpState.setDump(DumpState.DUMP_PACKAGES);
22046            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22047                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22048            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22049                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22050            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22051                dumpState.setDump(DumpState.DUMP_MESSAGES);
22052            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22053                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22054            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22055                    || "intent-filter-verifiers".equals(cmd)) {
22056                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22057            } else if ("version".equals(cmd)) {
22058                dumpState.setDump(DumpState.DUMP_VERSION);
22059            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22060                dumpState.setDump(DumpState.DUMP_KEYSETS);
22061            } else if ("installs".equals(cmd)) {
22062                dumpState.setDump(DumpState.DUMP_INSTALLS);
22063            } else if ("frozen".equals(cmd)) {
22064                dumpState.setDump(DumpState.DUMP_FROZEN);
22065            } else if ("volumes".equals(cmd)) {
22066                dumpState.setDump(DumpState.DUMP_VOLUMES);
22067            } else if ("dexopt".equals(cmd)) {
22068                dumpState.setDump(DumpState.DUMP_DEXOPT);
22069            } else if ("compiler-stats".equals(cmd)) {
22070                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22071            } else if ("changes".equals(cmd)) {
22072                dumpState.setDump(DumpState.DUMP_CHANGES);
22073            } else if ("write".equals(cmd)) {
22074                synchronized (mPackages) {
22075                    mSettings.writeLPr();
22076                    pw.println("Settings written.");
22077                    return;
22078                }
22079            }
22080        }
22081
22082        if (checkin) {
22083            pw.println("vers,1");
22084        }
22085
22086        // reader
22087        synchronized (mPackages) {
22088            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22089                if (!checkin) {
22090                    if (dumpState.onTitlePrinted())
22091                        pw.println();
22092                    pw.println("Database versions:");
22093                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22094                }
22095            }
22096
22097            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22098                if (!checkin) {
22099                    if (dumpState.onTitlePrinted())
22100                        pw.println();
22101                    pw.println("Verifiers:");
22102                    pw.print("  Required: ");
22103                    pw.print(mRequiredVerifierPackage);
22104                    pw.print(" (uid=");
22105                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22106                            UserHandle.USER_SYSTEM));
22107                    pw.println(")");
22108                } else if (mRequiredVerifierPackage != null) {
22109                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22110                    pw.print(",");
22111                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22112                            UserHandle.USER_SYSTEM));
22113                }
22114            }
22115
22116            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22117                    packageName == null) {
22118                if (mIntentFilterVerifierComponent != null) {
22119                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22120                    if (!checkin) {
22121                        if (dumpState.onTitlePrinted())
22122                            pw.println();
22123                        pw.println("Intent Filter Verifier:");
22124                        pw.print("  Using: ");
22125                        pw.print(verifierPackageName);
22126                        pw.print(" (uid=");
22127                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22128                                UserHandle.USER_SYSTEM));
22129                        pw.println(")");
22130                    } else if (verifierPackageName != null) {
22131                        pw.print("ifv,"); pw.print(verifierPackageName);
22132                        pw.print(",");
22133                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22134                                UserHandle.USER_SYSTEM));
22135                    }
22136                } else {
22137                    pw.println();
22138                    pw.println("No Intent Filter Verifier available!");
22139                }
22140            }
22141
22142            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22143                boolean printedHeader = false;
22144                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22145                while (it.hasNext()) {
22146                    String libName = it.next();
22147                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22148                    if (versionedLib == null) {
22149                        continue;
22150                    }
22151                    final int versionCount = versionedLib.size();
22152                    for (int i = 0; i < versionCount; i++) {
22153                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22154                        if (!checkin) {
22155                            if (!printedHeader) {
22156                                if (dumpState.onTitlePrinted())
22157                                    pw.println();
22158                                pw.println("Libraries:");
22159                                printedHeader = true;
22160                            }
22161                            pw.print("  ");
22162                        } else {
22163                            pw.print("lib,");
22164                        }
22165                        pw.print(libEntry.info.getName());
22166                        if (libEntry.info.isStatic()) {
22167                            pw.print(" version=" + libEntry.info.getVersion());
22168                        }
22169                        if (!checkin) {
22170                            pw.print(" -> ");
22171                        }
22172                        if (libEntry.path != null) {
22173                            pw.print(" (jar) ");
22174                            pw.print(libEntry.path);
22175                        } else {
22176                            pw.print(" (apk) ");
22177                            pw.print(libEntry.apk);
22178                        }
22179                        pw.println();
22180                    }
22181                }
22182            }
22183
22184            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22185                if (dumpState.onTitlePrinted())
22186                    pw.println();
22187                if (!checkin) {
22188                    pw.println("Features:");
22189                }
22190
22191                synchronized (mAvailableFeatures) {
22192                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22193                        if (checkin) {
22194                            pw.print("feat,");
22195                            pw.print(feat.name);
22196                            pw.print(",");
22197                            pw.println(feat.version);
22198                        } else {
22199                            pw.print("  ");
22200                            pw.print(feat.name);
22201                            if (feat.version > 0) {
22202                                pw.print(" version=");
22203                                pw.print(feat.version);
22204                            }
22205                            pw.println();
22206                        }
22207                    }
22208                }
22209            }
22210
22211            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22212                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22213                        : "Activity Resolver Table:", "  ", packageName,
22214                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22215                    dumpState.setTitlePrinted(true);
22216                }
22217            }
22218            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22219                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22220                        : "Receiver Resolver Table:", "  ", packageName,
22221                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22222                    dumpState.setTitlePrinted(true);
22223                }
22224            }
22225            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22226                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22227                        : "Service Resolver Table:", "  ", packageName,
22228                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22229                    dumpState.setTitlePrinted(true);
22230                }
22231            }
22232            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22233                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22234                        : "Provider Resolver Table:", "  ", packageName,
22235                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22236                    dumpState.setTitlePrinted(true);
22237                }
22238            }
22239
22240            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22241                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22242                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22243                    int user = mSettings.mPreferredActivities.keyAt(i);
22244                    if (pir.dump(pw,
22245                            dumpState.getTitlePrinted()
22246                                ? "\nPreferred Activities User " + user + ":"
22247                                : "Preferred Activities User " + user + ":", "  ",
22248                            packageName, true, false)) {
22249                        dumpState.setTitlePrinted(true);
22250                    }
22251                }
22252            }
22253
22254            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22255                pw.flush();
22256                FileOutputStream fout = new FileOutputStream(fd);
22257                BufferedOutputStream str = new BufferedOutputStream(fout);
22258                XmlSerializer serializer = new FastXmlSerializer();
22259                try {
22260                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22261                    serializer.startDocument(null, true);
22262                    serializer.setFeature(
22263                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22264                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22265                    serializer.endDocument();
22266                    serializer.flush();
22267                } catch (IllegalArgumentException e) {
22268                    pw.println("Failed writing: " + e);
22269                } catch (IllegalStateException e) {
22270                    pw.println("Failed writing: " + e);
22271                } catch (IOException e) {
22272                    pw.println("Failed writing: " + e);
22273                }
22274            }
22275
22276            if (!checkin
22277                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22278                    && packageName == null) {
22279                pw.println();
22280                int count = mSettings.mPackages.size();
22281                if (count == 0) {
22282                    pw.println("No applications!");
22283                    pw.println();
22284                } else {
22285                    final String prefix = "  ";
22286                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22287                    if (allPackageSettings.size() == 0) {
22288                        pw.println("No domain preferred apps!");
22289                        pw.println();
22290                    } else {
22291                        pw.println("App verification status:");
22292                        pw.println();
22293                        count = 0;
22294                        for (PackageSetting ps : allPackageSettings) {
22295                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22296                            if (ivi == null || ivi.getPackageName() == null) continue;
22297                            pw.println(prefix + "Package: " + ivi.getPackageName());
22298                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22299                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22300                            pw.println();
22301                            count++;
22302                        }
22303                        if (count == 0) {
22304                            pw.println(prefix + "No app verification established.");
22305                            pw.println();
22306                        }
22307                        for (int userId : sUserManager.getUserIds()) {
22308                            pw.println("App linkages for user " + userId + ":");
22309                            pw.println();
22310                            count = 0;
22311                            for (PackageSetting ps : allPackageSettings) {
22312                                final long status = ps.getDomainVerificationStatusForUser(userId);
22313                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22314                                        && !DEBUG_DOMAIN_VERIFICATION) {
22315                                    continue;
22316                                }
22317                                pw.println(prefix + "Package: " + ps.name);
22318                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22319                                String statusStr = IntentFilterVerificationInfo.
22320                                        getStatusStringFromValue(status);
22321                                pw.println(prefix + "Status:  " + statusStr);
22322                                pw.println();
22323                                count++;
22324                            }
22325                            if (count == 0) {
22326                                pw.println(prefix + "No configured app linkages.");
22327                                pw.println();
22328                            }
22329                        }
22330                    }
22331                }
22332            }
22333
22334            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22335                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22336                if (packageName == null && permissionNames == null) {
22337                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22338                        if (iperm == 0) {
22339                            if (dumpState.onTitlePrinted())
22340                                pw.println();
22341                            pw.println("AppOp Permissions:");
22342                        }
22343                        pw.print("  AppOp Permission ");
22344                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22345                        pw.println(":");
22346                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22347                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22348                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22349                        }
22350                    }
22351                }
22352            }
22353
22354            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22355                boolean printedSomething = false;
22356                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22357                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22358                        continue;
22359                    }
22360                    if (!printedSomething) {
22361                        if (dumpState.onTitlePrinted())
22362                            pw.println();
22363                        pw.println("Registered ContentProviders:");
22364                        printedSomething = true;
22365                    }
22366                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22367                    pw.print("    "); pw.println(p.toString());
22368                }
22369                printedSomething = false;
22370                for (Map.Entry<String, PackageParser.Provider> entry :
22371                        mProvidersByAuthority.entrySet()) {
22372                    PackageParser.Provider p = entry.getValue();
22373                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22374                        continue;
22375                    }
22376                    if (!printedSomething) {
22377                        if (dumpState.onTitlePrinted())
22378                            pw.println();
22379                        pw.println("ContentProvider Authorities:");
22380                        printedSomething = true;
22381                    }
22382                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22383                    pw.print("    "); pw.println(p.toString());
22384                    if (p.info != null && p.info.applicationInfo != null) {
22385                        final String appInfo = p.info.applicationInfo.toString();
22386                        pw.print("      applicationInfo="); pw.println(appInfo);
22387                    }
22388                }
22389            }
22390
22391            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22392                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22393            }
22394
22395            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22396                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22397            }
22398
22399            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22400                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22401            }
22402
22403            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22404                if (dumpState.onTitlePrinted()) pw.println();
22405                pw.println("Package Changes:");
22406                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22407                final int K = mChangedPackages.size();
22408                for (int i = 0; i < K; i++) {
22409                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22410                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22411                    final int N = changes.size();
22412                    if (N == 0) {
22413                        pw.print("    "); pw.println("No packages changed");
22414                    } else {
22415                        for (int j = 0; j < N; j++) {
22416                            final String pkgName = changes.valueAt(j);
22417                            final int sequenceNumber = changes.keyAt(j);
22418                            pw.print("    ");
22419                            pw.print("seq=");
22420                            pw.print(sequenceNumber);
22421                            pw.print(", package=");
22422                            pw.println(pkgName);
22423                        }
22424                    }
22425                }
22426            }
22427
22428            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22429                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22430            }
22431
22432            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22433                // XXX should handle packageName != null by dumping only install data that
22434                // the given package is involved with.
22435                if (dumpState.onTitlePrinted()) pw.println();
22436
22437                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22438                ipw.println();
22439                ipw.println("Frozen packages:");
22440                ipw.increaseIndent();
22441                if (mFrozenPackages.size() == 0) {
22442                    ipw.println("(none)");
22443                } else {
22444                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22445                        ipw.println(mFrozenPackages.valueAt(i));
22446                    }
22447                }
22448                ipw.decreaseIndent();
22449            }
22450
22451            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22452                if (dumpState.onTitlePrinted()) pw.println();
22453
22454                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22455                ipw.println();
22456                ipw.println("Loaded volumes:");
22457                ipw.increaseIndent();
22458                if (mLoadedVolumes.size() == 0) {
22459                    ipw.println("(none)");
22460                } else {
22461                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22462                        ipw.println(mLoadedVolumes.valueAt(i));
22463                    }
22464                }
22465                ipw.decreaseIndent();
22466            }
22467
22468            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22469                if (dumpState.onTitlePrinted()) pw.println();
22470                dumpDexoptStateLPr(pw, packageName);
22471            }
22472
22473            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22474                if (dumpState.onTitlePrinted()) pw.println();
22475                dumpCompilerStatsLPr(pw, packageName);
22476            }
22477
22478            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22479                if (dumpState.onTitlePrinted()) pw.println();
22480                mSettings.dumpReadMessagesLPr(pw, dumpState);
22481
22482                pw.println();
22483                pw.println("Package warning messages:");
22484                BufferedReader in = null;
22485                String line = null;
22486                try {
22487                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22488                    while ((line = in.readLine()) != null) {
22489                        if (line.contains("ignored: updated version")) continue;
22490                        pw.println(line);
22491                    }
22492                } catch (IOException ignored) {
22493                } finally {
22494                    IoUtils.closeQuietly(in);
22495                }
22496            }
22497
22498            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22499                BufferedReader in = null;
22500                String line = null;
22501                try {
22502                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22503                    while ((line = in.readLine()) != null) {
22504                        if (line.contains("ignored: updated version")) continue;
22505                        pw.print("msg,");
22506                        pw.println(line);
22507                    }
22508                } catch (IOException ignored) {
22509                } finally {
22510                    IoUtils.closeQuietly(in);
22511                }
22512            }
22513        }
22514
22515        // PackageInstaller should be called outside of mPackages lock
22516        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22517            // XXX should handle packageName != null by dumping only install data that
22518            // the given package is involved with.
22519            if (dumpState.onTitlePrinted()) pw.println();
22520            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22521        }
22522    }
22523
22524    private void dumpProto(FileDescriptor fd) {
22525        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22526
22527        synchronized (mPackages) {
22528            final long requiredVerifierPackageToken =
22529                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22530            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22531            proto.write(
22532                    PackageServiceDumpProto.PackageShortProto.UID,
22533                    getPackageUid(
22534                            mRequiredVerifierPackage,
22535                            MATCH_DEBUG_TRIAGED_MISSING,
22536                            UserHandle.USER_SYSTEM));
22537            proto.end(requiredVerifierPackageToken);
22538
22539            if (mIntentFilterVerifierComponent != null) {
22540                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22541                final long verifierPackageToken =
22542                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22543                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22544                proto.write(
22545                        PackageServiceDumpProto.PackageShortProto.UID,
22546                        getPackageUid(
22547                                verifierPackageName,
22548                                MATCH_DEBUG_TRIAGED_MISSING,
22549                                UserHandle.USER_SYSTEM));
22550                proto.end(verifierPackageToken);
22551            }
22552
22553            dumpSharedLibrariesProto(proto);
22554            dumpFeaturesProto(proto);
22555            mSettings.dumpPackagesProto(proto);
22556            mSettings.dumpSharedUsersProto(proto);
22557            dumpMessagesProto(proto);
22558        }
22559        proto.flush();
22560    }
22561
22562    private void dumpMessagesProto(ProtoOutputStream proto) {
22563        BufferedReader in = null;
22564        String line = null;
22565        try {
22566            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22567            while ((line = in.readLine()) != null) {
22568                if (line.contains("ignored: updated version")) continue;
22569                proto.write(PackageServiceDumpProto.MESSAGES, line);
22570            }
22571        } catch (IOException ignored) {
22572        } finally {
22573            IoUtils.closeQuietly(in);
22574        }
22575    }
22576
22577    private void dumpFeaturesProto(ProtoOutputStream proto) {
22578        synchronized (mAvailableFeatures) {
22579            final int count = mAvailableFeatures.size();
22580            for (int i = 0; i < count; i++) {
22581                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22582                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22583                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22584                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22585                proto.end(featureToken);
22586            }
22587        }
22588    }
22589
22590    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22591        final int count = mSharedLibraries.size();
22592        for (int i = 0; i < count; i++) {
22593            final String libName = mSharedLibraries.keyAt(i);
22594            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22595            if (versionedLib == null) {
22596                continue;
22597            }
22598            final int versionCount = versionedLib.size();
22599            for (int j = 0; j < versionCount; j++) {
22600                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22601                final long sharedLibraryToken =
22602                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22603                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22604                final boolean isJar = (libEntry.path != null);
22605                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22606                if (isJar) {
22607                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22608                } else {
22609                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22610                }
22611                proto.end(sharedLibraryToken);
22612            }
22613        }
22614    }
22615
22616    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22617        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22618        ipw.println();
22619        ipw.println("Dexopt state:");
22620        ipw.increaseIndent();
22621        Collection<PackageParser.Package> packages = null;
22622        if (packageName != null) {
22623            PackageParser.Package targetPackage = mPackages.get(packageName);
22624            if (targetPackage != null) {
22625                packages = Collections.singletonList(targetPackage);
22626            } else {
22627                ipw.println("Unable to find package: " + packageName);
22628                return;
22629            }
22630        } else {
22631            packages = mPackages.values();
22632        }
22633
22634        for (PackageParser.Package pkg : packages) {
22635            ipw.println("[" + pkg.packageName + "]");
22636            ipw.increaseIndent();
22637            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22638                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22639            ipw.decreaseIndent();
22640        }
22641    }
22642
22643    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22644        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22645        ipw.println();
22646        ipw.println("Compiler stats:");
22647        ipw.increaseIndent();
22648        Collection<PackageParser.Package> packages = null;
22649        if (packageName != null) {
22650            PackageParser.Package targetPackage = mPackages.get(packageName);
22651            if (targetPackage != null) {
22652                packages = Collections.singletonList(targetPackage);
22653            } else {
22654                ipw.println("Unable to find package: " + packageName);
22655                return;
22656            }
22657        } else {
22658            packages = mPackages.values();
22659        }
22660
22661        for (PackageParser.Package pkg : packages) {
22662            ipw.println("[" + pkg.packageName + "]");
22663            ipw.increaseIndent();
22664
22665            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22666            if (stats == null) {
22667                ipw.println("(No recorded stats)");
22668            } else {
22669                stats.dump(ipw);
22670            }
22671            ipw.decreaseIndent();
22672        }
22673    }
22674
22675    private String dumpDomainString(String packageName) {
22676        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22677                .getList();
22678        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22679
22680        ArraySet<String> result = new ArraySet<>();
22681        if (iviList.size() > 0) {
22682            for (IntentFilterVerificationInfo ivi : iviList) {
22683                for (String host : ivi.getDomains()) {
22684                    result.add(host);
22685                }
22686            }
22687        }
22688        if (filters != null && filters.size() > 0) {
22689            for (IntentFilter filter : filters) {
22690                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22691                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22692                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22693                    result.addAll(filter.getHostsList());
22694                }
22695            }
22696        }
22697
22698        StringBuilder sb = new StringBuilder(result.size() * 16);
22699        for (String domain : result) {
22700            if (sb.length() > 0) sb.append(" ");
22701            sb.append(domain);
22702        }
22703        return sb.toString();
22704    }
22705
22706    // ------- apps on sdcard specific code -------
22707    static final boolean DEBUG_SD_INSTALL = false;
22708
22709    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22710
22711    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22712
22713    private boolean mMediaMounted = false;
22714
22715    static String getEncryptKey() {
22716        try {
22717            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22718                    SD_ENCRYPTION_KEYSTORE_NAME);
22719            if (sdEncKey == null) {
22720                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22721                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22722                if (sdEncKey == null) {
22723                    Slog.e(TAG, "Failed to create encryption keys");
22724                    return null;
22725                }
22726            }
22727            return sdEncKey;
22728        } catch (NoSuchAlgorithmException nsae) {
22729            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22730            return null;
22731        } catch (IOException ioe) {
22732            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22733            return null;
22734        }
22735    }
22736
22737    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22738            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22739        final int size = infos.size();
22740        final String[] packageNames = new String[size];
22741        final int[] packageUids = new int[size];
22742        for (int i = 0; i < size; i++) {
22743            final ApplicationInfo info = infos.get(i);
22744            packageNames[i] = info.packageName;
22745            packageUids[i] = info.uid;
22746        }
22747        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22748                finishedReceiver);
22749    }
22750
22751    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22752            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22753        sendResourcesChangedBroadcast(mediaStatus, replacing,
22754                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22755    }
22756
22757    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22758            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22759        int size = pkgList.length;
22760        if (size > 0) {
22761            // Send broadcasts here
22762            Bundle extras = new Bundle();
22763            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22764            if (uidArr != null) {
22765                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22766            }
22767            if (replacing) {
22768                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22769            }
22770            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22771                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22772            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22773        }
22774    }
22775
22776    private void loadPrivatePackages(final VolumeInfo vol) {
22777        mHandler.post(new Runnable() {
22778            @Override
22779            public void run() {
22780                loadPrivatePackagesInner(vol);
22781            }
22782        });
22783    }
22784
22785    private void loadPrivatePackagesInner(VolumeInfo vol) {
22786        final String volumeUuid = vol.fsUuid;
22787        if (TextUtils.isEmpty(volumeUuid)) {
22788            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22789            return;
22790        }
22791
22792        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22793        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22794        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22795
22796        final VersionInfo ver;
22797        final List<PackageSetting> packages;
22798        synchronized (mPackages) {
22799            ver = mSettings.findOrCreateVersion(volumeUuid);
22800            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22801        }
22802
22803        for (PackageSetting ps : packages) {
22804            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22805            synchronized (mInstallLock) {
22806                final PackageParser.Package pkg;
22807                try {
22808                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22809                    loaded.add(pkg.applicationInfo);
22810
22811                } catch (PackageManagerException e) {
22812                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22813                }
22814
22815                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22816                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22817                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22818                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22819                }
22820            }
22821        }
22822
22823        // Reconcile app data for all started/unlocked users
22824        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22825        final UserManager um = mContext.getSystemService(UserManager.class);
22826        UserManagerInternal umInternal = getUserManagerInternal();
22827        for (UserInfo user : um.getUsers()) {
22828            final int flags;
22829            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22830                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22831            } else if (umInternal.isUserRunning(user.id)) {
22832                flags = StorageManager.FLAG_STORAGE_DE;
22833            } else {
22834                continue;
22835            }
22836
22837            try {
22838                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22839                synchronized (mInstallLock) {
22840                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22841                }
22842            } catch (IllegalStateException e) {
22843                // Device was probably ejected, and we'll process that event momentarily
22844                Slog.w(TAG, "Failed to prepare storage: " + e);
22845            }
22846        }
22847
22848        synchronized (mPackages) {
22849            int updateFlags = UPDATE_PERMISSIONS_ALL;
22850            if (ver.sdkVersion != mSdkVersion) {
22851                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22852                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22853                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22854            }
22855            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22856
22857            // Yay, everything is now upgraded
22858            ver.forceCurrent();
22859
22860            mSettings.writeLPr();
22861        }
22862
22863        for (PackageFreezer freezer : freezers) {
22864            freezer.close();
22865        }
22866
22867        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22868        sendResourcesChangedBroadcast(true, false, loaded, null);
22869        mLoadedVolumes.add(vol.getId());
22870    }
22871
22872    private void unloadPrivatePackages(final VolumeInfo vol) {
22873        mHandler.post(new Runnable() {
22874            @Override
22875            public void run() {
22876                unloadPrivatePackagesInner(vol);
22877            }
22878        });
22879    }
22880
22881    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22882        final String volumeUuid = vol.fsUuid;
22883        if (TextUtils.isEmpty(volumeUuid)) {
22884            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22885            return;
22886        }
22887
22888        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22889        synchronized (mInstallLock) {
22890        synchronized (mPackages) {
22891            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22892            for (PackageSetting ps : packages) {
22893                if (ps.pkg == null) continue;
22894
22895                final ApplicationInfo info = ps.pkg.applicationInfo;
22896                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22897                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22898
22899                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22900                        "unloadPrivatePackagesInner")) {
22901                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22902                            false, null)) {
22903                        unloaded.add(info);
22904                    } else {
22905                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22906                    }
22907                }
22908
22909                // Try very hard to release any references to this package
22910                // so we don't risk the system server being killed due to
22911                // open FDs
22912                AttributeCache.instance().removePackage(ps.name);
22913            }
22914
22915            mSettings.writeLPr();
22916        }
22917        }
22918
22919        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22920        sendResourcesChangedBroadcast(false, false, unloaded, null);
22921        mLoadedVolumes.remove(vol.getId());
22922
22923        // Try very hard to release any references to this path so we don't risk
22924        // the system server being killed due to open FDs
22925        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22926
22927        for (int i = 0; i < 3; i++) {
22928            System.gc();
22929            System.runFinalization();
22930        }
22931    }
22932
22933    private void assertPackageKnown(String volumeUuid, String packageName)
22934            throws PackageManagerException {
22935        synchronized (mPackages) {
22936            // Normalize package name to handle renamed packages
22937            packageName = normalizePackageNameLPr(packageName);
22938
22939            final PackageSetting ps = mSettings.mPackages.get(packageName);
22940            if (ps == null) {
22941                throw new PackageManagerException("Package " + packageName + " is unknown");
22942            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22943                throw new PackageManagerException(
22944                        "Package " + packageName + " found on unknown volume " + volumeUuid
22945                                + "; expected volume " + ps.volumeUuid);
22946            }
22947        }
22948    }
22949
22950    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22951            throws PackageManagerException {
22952        synchronized (mPackages) {
22953            // Normalize package name to handle renamed packages
22954            packageName = normalizePackageNameLPr(packageName);
22955
22956            final PackageSetting ps = mSettings.mPackages.get(packageName);
22957            if (ps == null) {
22958                throw new PackageManagerException("Package " + packageName + " is unknown");
22959            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22960                throw new PackageManagerException(
22961                        "Package " + packageName + " found on unknown volume " + volumeUuid
22962                                + "; expected volume " + ps.volumeUuid);
22963            } else if (!ps.getInstalled(userId)) {
22964                throw new PackageManagerException(
22965                        "Package " + packageName + " not installed for user " + userId);
22966            }
22967        }
22968    }
22969
22970    private List<String> collectAbsoluteCodePaths() {
22971        synchronized (mPackages) {
22972            List<String> codePaths = new ArrayList<>();
22973            final int packageCount = mSettings.mPackages.size();
22974            for (int i = 0; i < packageCount; i++) {
22975                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22976                codePaths.add(ps.codePath.getAbsolutePath());
22977            }
22978            return codePaths;
22979        }
22980    }
22981
22982    /**
22983     * Examine all apps present on given mounted volume, and destroy apps that
22984     * aren't expected, either due to uninstallation or reinstallation on
22985     * another volume.
22986     */
22987    private void reconcileApps(String volumeUuid) {
22988        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22989        List<File> filesToDelete = null;
22990
22991        final File[] files = FileUtils.listFilesOrEmpty(
22992                Environment.getDataAppDirectory(volumeUuid));
22993        for (File file : files) {
22994            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22995                    && !PackageInstallerService.isStageName(file.getName());
22996            if (!isPackage) {
22997                // Ignore entries which are not packages
22998                continue;
22999            }
23000
23001            String absolutePath = file.getAbsolutePath();
23002
23003            boolean pathValid = false;
23004            final int absoluteCodePathCount = absoluteCodePaths.size();
23005            for (int i = 0; i < absoluteCodePathCount; i++) {
23006                String absoluteCodePath = absoluteCodePaths.get(i);
23007                if (absolutePath.startsWith(absoluteCodePath)) {
23008                    pathValid = true;
23009                    break;
23010                }
23011            }
23012
23013            if (!pathValid) {
23014                if (filesToDelete == null) {
23015                    filesToDelete = new ArrayList<>();
23016                }
23017                filesToDelete.add(file);
23018            }
23019        }
23020
23021        if (filesToDelete != null) {
23022            final int fileToDeleteCount = filesToDelete.size();
23023            for (int i = 0; i < fileToDeleteCount; i++) {
23024                File fileToDelete = filesToDelete.get(i);
23025                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23026                synchronized (mInstallLock) {
23027                    removeCodePathLI(fileToDelete);
23028                }
23029            }
23030        }
23031    }
23032
23033    /**
23034     * Reconcile all app data for the given user.
23035     * <p>
23036     * Verifies that directories exist and that ownership and labeling is
23037     * correct for all installed apps on all mounted volumes.
23038     */
23039    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23040        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23041        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23042            final String volumeUuid = vol.getFsUuid();
23043            synchronized (mInstallLock) {
23044                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23045            }
23046        }
23047    }
23048
23049    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23050            boolean migrateAppData) {
23051        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23052    }
23053
23054    /**
23055     * Reconcile all app data on given mounted volume.
23056     * <p>
23057     * Destroys app data that isn't expected, either due to uninstallation or
23058     * reinstallation on another volume.
23059     * <p>
23060     * Verifies that directories exist and that ownership and labeling is
23061     * correct for all installed apps.
23062     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23063     */
23064    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23065            boolean migrateAppData, boolean onlyCoreApps) {
23066        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23067                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23068        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23069
23070        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23071        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23072
23073        // First look for stale data that doesn't belong, and check if things
23074        // have changed since we did our last restorecon
23075        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23076            if (StorageManager.isFileEncryptedNativeOrEmulated()
23077                    && !StorageManager.isUserKeyUnlocked(userId)) {
23078                throw new RuntimeException(
23079                        "Yikes, someone asked us to reconcile CE storage while " + userId
23080                                + " was still locked; this would have caused massive data loss!");
23081            }
23082
23083            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23084            for (File file : files) {
23085                final String packageName = file.getName();
23086                try {
23087                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23088                } catch (PackageManagerException e) {
23089                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23090                    try {
23091                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23092                                StorageManager.FLAG_STORAGE_CE, 0);
23093                    } catch (InstallerException e2) {
23094                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23095                    }
23096                }
23097            }
23098        }
23099        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23100            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23101            for (File file : files) {
23102                final String packageName = file.getName();
23103                try {
23104                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23105                } catch (PackageManagerException e) {
23106                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23107                    try {
23108                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23109                                StorageManager.FLAG_STORAGE_DE, 0);
23110                    } catch (InstallerException e2) {
23111                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23112                    }
23113                }
23114            }
23115        }
23116
23117        // Ensure that data directories are ready to roll for all packages
23118        // installed for this volume and user
23119        final List<PackageSetting> packages;
23120        synchronized (mPackages) {
23121            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23122        }
23123        int preparedCount = 0;
23124        for (PackageSetting ps : packages) {
23125            final String packageName = ps.name;
23126            if (ps.pkg == null) {
23127                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23128                // TODO: might be due to legacy ASEC apps; we should circle back
23129                // and reconcile again once they're scanned
23130                continue;
23131            }
23132            // Skip non-core apps if requested
23133            if (onlyCoreApps && !ps.pkg.coreApp) {
23134                result.add(packageName);
23135                continue;
23136            }
23137
23138            if (ps.getInstalled(userId)) {
23139                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23140                preparedCount++;
23141            }
23142        }
23143
23144        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23145        return result;
23146    }
23147
23148    /**
23149     * Prepare app data for the given app just after it was installed or
23150     * upgraded. This method carefully only touches users that it's installed
23151     * for, and it forces a restorecon to handle any seinfo changes.
23152     * <p>
23153     * Verifies that directories exist and that ownership and labeling is
23154     * correct for all installed apps. If there is an ownership mismatch, it
23155     * will try recovering system apps by wiping data; third-party app data is
23156     * left intact.
23157     * <p>
23158     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23159     */
23160    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23161        final PackageSetting ps;
23162        synchronized (mPackages) {
23163            ps = mSettings.mPackages.get(pkg.packageName);
23164            mSettings.writeKernelMappingLPr(ps);
23165        }
23166
23167        final UserManager um = mContext.getSystemService(UserManager.class);
23168        UserManagerInternal umInternal = getUserManagerInternal();
23169        for (UserInfo user : um.getUsers()) {
23170            final int flags;
23171            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23172                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23173            } else if (umInternal.isUserRunning(user.id)) {
23174                flags = StorageManager.FLAG_STORAGE_DE;
23175            } else {
23176                continue;
23177            }
23178
23179            if (ps.getInstalled(user.id)) {
23180                // TODO: when user data is locked, mark that we're still dirty
23181                prepareAppDataLIF(pkg, user.id, flags);
23182            }
23183        }
23184    }
23185
23186    /**
23187     * Prepare app data for the given app.
23188     * <p>
23189     * Verifies that directories exist and that ownership and labeling is
23190     * correct for all installed apps. If there is an ownership mismatch, this
23191     * will try recovering system apps by wiping data; third-party app data is
23192     * left intact.
23193     */
23194    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23195        if (pkg == null) {
23196            Slog.wtf(TAG, "Package was null!", new Throwable());
23197            return;
23198        }
23199        prepareAppDataLeafLIF(pkg, userId, flags);
23200        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23201        for (int i = 0; i < childCount; i++) {
23202            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23203        }
23204    }
23205
23206    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23207            boolean maybeMigrateAppData) {
23208        prepareAppDataLIF(pkg, userId, flags);
23209
23210        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23211            // We may have just shuffled around app data directories, so
23212            // prepare them one more time
23213            prepareAppDataLIF(pkg, userId, flags);
23214        }
23215    }
23216
23217    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23218        if (DEBUG_APP_DATA) {
23219            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23220                    + Integer.toHexString(flags));
23221        }
23222
23223        final String volumeUuid = pkg.volumeUuid;
23224        final String packageName = pkg.packageName;
23225        final ApplicationInfo app = pkg.applicationInfo;
23226        final int appId = UserHandle.getAppId(app.uid);
23227
23228        Preconditions.checkNotNull(app.seInfo);
23229
23230        long ceDataInode = -1;
23231        try {
23232            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23233                    appId, app.seInfo, app.targetSdkVersion);
23234        } catch (InstallerException e) {
23235            if (app.isSystemApp()) {
23236                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23237                        + ", but trying to recover: " + e);
23238                destroyAppDataLeafLIF(pkg, userId, flags);
23239                try {
23240                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23241                            appId, app.seInfo, app.targetSdkVersion);
23242                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23243                } catch (InstallerException e2) {
23244                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23245                }
23246            } else {
23247                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23248            }
23249        }
23250
23251        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23252            // TODO: mark this structure as dirty so we persist it!
23253            synchronized (mPackages) {
23254                final PackageSetting ps = mSettings.mPackages.get(packageName);
23255                if (ps != null) {
23256                    ps.setCeDataInode(ceDataInode, userId);
23257                }
23258            }
23259        }
23260
23261        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23262    }
23263
23264    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23265        if (pkg == null) {
23266            Slog.wtf(TAG, "Package was null!", new Throwable());
23267            return;
23268        }
23269        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23270        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23271        for (int i = 0; i < childCount; i++) {
23272            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23273        }
23274    }
23275
23276    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23277        final String volumeUuid = pkg.volumeUuid;
23278        final String packageName = pkg.packageName;
23279        final ApplicationInfo app = pkg.applicationInfo;
23280
23281        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23282            // Create a native library symlink only if we have native libraries
23283            // and if the native libraries are 32 bit libraries. We do not provide
23284            // this symlink for 64 bit libraries.
23285            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23286                final String nativeLibPath = app.nativeLibraryDir;
23287                try {
23288                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23289                            nativeLibPath, userId);
23290                } catch (InstallerException e) {
23291                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23292                }
23293            }
23294        }
23295    }
23296
23297    /**
23298     * For system apps on non-FBE devices, this method migrates any existing
23299     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23300     * requested by the app.
23301     */
23302    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23303        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23304                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23305            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23306                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23307            try {
23308                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23309                        storageTarget);
23310            } catch (InstallerException e) {
23311                logCriticalInfo(Log.WARN,
23312                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23313            }
23314            return true;
23315        } else {
23316            return false;
23317        }
23318    }
23319
23320    public PackageFreezer freezePackage(String packageName, String killReason) {
23321        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23322    }
23323
23324    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23325        return new PackageFreezer(packageName, userId, killReason);
23326    }
23327
23328    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23329            String killReason) {
23330        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23331    }
23332
23333    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23334            String killReason) {
23335        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23336            return new PackageFreezer();
23337        } else {
23338            return freezePackage(packageName, userId, killReason);
23339        }
23340    }
23341
23342    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23343            String killReason) {
23344        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23345    }
23346
23347    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23348            String killReason) {
23349        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23350            return new PackageFreezer();
23351        } else {
23352            return freezePackage(packageName, userId, killReason);
23353        }
23354    }
23355
23356    /**
23357     * Class that freezes and kills the given package upon creation, and
23358     * unfreezes it upon closing. This is typically used when doing surgery on
23359     * app code/data to prevent the app from running while you're working.
23360     */
23361    private class PackageFreezer implements AutoCloseable {
23362        private final String mPackageName;
23363        private final PackageFreezer[] mChildren;
23364
23365        private final boolean mWeFroze;
23366
23367        private final AtomicBoolean mClosed = new AtomicBoolean();
23368        private final CloseGuard mCloseGuard = CloseGuard.get();
23369
23370        /**
23371         * Create and return a stub freezer that doesn't actually do anything,
23372         * typically used when someone requested
23373         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23374         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23375         */
23376        public PackageFreezer() {
23377            mPackageName = null;
23378            mChildren = null;
23379            mWeFroze = false;
23380            mCloseGuard.open("close");
23381        }
23382
23383        public PackageFreezer(String packageName, int userId, String killReason) {
23384            synchronized (mPackages) {
23385                mPackageName = packageName;
23386                mWeFroze = mFrozenPackages.add(mPackageName);
23387
23388                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23389                if (ps != null) {
23390                    killApplication(ps.name, ps.appId, userId, killReason);
23391                }
23392
23393                final PackageParser.Package p = mPackages.get(packageName);
23394                if (p != null && p.childPackages != null) {
23395                    final int N = p.childPackages.size();
23396                    mChildren = new PackageFreezer[N];
23397                    for (int i = 0; i < N; i++) {
23398                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23399                                userId, killReason);
23400                    }
23401                } else {
23402                    mChildren = null;
23403                }
23404            }
23405            mCloseGuard.open("close");
23406        }
23407
23408        @Override
23409        protected void finalize() throws Throwable {
23410            try {
23411                if (mCloseGuard != null) {
23412                    mCloseGuard.warnIfOpen();
23413                }
23414
23415                close();
23416            } finally {
23417                super.finalize();
23418            }
23419        }
23420
23421        @Override
23422        public void close() {
23423            mCloseGuard.close();
23424            if (mClosed.compareAndSet(false, true)) {
23425                synchronized (mPackages) {
23426                    if (mWeFroze) {
23427                        mFrozenPackages.remove(mPackageName);
23428                    }
23429
23430                    if (mChildren != null) {
23431                        for (PackageFreezer freezer : mChildren) {
23432                            freezer.close();
23433                        }
23434                    }
23435                }
23436            }
23437        }
23438    }
23439
23440    /**
23441     * Verify that given package is currently frozen.
23442     */
23443    private void checkPackageFrozen(String packageName) {
23444        synchronized (mPackages) {
23445            if (!mFrozenPackages.contains(packageName)) {
23446                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23447            }
23448        }
23449    }
23450
23451    @Override
23452    public int movePackage(final String packageName, final String volumeUuid) {
23453        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23454
23455        final int callingUid = Binder.getCallingUid();
23456        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23457        final int moveId = mNextMoveId.getAndIncrement();
23458        mHandler.post(new Runnable() {
23459            @Override
23460            public void run() {
23461                try {
23462                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23463                } catch (PackageManagerException e) {
23464                    Slog.w(TAG, "Failed to move " + packageName, e);
23465                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23466                }
23467            }
23468        });
23469        return moveId;
23470    }
23471
23472    private void movePackageInternal(final String packageName, final String volumeUuid,
23473            final int moveId, final int callingUid, UserHandle user)
23474                    throws PackageManagerException {
23475        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23476        final PackageManager pm = mContext.getPackageManager();
23477
23478        final boolean currentAsec;
23479        final String currentVolumeUuid;
23480        final File codeFile;
23481        final String installerPackageName;
23482        final String packageAbiOverride;
23483        final int appId;
23484        final String seinfo;
23485        final String label;
23486        final int targetSdkVersion;
23487        final PackageFreezer freezer;
23488        final int[] installedUserIds;
23489
23490        // reader
23491        synchronized (mPackages) {
23492            final PackageParser.Package pkg = mPackages.get(packageName);
23493            final PackageSetting ps = mSettings.mPackages.get(packageName);
23494            if (pkg == null
23495                    || ps == null
23496                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23497                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23498            }
23499            if (pkg.applicationInfo.isSystemApp()) {
23500                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23501                        "Cannot move system application");
23502            }
23503
23504            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23505            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23506                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23507            if (isInternalStorage && !allow3rdPartyOnInternal) {
23508                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23509                        "3rd party apps are not allowed on internal storage");
23510            }
23511
23512            if (pkg.applicationInfo.isExternalAsec()) {
23513                currentAsec = true;
23514                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23515            } else if (pkg.applicationInfo.isForwardLocked()) {
23516                currentAsec = true;
23517                currentVolumeUuid = "forward_locked";
23518            } else {
23519                currentAsec = false;
23520                currentVolumeUuid = ps.volumeUuid;
23521
23522                final File probe = new File(pkg.codePath);
23523                final File probeOat = new File(probe, "oat");
23524                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23525                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23526                            "Move only supported for modern cluster style installs");
23527                }
23528            }
23529
23530            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23531                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23532                        "Package already moved to " + volumeUuid);
23533            }
23534            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23535                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23536                        "Device admin cannot be moved");
23537            }
23538
23539            if (mFrozenPackages.contains(packageName)) {
23540                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23541                        "Failed to move already frozen package");
23542            }
23543
23544            codeFile = new File(pkg.codePath);
23545            installerPackageName = ps.installerPackageName;
23546            packageAbiOverride = ps.cpuAbiOverrideString;
23547            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23548            seinfo = pkg.applicationInfo.seInfo;
23549            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23550            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23551            freezer = freezePackage(packageName, "movePackageInternal");
23552            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23553        }
23554
23555        final Bundle extras = new Bundle();
23556        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23557        extras.putString(Intent.EXTRA_TITLE, label);
23558        mMoveCallbacks.notifyCreated(moveId, extras);
23559
23560        int installFlags;
23561        final boolean moveCompleteApp;
23562        final File measurePath;
23563
23564        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23565            installFlags = INSTALL_INTERNAL;
23566            moveCompleteApp = !currentAsec;
23567            measurePath = Environment.getDataAppDirectory(volumeUuid);
23568        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23569            installFlags = INSTALL_EXTERNAL;
23570            moveCompleteApp = false;
23571            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23572        } else {
23573            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23574            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23575                    || !volume.isMountedWritable()) {
23576                freezer.close();
23577                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23578                        "Move location not mounted private volume");
23579            }
23580
23581            Preconditions.checkState(!currentAsec);
23582
23583            installFlags = INSTALL_INTERNAL;
23584            moveCompleteApp = true;
23585            measurePath = Environment.getDataAppDirectory(volumeUuid);
23586        }
23587
23588        // If we're moving app data around, we need all the users unlocked
23589        if (moveCompleteApp) {
23590            for (int userId : installedUserIds) {
23591                if (StorageManager.isFileEncryptedNativeOrEmulated()
23592                        && !StorageManager.isUserKeyUnlocked(userId)) {
23593                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23594                            "User " + userId + " must be unlocked");
23595                }
23596            }
23597        }
23598
23599        final PackageStats stats = new PackageStats(null, -1);
23600        synchronized (mInstaller) {
23601            for (int userId : installedUserIds) {
23602                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23603                    freezer.close();
23604                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23605                            "Failed to measure package size");
23606                }
23607            }
23608        }
23609
23610        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23611                + stats.dataSize);
23612
23613        final long startFreeBytes = measurePath.getUsableSpace();
23614        final long sizeBytes;
23615        if (moveCompleteApp) {
23616            sizeBytes = stats.codeSize + stats.dataSize;
23617        } else {
23618            sizeBytes = stats.codeSize;
23619        }
23620
23621        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23622            freezer.close();
23623            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23624                    "Not enough free space to move");
23625        }
23626
23627        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23628
23629        final CountDownLatch installedLatch = new CountDownLatch(1);
23630        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23631            @Override
23632            public void onUserActionRequired(Intent intent) throws RemoteException {
23633                throw new IllegalStateException();
23634            }
23635
23636            @Override
23637            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23638                    Bundle extras) throws RemoteException {
23639                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23640                        + PackageManager.installStatusToString(returnCode, msg));
23641
23642                installedLatch.countDown();
23643                freezer.close();
23644
23645                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23646                switch (status) {
23647                    case PackageInstaller.STATUS_SUCCESS:
23648                        mMoveCallbacks.notifyStatusChanged(moveId,
23649                                PackageManager.MOVE_SUCCEEDED);
23650                        break;
23651                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23652                        mMoveCallbacks.notifyStatusChanged(moveId,
23653                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23654                        break;
23655                    default:
23656                        mMoveCallbacks.notifyStatusChanged(moveId,
23657                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23658                        break;
23659                }
23660            }
23661        };
23662
23663        final MoveInfo move;
23664        if (moveCompleteApp) {
23665            // Kick off a thread to report progress estimates
23666            new Thread() {
23667                @Override
23668                public void run() {
23669                    while (true) {
23670                        try {
23671                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23672                                break;
23673                            }
23674                        } catch (InterruptedException ignored) {
23675                        }
23676
23677                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23678                        final int progress = 10 + (int) MathUtils.constrain(
23679                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23680                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23681                    }
23682                }
23683            }.start();
23684
23685            final String dataAppName = codeFile.getName();
23686            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23687                    dataAppName, appId, seinfo, targetSdkVersion);
23688        } else {
23689            move = null;
23690        }
23691
23692        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23693
23694        final Message msg = mHandler.obtainMessage(INIT_COPY);
23695        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23696        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23697                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23698                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23699                PackageManager.INSTALL_REASON_UNKNOWN);
23700        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23701        msg.obj = params;
23702
23703        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23704                System.identityHashCode(msg.obj));
23705        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23706                System.identityHashCode(msg.obj));
23707
23708        mHandler.sendMessage(msg);
23709    }
23710
23711    @Override
23712    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23713        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23714
23715        final int realMoveId = mNextMoveId.getAndIncrement();
23716        final Bundle extras = new Bundle();
23717        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23718        mMoveCallbacks.notifyCreated(realMoveId, extras);
23719
23720        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23721            @Override
23722            public void onCreated(int moveId, Bundle extras) {
23723                // Ignored
23724            }
23725
23726            @Override
23727            public void onStatusChanged(int moveId, int status, long estMillis) {
23728                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23729            }
23730        };
23731
23732        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23733        storage.setPrimaryStorageUuid(volumeUuid, callback);
23734        return realMoveId;
23735    }
23736
23737    @Override
23738    public int getMoveStatus(int moveId) {
23739        mContext.enforceCallingOrSelfPermission(
23740                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23741        return mMoveCallbacks.mLastStatus.get(moveId);
23742    }
23743
23744    @Override
23745    public void registerMoveCallback(IPackageMoveObserver callback) {
23746        mContext.enforceCallingOrSelfPermission(
23747                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23748        mMoveCallbacks.register(callback);
23749    }
23750
23751    @Override
23752    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23753        mContext.enforceCallingOrSelfPermission(
23754                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23755        mMoveCallbacks.unregister(callback);
23756    }
23757
23758    @Override
23759    public boolean setInstallLocation(int loc) {
23760        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23761                null);
23762        if (getInstallLocation() == loc) {
23763            return true;
23764        }
23765        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23766                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23767            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23768                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23769            return true;
23770        }
23771        return false;
23772   }
23773
23774    @Override
23775    public int getInstallLocation() {
23776        // allow instant app access
23777        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23778                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23779                PackageHelper.APP_INSTALL_AUTO);
23780    }
23781
23782    /** Called by UserManagerService */
23783    void cleanUpUser(UserManagerService userManager, int userHandle) {
23784        synchronized (mPackages) {
23785            mDirtyUsers.remove(userHandle);
23786            mUserNeedsBadging.delete(userHandle);
23787            mSettings.removeUserLPw(userHandle);
23788            mPendingBroadcasts.remove(userHandle);
23789            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23790            removeUnusedPackagesLPw(userManager, userHandle);
23791        }
23792    }
23793
23794    /**
23795     * We're removing userHandle and would like to remove any downloaded packages
23796     * that are no longer in use by any other user.
23797     * @param userHandle the user being removed
23798     */
23799    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23800        final boolean DEBUG_CLEAN_APKS = false;
23801        int [] users = userManager.getUserIds();
23802        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23803        while (psit.hasNext()) {
23804            PackageSetting ps = psit.next();
23805            if (ps.pkg == null) {
23806                continue;
23807            }
23808            final String packageName = ps.pkg.packageName;
23809            // Skip over if system app
23810            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23811                continue;
23812            }
23813            if (DEBUG_CLEAN_APKS) {
23814                Slog.i(TAG, "Checking package " + packageName);
23815            }
23816            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23817            if (keep) {
23818                if (DEBUG_CLEAN_APKS) {
23819                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23820                }
23821            } else {
23822                for (int i = 0; i < users.length; i++) {
23823                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23824                        keep = true;
23825                        if (DEBUG_CLEAN_APKS) {
23826                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23827                                    + users[i]);
23828                        }
23829                        break;
23830                    }
23831                }
23832            }
23833            if (!keep) {
23834                if (DEBUG_CLEAN_APKS) {
23835                    Slog.i(TAG, "  Removing package " + packageName);
23836                }
23837                mHandler.post(new Runnable() {
23838                    public void run() {
23839                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23840                                userHandle, 0);
23841                    } //end run
23842                });
23843            }
23844        }
23845    }
23846
23847    /** Called by UserManagerService */
23848    void createNewUser(int userId, String[] disallowedPackages) {
23849        synchronized (mInstallLock) {
23850            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23851        }
23852        synchronized (mPackages) {
23853            scheduleWritePackageRestrictionsLocked(userId);
23854            scheduleWritePackageListLocked(userId);
23855            applyFactoryDefaultBrowserLPw(userId);
23856            primeDomainVerificationsLPw(userId);
23857        }
23858    }
23859
23860    void onNewUserCreated(final int userId) {
23861        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23862        // If permission review for legacy apps is required, we represent
23863        // dagerous permissions for such apps as always granted runtime
23864        // permissions to keep per user flag state whether review is needed.
23865        // Hence, if a new user is added we have to propagate dangerous
23866        // permission grants for these legacy apps.
23867        if (mPermissionReviewRequired) {
23868            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23869                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23870        }
23871    }
23872
23873    @Override
23874    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23875        mContext.enforceCallingOrSelfPermission(
23876                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23877                "Only package verification agents can read the verifier device identity");
23878
23879        synchronized (mPackages) {
23880            return mSettings.getVerifierDeviceIdentityLPw();
23881        }
23882    }
23883
23884    @Override
23885    public void setPermissionEnforced(String permission, boolean enforced) {
23886        // TODO: Now that we no longer change GID for storage, this should to away.
23887        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23888                "setPermissionEnforced");
23889        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23890            synchronized (mPackages) {
23891                if (mSettings.mReadExternalStorageEnforced == null
23892                        || mSettings.mReadExternalStorageEnforced != enforced) {
23893                    mSettings.mReadExternalStorageEnforced =
23894                            enforced ? Boolean.TRUE : Boolean.FALSE;
23895                    mSettings.writeLPr();
23896                }
23897            }
23898            // kill any non-foreground processes so we restart them and
23899            // grant/revoke the GID.
23900            final IActivityManager am = ActivityManager.getService();
23901            if (am != null) {
23902                final long token = Binder.clearCallingIdentity();
23903                try {
23904                    am.killProcessesBelowForeground("setPermissionEnforcement");
23905                } catch (RemoteException e) {
23906                } finally {
23907                    Binder.restoreCallingIdentity(token);
23908                }
23909            }
23910        } else {
23911            throw new IllegalArgumentException("No selective enforcement for " + permission);
23912        }
23913    }
23914
23915    @Override
23916    @Deprecated
23917    public boolean isPermissionEnforced(String permission) {
23918        // allow instant applications
23919        return true;
23920    }
23921
23922    @Override
23923    public boolean isStorageLow() {
23924        // allow instant applications
23925        final long token = Binder.clearCallingIdentity();
23926        try {
23927            final DeviceStorageMonitorInternal
23928                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23929            if (dsm != null) {
23930                return dsm.isMemoryLow();
23931            } else {
23932                return false;
23933            }
23934        } finally {
23935            Binder.restoreCallingIdentity(token);
23936        }
23937    }
23938
23939    @Override
23940    public IPackageInstaller getPackageInstaller() {
23941        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23942            return null;
23943        }
23944        return mInstallerService;
23945    }
23946
23947    private boolean userNeedsBadging(int userId) {
23948        int index = mUserNeedsBadging.indexOfKey(userId);
23949        if (index < 0) {
23950            final UserInfo userInfo;
23951            final long token = Binder.clearCallingIdentity();
23952            try {
23953                userInfo = sUserManager.getUserInfo(userId);
23954            } finally {
23955                Binder.restoreCallingIdentity(token);
23956            }
23957            final boolean b;
23958            if (userInfo != null && userInfo.isManagedProfile()) {
23959                b = true;
23960            } else {
23961                b = false;
23962            }
23963            mUserNeedsBadging.put(userId, b);
23964            return b;
23965        }
23966        return mUserNeedsBadging.valueAt(index);
23967    }
23968
23969    @Override
23970    public KeySet getKeySetByAlias(String packageName, String alias) {
23971        if (packageName == null || alias == null) {
23972            return null;
23973        }
23974        synchronized(mPackages) {
23975            final PackageParser.Package pkg = mPackages.get(packageName);
23976            if (pkg == null) {
23977                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23978                throw new IllegalArgumentException("Unknown package: " + packageName);
23979            }
23980            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23981            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23982                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23983                throw new IllegalArgumentException("Unknown package: " + packageName);
23984            }
23985            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23986            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23987        }
23988    }
23989
23990    @Override
23991    public KeySet getSigningKeySet(String packageName) {
23992        if (packageName == null) {
23993            return null;
23994        }
23995        synchronized(mPackages) {
23996            final int callingUid = Binder.getCallingUid();
23997            final int callingUserId = UserHandle.getUserId(callingUid);
23998            final PackageParser.Package pkg = mPackages.get(packageName);
23999            if (pkg == null) {
24000                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24001                throw new IllegalArgumentException("Unknown package: " + packageName);
24002            }
24003            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24004            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24005                // filter and pretend the package doesn't exist
24006                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24007                        + ", uid:" + callingUid);
24008                throw new IllegalArgumentException("Unknown package: " + packageName);
24009            }
24010            if (pkg.applicationInfo.uid != callingUid
24011                    && Process.SYSTEM_UID != callingUid) {
24012                throw new SecurityException("May not access signing KeySet of other apps.");
24013            }
24014            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24015            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24016        }
24017    }
24018
24019    @Override
24020    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24021        final int callingUid = Binder.getCallingUid();
24022        if (getInstantAppPackageName(callingUid) != null) {
24023            return false;
24024        }
24025        if (packageName == null || ks == null) {
24026            return false;
24027        }
24028        synchronized(mPackages) {
24029            final PackageParser.Package pkg = mPackages.get(packageName);
24030            if (pkg == null
24031                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24032                            UserHandle.getUserId(callingUid))) {
24033                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24034                throw new IllegalArgumentException("Unknown package: " + packageName);
24035            }
24036            IBinder ksh = ks.getToken();
24037            if (ksh instanceof KeySetHandle) {
24038                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24039                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24040            }
24041            return false;
24042        }
24043    }
24044
24045    @Override
24046    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24047        final int callingUid = Binder.getCallingUid();
24048        if (getInstantAppPackageName(callingUid) != null) {
24049            return false;
24050        }
24051        if (packageName == null || ks == null) {
24052            return false;
24053        }
24054        synchronized(mPackages) {
24055            final PackageParser.Package pkg = mPackages.get(packageName);
24056            if (pkg == null
24057                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24058                            UserHandle.getUserId(callingUid))) {
24059                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24060                throw new IllegalArgumentException("Unknown package: " + packageName);
24061            }
24062            IBinder ksh = ks.getToken();
24063            if (ksh instanceof KeySetHandle) {
24064                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24065                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24066            }
24067            return false;
24068        }
24069    }
24070
24071    private void deletePackageIfUnusedLPr(final String packageName) {
24072        PackageSetting ps = mSettings.mPackages.get(packageName);
24073        if (ps == null) {
24074            return;
24075        }
24076        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24077            // TODO Implement atomic delete if package is unused
24078            // It is currently possible that the package will be deleted even if it is installed
24079            // after this method returns.
24080            mHandler.post(new Runnable() {
24081                public void run() {
24082                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24083                            0, PackageManager.DELETE_ALL_USERS);
24084                }
24085            });
24086        }
24087    }
24088
24089    /**
24090     * Check and throw if the given before/after packages would be considered a
24091     * downgrade.
24092     */
24093    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24094            throws PackageManagerException {
24095        if (after.versionCode < before.mVersionCode) {
24096            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24097                    "Update version code " + after.versionCode + " is older than current "
24098                    + before.mVersionCode);
24099        } else if (after.versionCode == before.mVersionCode) {
24100            if (after.baseRevisionCode < before.baseRevisionCode) {
24101                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24102                        "Update base revision code " + after.baseRevisionCode
24103                        + " is older than current " + before.baseRevisionCode);
24104            }
24105
24106            if (!ArrayUtils.isEmpty(after.splitNames)) {
24107                for (int i = 0; i < after.splitNames.length; i++) {
24108                    final String splitName = after.splitNames[i];
24109                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24110                    if (j != -1) {
24111                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24112                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24113                                    "Update split " + splitName + " revision code "
24114                                    + after.splitRevisionCodes[i] + " is older than current "
24115                                    + before.splitRevisionCodes[j]);
24116                        }
24117                    }
24118                }
24119            }
24120        }
24121    }
24122
24123    private static class MoveCallbacks extends Handler {
24124        private static final int MSG_CREATED = 1;
24125        private static final int MSG_STATUS_CHANGED = 2;
24126
24127        private final RemoteCallbackList<IPackageMoveObserver>
24128                mCallbacks = new RemoteCallbackList<>();
24129
24130        private final SparseIntArray mLastStatus = new SparseIntArray();
24131
24132        public MoveCallbacks(Looper looper) {
24133            super(looper);
24134        }
24135
24136        public void register(IPackageMoveObserver callback) {
24137            mCallbacks.register(callback);
24138        }
24139
24140        public void unregister(IPackageMoveObserver callback) {
24141            mCallbacks.unregister(callback);
24142        }
24143
24144        @Override
24145        public void handleMessage(Message msg) {
24146            final SomeArgs args = (SomeArgs) msg.obj;
24147            final int n = mCallbacks.beginBroadcast();
24148            for (int i = 0; i < n; i++) {
24149                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24150                try {
24151                    invokeCallback(callback, msg.what, args);
24152                } catch (RemoteException ignored) {
24153                }
24154            }
24155            mCallbacks.finishBroadcast();
24156            args.recycle();
24157        }
24158
24159        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24160                throws RemoteException {
24161            switch (what) {
24162                case MSG_CREATED: {
24163                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24164                    break;
24165                }
24166                case MSG_STATUS_CHANGED: {
24167                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24168                    break;
24169                }
24170            }
24171        }
24172
24173        private void notifyCreated(int moveId, Bundle extras) {
24174            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24175
24176            final SomeArgs args = SomeArgs.obtain();
24177            args.argi1 = moveId;
24178            args.arg2 = extras;
24179            obtainMessage(MSG_CREATED, args).sendToTarget();
24180        }
24181
24182        private void notifyStatusChanged(int moveId, int status) {
24183            notifyStatusChanged(moveId, status, -1);
24184        }
24185
24186        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24187            Slog.v(TAG, "Move " + moveId + " status " + status);
24188
24189            final SomeArgs args = SomeArgs.obtain();
24190            args.argi1 = moveId;
24191            args.argi2 = status;
24192            args.arg3 = estMillis;
24193            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24194
24195            synchronized (mLastStatus) {
24196                mLastStatus.put(moveId, status);
24197            }
24198        }
24199    }
24200
24201    private final static class OnPermissionChangeListeners extends Handler {
24202        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24203
24204        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24205                new RemoteCallbackList<>();
24206
24207        public OnPermissionChangeListeners(Looper looper) {
24208            super(looper);
24209        }
24210
24211        @Override
24212        public void handleMessage(Message msg) {
24213            switch (msg.what) {
24214                case MSG_ON_PERMISSIONS_CHANGED: {
24215                    final int uid = msg.arg1;
24216                    handleOnPermissionsChanged(uid);
24217                } break;
24218            }
24219        }
24220
24221        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24222            mPermissionListeners.register(listener);
24223
24224        }
24225
24226        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24227            mPermissionListeners.unregister(listener);
24228        }
24229
24230        public void onPermissionsChanged(int uid) {
24231            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24232                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24233            }
24234        }
24235
24236        private void handleOnPermissionsChanged(int uid) {
24237            final int count = mPermissionListeners.beginBroadcast();
24238            try {
24239                for (int i = 0; i < count; i++) {
24240                    IOnPermissionsChangeListener callback = mPermissionListeners
24241                            .getBroadcastItem(i);
24242                    try {
24243                        callback.onPermissionsChanged(uid);
24244                    } catch (RemoteException e) {
24245                        Log.e(TAG, "Permission listener is dead", e);
24246                    }
24247                }
24248            } finally {
24249                mPermissionListeners.finishBroadcast();
24250            }
24251        }
24252    }
24253
24254    private class PackageManagerNative extends IPackageManagerNative.Stub {
24255        @Override
24256        public String[] getNamesForUids(int[] uids) throws RemoteException {
24257            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24258            // massage results so they can be parsed by the native binder
24259            for (int i = results.length - 1; i >= 0; --i) {
24260                if (results[i] == null) {
24261                    results[i] = "";
24262                }
24263            }
24264            return results;
24265        }
24266
24267        // NB: this differentiates between preloads and sideloads
24268        @Override
24269        public String getInstallerForPackage(String packageName) throws RemoteException {
24270            final String installerName = getInstallerPackageName(packageName);
24271            if (!TextUtils.isEmpty(installerName)) {
24272                return installerName;
24273            }
24274            // differentiate between preload and sideload
24275            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24276            ApplicationInfo appInfo = getApplicationInfo(packageName,
24277                                    /*flags*/ 0,
24278                                    /*userId*/ callingUser);
24279            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24280                return "preload";
24281            }
24282            return "";
24283        }
24284
24285        @Override
24286        public int getVersionCodeForPackage(String packageName) throws RemoteException {
24287            try {
24288                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24289                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
24290                if (pInfo != null) {
24291                    return pInfo.versionCode;
24292                }
24293            } catch (Exception e) {
24294            }
24295            return 0;
24296        }
24297    }
24298
24299    private class PackageManagerInternalImpl extends PackageManagerInternal {
24300        @Override
24301        public void setLocationPackagesProvider(PackagesProvider provider) {
24302            synchronized (mPackages) {
24303                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24304            }
24305        }
24306
24307        @Override
24308        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24309            synchronized (mPackages) {
24310                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24311            }
24312        }
24313
24314        @Override
24315        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24316            synchronized (mPackages) {
24317                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24318            }
24319        }
24320
24321        @Override
24322        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24323            synchronized (mPackages) {
24324                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24325            }
24326        }
24327
24328        @Override
24329        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24330            synchronized (mPackages) {
24331                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24332            }
24333        }
24334
24335        @Override
24336        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24337            synchronized (mPackages) {
24338                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24339            }
24340        }
24341
24342        @Override
24343        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24344            synchronized (mPackages) {
24345                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24346                        packageName, userId);
24347            }
24348        }
24349
24350        @Override
24351        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24352            synchronized (mPackages) {
24353                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24354                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24355                        packageName, userId);
24356            }
24357        }
24358
24359        @Override
24360        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24361            synchronized (mPackages) {
24362                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24363                        packageName, userId);
24364            }
24365        }
24366
24367        @Override
24368        public void setKeepUninstalledPackages(final List<String> packageList) {
24369            Preconditions.checkNotNull(packageList);
24370            List<String> removedFromList = null;
24371            synchronized (mPackages) {
24372                if (mKeepUninstalledPackages != null) {
24373                    final int packagesCount = mKeepUninstalledPackages.size();
24374                    for (int i = 0; i < packagesCount; i++) {
24375                        String oldPackage = mKeepUninstalledPackages.get(i);
24376                        if (packageList != null && packageList.contains(oldPackage)) {
24377                            continue;
24378                        }
24379                        if (removedFromList == null) {
24380                            removedFromList = new ArrayList<>();
24381                        }
24382                        removedFromList.add(oldPackage);
24383                    }
24384                }
24385                mKeepUninstalledPackages = new ArrayList<>(packageList);
24386                if (removedFromList != null) {
24387                    final int removedCount = removedFromList.size();
24388                    for (int i = 0; i < removedCount; i++) {
24389                        deletePackageIfUnusedLPr(removedFromList.get(i));
24390                    }
24391                }
24392            }
24393        }
24394
24395        @Override
24396        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24397            synchronized (mPackages) {
24398                // If we do not support permission review, done.
24399                if (!mPermissionReviewRequired) {
24400                    return false;
24401                }
24402
24403                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24404                if (packageSetting == null) {
24405                    return false;
24406                }
24407
24408                // Permission review applies only to apps not supporting the new permission model.
24409                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24410                    return false;
24411                }
24412
24413                // Legacy apps have the permission and get user consent on launch.
24414                PermissionsState permissionsState = packageSetting.getPermissionsState();
24415                return permissionsState.isPermissionReviewRequired(userId);
24416            }
24417        }
24418
24419        @Override
24420        public PackageInfo getPackageInfo(
24421                String packageName, int flags, int filterCallingUid, int userId) {
24422            return PackageManagerService.this
24423                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24424                            flags, filterCallingUid, userId);
24425        }
24426
24427        @Override
24428        public ApplicationInfo getApplicationInfo(
24429                String packageName, int flags, int filterCallingUid, int userId) {
24430            return PackageManagerService.this
24431                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24432        }
24433
24434        @Override
24435        public ActivityInfo getActivityInfo(
24436                ComponentName component, int flags, int filterCallingUid, int userId) {
24437            return PackageManagerService.this
24438                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24439        }
24440
24441        @Override
24442        public List<ResolveInfo> queryIntentActivities(
24443                Intent intent, int flags, int filterCallingUid, int userId) {
24444            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24445            return PackageManagerService.this
24446                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24447                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
24448        }
24449
24450        @Override
24451        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24452                int userId) {
24453            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24454        }
24455
24456        @Override
24457        public void setDeviceAndProfileOwnerPackages(
24458                int deviceOwnerUserId, String deviceOwnerPackage,
24459                SparseArray<String> profileOwnerPackages) {
24460            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24461                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24462        }
24463
24464        @Override
24465        public boolean isPackageDataProtected(int userId, String packageName) {
24466            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24467        }
24468
24469        @Override
24470        public boolean isPackageEphemeral(int userId, String packageName) {
24471            synchronized (mPackages) {
24472                final PackageSetting ps = mSettings.mPackages.get(packageName);
24473                return ps != null ? ps.getInstantApp(userId) : false;
24474            }
24475        }
24476
24477        @Override
24478        public boolean wasPackageEverLaunched(String packageName, int userId) {
24479            synchronized (mPackages) {
24480                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24481            }
24482        }
24483
24484        @Override
24485        public void grantRuntimePermission(String packageName, String name, int userId,
24486                boolean overridePolicy) {
24487            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24488                    overridePolicy);
24489        }
24490
24491        @Override
24492        public void revokeRuntimePermission(String packageName, String name, int userId,
24493                boolean overridePolicy) {
24494            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24495                    overridePolicy);
24496        }
24497
24498        @Override
24499        public String getNameForUid(int uid) {
24500            return PackageManagerService.this.getNameForUid(uid);
24501        }
24502
24503        @Override
24504        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24505                Intent origIntent, String resolvedType, String callingPackage,
24506                Bundle verificationBundle, int userId) {
24507            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24508                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24509                    userId);
24510        }
24511
24512        @Override
24513        public void grantEphemeralAccess(int userId, Intent intent,
24514                int targetAppId, int ephemeralAppId) {
24515            synchronized (mPackages) {
24516                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24517                        targetAppId, ephemeralAppId);
24518            }
24519        }
24520
24521        @Override
24522        public boolean isInstantAppInstallerComponent(ComponentName component) {
24523            synchronized (mPackages) {
24524                return mInstantAppInstallerActivity != null
24525                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24526            }
24527        }
24528
24529        @Override
24530        public void pruneInstantApps() {
24531            mInstantAppRegistry.pruneInstantApps();
24532        }
24533
24534        @Override
24535        public String getSetupWizardPackageName() {
24536            return mSetupWizardPackage;
24537        }
24538
24539        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24540            if (policy != null) {
24541                mExternalSourcesPolicy = policy;
24542            }
24543        }
24544
24545        @Override
24546        public boolean isPackagePersistent(String packageName) {
24547            synchronized (mPackages) {
24548                PackageParser.Package pkg = mPackages.get(packageName);
24549                return pkg != null
24550                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24551                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24552                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24553                        : false;
24554            }
24555        }
24556
24557        @Override
24558        public List<PackageInfo> getOverlayPackages(int userId) {
24559            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24560            synchronized (mPackages) {
24561                for (PackageParser.Package p : mPackages.values()) {
24562                    if (p.mOverlayTarget != null) {
24563                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24564                        if (pkg != null) {
24565                            overlayPackages.add(pkg);
24566                        }
24567                    }
24568                }
24569            }
24570            return overlayPackages;
24571        }
24572
24573        @Override
24574        public List<String> getTargetPackageNames(int userId) {
24575            List<String> targetPackages = new ArrayList<>();
24576            synchronized (mPackages) {
24577                for (PackageParser.Package p : mPackages.values()) {
24578                    if (p.mOverlayTarget == null) {
24579                        targetPackages.add(p.packageName);
24580                    }
24581                }
24582            }
24583            return targetPackages;
24584        }
24585
24586        @Override
24587        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24588                @Nullable List<String> overlayPackageNames) {
24589            synchronized (mPackages) {
24590                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24591                    Slog.e(TAG, "failed to find package " + targetPackageName);
24592                    return false;
24593                }
24594                ArrayList<String> overlayPaths = null;
24595                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24596                    final int N = overlayPackageNames.size();
24597                    overlayPaths = new ArrayList<>(N);
24598                    for (int i = 0; i < N; i++) {
24599                        final String packageName = overlayPackageNames.get(i);
24600                        final PackageParser.Package pkg = mPackages.get(packageName);
24601                        if (pkg == null) {
24602                            Slog.e(TAG, "failed to find package " + packageName);
24603                            return false;
24604                        }
24605                        overlayPaths.add(pkg.baseCodePath);
24606                    }
24607                }
24608
24609                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24610                ps.setOverlayPaths(overlayPaths, userId);
24611                return true;
24612            }
24613        }
24614
24615        @Override
24616        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24617                int flags, int userId) {
24618            return resolveIntentInternal(
24619                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24620        }
24621
24622        @Override
24623        public ResolveInfo resolveService(Intent intent, String resolvedType,
24624                int flags, int userId, int callingUid) {
24625            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24626        }
24627
24628        @Override
24629        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24630            synchronized (mPackages) {
24631                mIsolatedOwners.put(isolatedUid, ownerUid);
24632            }
24633        }
24634
24635        @Override
24636        public void removeIsolatedUid(int isolatedUid) {
24637            synchronized (mPackages) {
24638                mIsolatedOwners.delete(isolatedUid);
24639            }
24640        }
24641
24642        @Override
24643        public int getUidTargetSdkVersion(int uid) {
24644            synchronized (mPackages) {
24645                return getUidTargetSdkVersionLockedLPr(uid);
24646            }
24647        }
24648
24649        @Override
24650        public boolean canAccessInstantApps(int callingUid, int userId) {
24651            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24652        }
24653
24654        @Override
24655        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24656            synchronized (mPackages) {
24657                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24658            }
24659        }
24660
24661        @Override
24662        public void notifyPackageUse(String packageName, int reason) {
24663            synchronized (mPackages) {
24664                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24665            }
24666        }
24667    }
24668
24669    @Override
24670    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24671        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24672        synchronized (mPackages) {
24673            final long identity = Binder.clearCallingIdentity();
24674            try {
24675                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24676                        packageNames, userId);
24677            } finally {
24678                Binder.restoreCallingIdentity(identity);
24679            }
24680        }
24681    }
24682
24683    @Override
24684    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24685        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24686        synchronized (mPackages) {
24687            final long identity = Binder.clearCallingIdentity();
24688            try {
24689                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24690                        packageNames, userId);
24691            } finally {
24692                Binder.restoreCallingIdentity(identity);
24693            }
24694        }
24695    }
24696
24697    private static void enforceSystemOrPhoneCaller(String tag) {
24698        int callingUid = Binder.getCallingUid();
24699        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24700            throw new SecurityException(
24701                    "Cannot call " + tag + " from UID " + callingUid);
24702        }
24703    }
24704
24705    boolean isHistoricalPackageUsageAvailable() {
24706        return mPackageUsage.isHistoricalPackageUsageAvailable();
24707    }
24708
24709    /**
24710     * Return a <b>copy</b> of the collection of packages known to the package manager.
24711     * @return A copy of the values of mPackages.
24712     */
24713    Collection<PackageParser.Package> getPackages() {
24714        synchronized (mPackages) {
24715            return new ArrayList<>(mPackages.values());
24716        }
24717    }
24718
24719    /**
24720     * Logs process start information (including base APK hash) to the security log.
24721     * @hide
24722     */
24723    @Override
24724    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24725            String apkFile, int pid) {
24726        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24727            return;
24728        }
24729        if (!SecurityLog.isLoggingEnabled()) {
24730            return;
24731        }
24732        Bundle data = new Bundle();
24733        data.putLong("startTimestamp", System.currentTimeMillis());
24734        data.putString("processName", processName);
24735        data.putInt("uid", uid);
24736        data.putString("seinfo", seinfo);
24737        data.putString("apkFile", apkFile);
24738        data.putInt("pid", pid);
24739        Message msg = mProcessLoggingHandler.obtainMessage(
24740                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24741        msg.setData(data);
24742        mProcessLoggingHandler.sendMessage(msg);
24743    }
24744
24745    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24746        return mCompilerStats.getPackageStats(pkgName);
24747    }
24748
24749    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24750        return getOrCreateCompilerPackageStats(pkg.packageName);
24751    }
24752
24753    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24754        return mCompilerStats.getOrCreatePackageStats(pkgName);
24755    }
24756
24757    public void deleteCompilerPackageStats(String pkgName) {
24758        mCompilerStats.deletePackageStats(pkgName);
24759    }
24760
24761    @Override
24762    public int getInstallReason(String packageName, int userId) {
24763        final int callingUid = Binder.getCallingUid();
24764        enforceCrossUserPermission(callingUid, userId,
24765                true /* requireFullPermission */, false /* checkShell */,
24766                "get install reason");
24767        synchronized (mPackages) {
24768            final PackageSetting ps = mSettings.mPackages.get(packageName);
24769            if (filterAppAccessLPr(ps, callingUid, userId)) {
24770                return PackageManager.INSTALL_REASON_UNKNOWN;
24771            }
24772            if (ps != null) {
24773                return ps.getInstallReason(userId);
24774            }
24775        }
24776        return PackageManager.INSTALL_REASON_UNKNOWN;
24777    }
24778
24779    @Override
24780    public boolean canRequestPackageInstalls(String packageName, int userId) {
24781        return canRequestPackageInstallsInternal(packageName, 0, userId,
24782                true /* throwIfPermNotDeclared*/);
24783    }
24784
24785    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24786            boolean throwIfPermNotDeclared) {
24787        int callingUid = Binder.getCallingUid();
24788        int uid = getPackageUid(packageName, 0, userId);
24789        if (callingUid != uid && callingUid != Process.ROOT_UID
24790                && callingUid != Process.SYSTEM_UID) {
24791            throw new SecurityException(
24792                    "Caller uid " + callingUid + " does not own package " + packageName);
24793        }
24794        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24795        if (info == null) {
24796            return false;
24797        }
24798        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24799            return false;
24800        }
24801        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24802        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24803        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24804            if (throwIfPermNotDeclared) {
24805                throw new SecurityException("Need to declare " + appOpPermission
24806                        + " to call this api");
24807            } else {
24808                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24809                return false;
24810            }
24811        }
24812        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24813            return false;
24814        }
24815        if (mExternalSourcesPolicy != null) {
24816            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24817            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24818                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24819            }
24820        }
24821        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24822    }
24823
24824    @Override
24825    public ComponentName getInstantAppResolverSettingsComponent() {
24826        return mInstantAppResolverSettingsComponent;
24827    }
24828
24829    @Override
24830    public ComponentName getInstantAppInstallerComponent() {
24831        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24832            return null;
24833        }
24834        return mInstantAppInstallerActivity == null
24835                ? null : mInstantAppInstallerActivity.getComponentName();
24836    }
24837
24838    @Override
24839    public String getInstantAppAndroidId(String packageName, int userId) {
24840        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24841                "getInstantAppAndroidId");
24842        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24843                true /* requireFullPermission */, false /* checkShell */,
24844                "getInstantAppAndroidId");
24845        // Make sure the target is an Instant App.
24846        if (!isInstantApp(packageName, userId)) {
24847            return null;
24848        }
24849        synchronized (mPackages) {
24850            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24851        }
24852    }
24853
24854    boolean canHaveOatDir(String packageName) {
24855        synchronized (mPackages) {
24856            PackageParser.Package p = mPackages.get(packageName);
24857            if (p == null) {
24858                return false;
24859            }
24860            return p.canHaveOatDir();
24861        }
24862    }
24863
24864    private String getOatDir(PackageParser.Package pkg) {
24865        if (!pkg.canHaveOatDir()) {
24866            return null;
24867        }
24868        File codePath = new File(pkg.codePath);
24869        if (codePath.isDirectory()) {
24870            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24871        }
24872        return null;
24873    }
24874
24875    void deleteOatArtifactsOfPackage(String packageName) {
24876        final String[] instructionSets;
24877        final List<String> codePaths;
24878        final String oatDir;
24879        final PackageParser.Package pkg;
24880        synchronized (mPackages) {
24881            pkg = mPackages.get(packageName);
24882        }
24883        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24884        codePaths = pkg.getAllCodePaths();
24885        oatDir = getOatDir(pkg);
24886
24887        for (String codePath : codePaths) {
24888            for (String isa : instructionSets) {
24889                try {
24890                    mInstaller.deleteOdex(codePath, isa, oatDir);
24891                } catch (InstallerException e) {
24892                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24893                }
24894            }
24895        }
24896    }
24897
24898    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24899        Set<String> unusedPackages = new HashSet<>();
24900        long currentTimeInMillis = System.currentTimeMillis();
24901        synchronized (mPackages) {
24902            for (PackageParser.Package pkg : mPackages.values()) {
24903                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24904                if (ps == null) {
24905                    continue;
24906                }
24907                PackageDexUsage.PackageUseInfo packageUseInfo =
24908                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24909                if (PackageManagerServiceUtils
24910                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24911                                downgradeTimeThresholdMillis, packageUseInfo,
24912                                pkg.getLatestPackageUseTimeInMills(),
24913                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24914                    unusedPackages.add(pkg.packageName);
24915                }
24916            }
24917        }
24918        return unusedPackages;
24919    }
24920}
24921
24922interface PackageSender {
24923    void sendPackageBroadcast(final String action, final String pkg,
24924        final Bundle extras, final int flags, final String targetPkg,
24925        final IIntentReceiver finishedReceiver, final int[] userIds);
24926    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24927        boolean includeStopped, int appId, int... userIds);
24928}
24929