PackageManagerService.java revision 03e5215708d498221f024641cd0f58a395f1df4b
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.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.TimingsTraceLog;
233import android.util.DisplayMetrics;
234import android.util.EventLog;
235import android.util.ExceptionUtils;
236import android.util.Log;
237import android.util.LogPrinter;
238import android.util.MathUtils;
239import android.util.PackageUtils;
240import android.util.Pair;
241import android.util.PrintStreamPrinter;
242import android.util.Slog;
243import android.util.SparseArray;
244import android.util.SparseBooleanArray;
245import android.util.SparseIntArray;
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.storage.DeviceStorageMonitorInternal;
292
293import dalvik.system.CloseGuard;
294import dalvik.system.DexFile;
295import dalvik.system.VMRuntime;
296
297import libcore.io.IoUtils;
298import libcore.io.Streams;
299import libcore.util.EmptyArray;
300
301import org.xmlpull.v1.XmlPullParser;
302import org.xmlpull.v1.XmlPullParserException;
303import org.xmlpull.v1.XmlSerializer;
304
305import java.io.BufferedOutputStream;
306import java.io.BufferedReader;
307import java.io.ByteArrayInputStream;
308import java.io.ByteArrayOutputStream;
309import java.io.File;
310import java.io.FileDescriptor;
311import java.io.FileInputStream;
312import java.io.FileOutputStream;
313import java.io.FileReader;
314import java.io.FilenameFilter;
315import java.io.IOException;
316import java.io.InputStream;
317import java.io.OutputStream;
318import java.io.PrintWriter;
319import java.lang.annotation.Retention;
320import java.lang.annotation.RetentionPolicy;
321import java.nio.charset.StandardCharsets;
322import java.security.DigestInputStream;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325import java.security.PublicKey;
326import java.security.SecureRandom;
327import java.security.cert.Certificate;
328import java.security.cert.CertificateEncodingException;
329import java.security.cert.CertificateException;
330import java.text.SimpleDateFormat;
331import java.util.ArrayList;
332import java.util.Arrays;
333import java.util.Collection;
334import java.util.Collections;
335import java.util.Comparator;
336import java.util.Date;
337import java.util.HashMap;
338import java.util.HashSet;
339import java.util.Iterator;
340import java.util.List;
341import java.util.Map;
342import java.util.Objects;
343import java.util.Set;
344import java.util.concurrent.CountDownLatch;
345import java.util.concurrent.Future;
346import java.util.concurrent.TimeUnit;
347import java.util.concurrent.atomic.AtomicBoolean;
348import java.util.concurrent.atomic.AtomicInteger;
349import java.util.zip.GZIPInputStream;
350
351/**
352 * Keep track of all those APKs everywhere.
353 * <p>
354 * Internally there are two important locks:
355 * <ul>
356 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
357 * and other related state. It is a fine-grained lock that should only be held
358 * momentarily, as it's one of the most contended locks in the system.
359 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
360 * operations typically involve heavy lifting of application data on disk. Since
361 * {@code installd} is single-threaded, and it's operations can often be slow,
362 * this lock should never be acquired while already holding {@link #mPackages}.
363 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
364 * holding {@link #mInstallLock}.
365 * </ul>
366 * Many internal methods rely on the caller to hold the appropriate locks, and
367 * this contract is expressed through method name suffixes:
368 * <ul>
369 * <li>fooLI(): the caller must hold {@link #mInstallLock}
370 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
371 * being modified must be frozen
372 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
373 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
374 * </ul>
375 * <p>
376 * Because this class is very central to the platform's security; please run all
377 * CTS and unit tests whenever making modifications:
378 *
379 * <pre>
380 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
381 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
382 * </pre>
383 */
384public class PackageManagerService extends IPackageManager.Stub
385        implements PackageSender {
386    static final String TAG = "PackageManager";
387    static final boolean DEBUG_SETTINGS = false;
388    static final boolean DEBUG_PREFERRED = false;
389    static final boolean DEBUG_UPGRADE = false;
390    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
391    private static final boolean DEBUG_BACKUP = false;
392    private static final boolean DEBUG_INSTALL = false;
393    private static final boolean DEBUG_REMOVE = false;
394    private static final boolean DEBUG_BROADCASTS = false;
395    private static final boolean DEBUG_SHOW_INFO = false;
396    private static final boolean DEBUG_PACKAGE_INFO = false;
397    private static final boolean DEBUG_INTENT_MATCHING = false;
398    private static final boolean DEBUG_PACKAGE_SCANNING = false;
399    private static final boolean DEBUG_VERIFY = false;
400    private static final boolean DEBUG_FILTERS = false;
401    private static final boolean DEBUG_PERMISSIONS = false;
402    private static final boolean DEBUG_SHARED_LIBRARIES = false;
403    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
404
405    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
406    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
407    // user, but by default initialize to this.
408    public static final boolean DEBUG_DEXOPT = false;
409
410    private static final boolean DEBUG_ABI_SELECTION = false;
411    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
412    private static final boolean DEBUG_TRIAGED_MISSING = false;
413    private static final boolean DEBUG_APP_DATA = false;
414
415    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
416    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
417
418    private static final boolean HIDE_EPHEMERAL_APIS = false;
419
420    private static final boolean ENABLE_FREE_CACHE_V2 =
421            SystemProperties.getBoolean("fw.free_cache_v2", true);
422
423    private static final int RADIO_UID = Process.PHONE_UID;
424    private static final int LOG_UID = Process.LOG_UID;
425    private static final int NFC_UID = Process.NFC_UID;
426    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
427    private static final int SHELL_UID = Process.SHELL_UID;
428
429    // Cap the size of permission trees that 3rd party apps can define
430    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
431
432    // Suffix used during package installation when copying/moving
433    // package apks to install directory.
434    private static final String INSTALL_PACKAGE_SUFFIX = "-";
435
436    static final int SCAN_NO_DEX = 1<<1;
437    static final int SCAN_FORCE_DEX = 1<<2;
438    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
439    static final int SCAN_NEW_INSTALL = 1<<4;
440    static final int SCAN_UPDATE_TIME = 1<<5;
441    static final int SCAN_BOOTING = 1<<6;
442    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
443    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
444    static final int SCAN_REPLACING = 1<<9;
445    static final int SCAN_REQUIRE_KNOWN = 1<<10;
446    static final int SCAN_MOVE = 1<<11;
447    static final int SCAN_INITIAL = 1<<12;
448    static final int SCAN_CHECK_ONLY = 1<<13;
449    static final int SCAN_DONT_KILL_APP = 1<<14;
450    static final int SCAN_IGNORE_FROZEN = 1<<15;
451    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
452    static final int SCAN_AS_INSTANT_APP = 1<<17;
453    static final int SCAN_AS_FULL_APP = 1<<18;
454    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
455    /** Should not be with the scan flags */
456    static final int FLAGS_REMOVE_CHATTY = 1<<31;
457
458    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
459    /** Extension of the compressed packages */
460    private final static String COMPRESSED_EXTENSION = ".gz";
461    /** Suffix of stub packages on the system partition */
462    private final static String STUB_SUFFIX = "-Stub";
463
464    private static final int[] EMPTY_INT_ARRAY = new int[0];
465
466    private static final int TYPE_UNKNOWN = 0;
467    private static final int TYPE_ACTIVITY = 1;
468    private static final int TYPE_RECEIVER = 2;
469    private static final int TYPE_SERVICE = 3;
470    private static final int TYPE_PROVIDER = 4;
471    @IntDef(prefix = { "TYPE_" }, value = {
472            TYPE_UNKNOWN,
473            TYPE_ACTIVITY,
474            TYPE_RECEIVER,
475            TYPE_SERVICE,
476            TYPE_PROVIDER,
477    })
478    @Retention(RetentionPolicy.SOURCE)
479    public @interface ComponentType {}
480
481    /**
482     * Timeout (in milliseconds) after which the watchdog should declare that
483     * our handler thread is wedged.  The usual default for such things is one
484     * minute but we sometimes do very lengthy I/O operations on this thread,
485     * such as installing multi-gigabyte applications, so ours needs to be longer.
486     */
487    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
488
489    /**
490     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
491     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
492     * settings entry if available, otherwise we use the hardcoded default.  If it's been
493     * more than this long since the last fstrim, we force one during the boot sequence.
494     *
495     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
496     * one gets run at the next available charging+idle time.  This final mandatory
497     * no-fstrim check kicks in only of the other scheduling criteria is never met.
498     */
499    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
500
501    /**
502     * Whether verification is enabled by default.
503     */
504    private static final boolean DEFAULT_VERIFY_ENABLE = true;
505
506    /**
507     * The default maximum time to wait for the verification agent to return in
508     * milliseconds.
509     */
510    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
511
512    /**
513     * The default response for package verification timeout.
514     *
515     * This can be either PackageManager.VERIFICATION_ALLOW or
516     * PackageManager.VERIFICATION_REJECT.
517     */
518    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
519
520    static final String PLATFORM_PACKAGE_NAME = "android";
521
522    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
523
524    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
525            DEFAULT_CONTAINER_PACKAGE,
526            "com.android.defcontainer.DefaultContainerService");
527
528    private static final String KILL_APP_REASON_GIDS_CHANGED =
529            "permission grant or revoke changed gids";
530
531    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
532            "permissions revoked";
533
534    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
535
536    private static final String PACKAGE_SCHEME = "package";
537
538    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
539
540    /** Permission grant: not grant the permission. */
541    private static final int GRANT_DENIED = 1;
542
543    /** Permission grant: grant the permission as an install permission. */
544    private static final int GRANT_INSTALL = 2;
545
546    /** Permission grant: grant the permission as a runtime one. */
547    private static final int GRANT_RUNTIME = 3;
548
549    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
550    private static final int GRANT_UPGRADE = 4;
551
552    /** Canonical intent used to identify what counts as a "web browser" app */
553    private static final Intent sBrowserIntent;
554    static {
555        sBrowserIntent = new Intent();
556        sBrowserIntent.setAction(Intent.ACTION_VIEW);
557        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
558        sBrowserIntent.setData(Uri.parse("http:"));
559    }
560
561    /**
562     * The set of all protected actions [i.e. those actions for which a high priority
563     * intent filter is disallowed].
564     */
565    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
566    static {
567        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
568        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
569        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
570        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
571    }
572
573    // Compilation reasons.
574    public static final int REASON_FIRST_BOOT = 0;
575    public static final int REASON_BOOT = 1;
576    public static final int REASON_INSTALL = 2;
577    public static final int REASON_BACKGROUND_DEXOPT = 3;
578    public static final int REASON_AB_OTA = 4;
579    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
580
581    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
582
583    /** All dangerous permission names in the same order as the events in MetricsEvent */
584    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
585            Manifest.permission.READ_CALENDAR,
586            Manifest.permission.WRITE_CALENDAR,
587            Manifest.permission.CAMERA,
588            Manifest.permission.READ_CONTACTS,
589            Manifest.permission.WRITE_CONTACTS,
590            Manifest.permission.GET_ACCOUNTS,
591            Manifest.permission.ACCESS_FINE_LOCATION,
592            Manifest.permission.ACCESS_COARSE_LOCATION,
593            Manifest.permission.RECORD_AUDIO,
594            Manifest.permission.READ_PHONE_STATE,
595            Manifest.permission.CALL_PHONE,
596            Manifest.permission.READ_CALL_LOG,
597            Manifest.permission.WRITE_CALL_LOG,
598            Manifest.permission.ADD_VOICEMAIL,
599            Manifest.permission.USE_SIP,
600            Manifest.permission.PROCESS_OUTGOING_CALLS,
601            Manifest.permission.READ_CELL_BROADCASTS,
602            Manifest.permission.BODY_SENSORS,
603            Manifest.permission.SEND_SMS,
604            Manifest.permission.RECEIVE_SMS,
605            Manifest.permission.READ_SMS,
606            Manifest.permission.RECEIVE_WAP_PUSH,
607            Manifest.permission.RECEIVE_MMS,
608            Manifest.permission.READ_EXTERNAL_STORAGE,
609            Manifest.permission.WRITE_EXTERNAL_STORAGE,
610            Manifest.permission.READ_PHONE_NUMBERS,
611            Manifest.permission.ANSWER_PHONE_CALLS);
612
613
614    /**
615     * Version number for the package parser cache. Increment this whenever the format or
616     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
617     */
618    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
619
620    /**
621     * Whether the package parser cache is enabled.
622     */
623    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
624
625    final ServiceThread mHandlerThread;
626
627    final PackageHandler mHandler;
628
629    private final ProcessLoggingHandler mProcessLoggingHandler;
630
631    /**
632     * Messages for {@link #mHandler} that need to wait for system ready before
633     * being dispatched.
634     */
635    private ArrayList<Message> mPostSystemReadyMessages;
636
637    final int mSdkVersion = Build.VERSION.SDK_INT;
638
639    final Context mContext;
640    final boolean mFactoryTest;
641    final boolean mOnlyCore;
642    final DisplayMetrics mMetrics;
643    final int mDefParseFlags;
644    final String[] mSeparateProcesses;
645    final boolean mIsUpgrade;
646    final boolean mIsPreNUpgrade;
647    final boolean mIsPreNMR1Upgrade;
648
649    // Have we told the Activity Manager to whitelist the default container service by uid yet?
650    @GuardedBy("mPackages")
651    boolean mDefaultContainerWhitelisted = false;
652
653    @GuardedBy("mPackages")
654    private boolean mDexOptDialogShown;
655
656    /** The location for ASEC container files on internal storage. */
657    final String mAsecInternalPath;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed third-party apps stored */
665    final File mAppInstallDir;
666
667    /**
668     * Directory to which applications installed internally have their
669     * 32 bit native libraries copied.
670     */
671    private File mAppLib32InstallDir;
672
673    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
674    // apps.
675    final File mDrmAppPrivateInstallDir;
676
677    // ----------------------------------------------------------------
678
679    // Lock for state used when installing and doing other long running
680    // operations.  Methods that must be called with this lock held have
681    // the suffix "LI".
682    final Object mInstallLock = new Object();
683
684    // ----------------------------------------------------------------
685
686    // Keys are String (package name), values are Package.  This also serves
687    // as the lock for the global state.  Methods that must be called with
688    // this lock held have the prefix "LP".
689    @GuardedBy("mPackages")
690    final ArrayMap<String, PackageParser.Package> mPackages =
691            new ArrayMap<String, PackageParser.Package>();
692
693    final ArrayMap<String, Set<String>> mKnownCodebase =
694            new ArrayMap<String, Set<String>>();
695
696    // Keys are isolated uids and values are the uid of the application
697    // that created the isolated proccess.
698    @GuardedBy("mPackages")
699    final SparseIntArray mIsolatedOwners = new SparseIntArray();
700
701    /**
702     * Tracks new system packages [received in an OTA] that we expect to
703     * find updated user-installed versions. Keys are package name, values
704     * are package location.
705     */
706    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
707    /**
708     * Tracks high priority intent filters for protected actions. During boot, certain
709     * filter actions are protected and should never be allowed to have a high priority
710     * intent filter for them. However, there is one, and only one exception -- the
711     * setup wizard. It must be able to define a high priority intent filter for these
712     * actions to ensure there are no escapes from the wizard. We need to delay processing
713     * of these during boot as we need to look at all of the system packages in order
714     * to know which component is the setup wizard.
715     */
716    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
717    /**
718     * Whether or not processing protected filters should be deferred.
719     */
720    private boolean mDeferProtectedFilters = true;
721
722    /**
723     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
724     */
725    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
726    /**
727     * Whether or not system app permissions should be promoted from install to runtime.
728     */
729    boolean mPromoteSystemApps;
730
731    @GuardedBy("mPackages")
732    final Settings mSettings;
733
734    /**
735     * Set of package names that are currently "frozen", which means active
736     * surgery is being done on the code/data for that package. The platform
737     * will refuse to launch frozen packages to avoid race conditions.
738     *
739     * @see PackageFreezer
740     */
741    @GuardedBy("mPackages")
742    final ArraySet<String> mFrozenPackages = new ArraySet<>();
743
744    final ProtectedPackages mProtectedPackages;
745
746    @GuardedBy("mLoadedVolumes")
747    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
748
749    boolean mFirstBoot;
750
751    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
752
753    // System configuration read by SystemConfig.
754    final int[] mGlobalGids;
755    final SparseArray<ArraySet<String>> mSystemPermissions;
756    @GuardedBy("mAvailableFeatures")
757    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
758
759    // If mac_permissions.xml was found for seinfo labeling.
760    boolean mFoundPolicyFile;
761
762    private final InstantAppRegistry mInstantAppRegistry;
763
764    @GuardedBy("mPackages")
765    int mChangedPackagesSequenceNumber;
766    /**
767     * List of changed [installed, removed or updated] packages.
768     * mapping from user id -> sequence number -> package name
769     */
770    @GuardedBy("mPackages")
771    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
772    /**
773     * The sequence number of the last change to a package.
774     * mapping from user id -> package name -> sequence number
775     */
776    @GuardedBy("mPackages")
777    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
778
779    class PackageParserCallback implements PackageParser.Callback {
780        @Override public final boolean hasFeature(String feature) {
781            return PackageManagerService.this.hasSystemFeature(feature, 0);
782        }
783
784        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
785                Collection<PackageParser.Package> allPackages, String targetPackageName) {
786            List<PackageParser.Package> overlayPackages = null;
787            for (PackageParser.Package p : allPackages) {
788                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
789                    if (overlayPackages == null) {
790                        overlayPackages = new ArrayList<PackageParser.Package>();
791                    }
792                    overlayPackages.add(p);
793                }
794            }
795            if (overlayPackages != null) {
796                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
797                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
798                        return p1.mOverlayPriority - p2.mOverlayPriority;
799                    }
800                };
801                Collections.sort(overlayPackages, cmp);
802            }
803            return overlayPackages;
804        }
805
806        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
807                String targetPackageName, String targetPath) {
808            if ("android".equals(targetPackageName)) {
809                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
810                // native AssetManager.
811                return null;
812            }
813            List<PackageParser.Package> overlayPackages =
814                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
815            if (overlayPackages == null || overlayPackages.isEmpty()) {
816                return null;
817            }
818            List<String> overlayPathList = null;
819            for (PackageParser.Package overlayPackage : overlayPackages) {
820                if (targetPath == null) {
821                    if (overlayPathList == null) {
822                        overlayPathList = new ArrayList<String>();
823                    }
824                    overlayPathList.add(overlayPackage.baseCodePath);
825                    continue;
826                }
827
828                try {
829                    // Creates idmaps for system to parse correctly the Android manifest of the
830                    // target package.
831                    //
832                    // OverlayManagerService will update each of them with a correct gid from its
833                    // target package app id.
834                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
835                            UserHandle.getSharedAppGid(
836                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
837                    if (overlayPathList == null) {
838                        overlayPathList = new ArrayList<String>();
839                    }
840                    overlayPathList.add(overlayPackage.baseCodePath);
841                } catch (InstallerException e) {
842                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
843                            overlayPackage.baseCodePath);
844                }
845            }
846            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
847        }
848
849        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
850            synchronized (mPackages) {
851                return getStaticOverlayPathsLocked(
852                        mPackages.values(), targetPackageName, targetPath);
853            }
854        }
855
856        @Override public final String[] getOverlayApks(String targetPackageName) {
857            return getStaticOverlayPaths(targetPackageName, null);
858        }
859
860        @Override public final String[] getOverlayPaths(String targetPackageName,
861                String targetPath) {
862            return getStaticOverlayPaths(targetPackageName, targetPath);
863        }
864    };
865
866    class ParallelPackageParserCallback extends PackageParserCallback {
867        List<PackageParser.Package> mOverlayPackages = null;
868
869        void findStaticOverlayPackages() {
870            synchronized (mPackages) {
871                for (PackageParser.Package p : mPackages.values()) {
872                    if (p.mIsStaticOverlay) {
873                        if (mOverlayPackages == null) {
874                            mOverlayPackages = new ArrayList<PackageParser.Package>();
875                        }
876                        mOverlayPackages.add(p);
877                    }
878                }
879            }
880        }
881
882        @Override
883        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
884            // We can trust mOverlayPackages without holding mPackages because package uninstall
885            // can't happen while running parallel parsing.
886            // Moreover holding mPackages on each parsing thread causes dead-lock.
887            return mOverlayPackages == null ? null :
888                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
889        }
890    }
891
892    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
893    final ParallelPackageParserCallback mParallelPackageParserCallback =
894            new ParallelPackageParserCallback();
895
896    public static final class SharedLibraryEntry {
897        public final @Nullable String path;
898        public final @Nullable String apk;
899        public final @NonNull SharedLibraryInfo info;
900
901        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
902                String declaringPackageName, int declaringPackageVersionCode) {
903            path = _path;
904            apk = _apk;
905            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
906                    declaringPackageName, declaringPackageVersionCode), null);
907        }
908    }
909
910    // Currently known shared libraries.
911    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
912    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
913            new ArrayMap<>();
914
915    // All available activities, for your resolving pleasure.
916    final ActivityIntentResolver mActivities =
917            new ActivityIntentResolver();
918
919    // All available receivers, for your resolving pleasure.
920    final ActivityIntentResolver mReceivers =
921            new ActivityIntentResolver();
922
923    // All available services, for your resolving pleasure.
924    final ServiceIntentResolver mServices = new ServiceIntentResolver();
925
926    // All available providers, for your resolving pleasure.
927    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
928
929    // Mapping from provider base names (first directory in content URI codePath)
930    // to the provider information.
931    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
932            new ArrayMap<String, PackageParser.Provider>();
933
934    // Mapping from instrumentation class names to info about them.
935    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
936            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
937
938    // Mapping from permission names to info about them.
939    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
940            new ArrayMap<String, PackageParser.PermissionGroup>();
941
942    // Packages whose data we have transfered into another package, thus
943    // should no longer exist.
944    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
945
946    // Broadcast actions that are only available to the system.
947    @GuardedBy("mProtectedBroadcasts")
948    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
949
950    /** List of packages waiting for verification. */
951    final SparseArray<PackageVerificationState> mPendingVerification
952            = new SparseArray<PackageVerificationState>();
953
954    /** Set of packages associated with each app op permission. */
955    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
956
957    final PackageInstallerService mInstallerService;
958
959    private final PackageDexOptimizer mPackageDexOptimizer;
960    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
961    // is used by other apps).
962    private final DexManager mDexManager;
963
964    private AtomicInteger mNextMoveId = new AtomicInteger();
965    private final MoveCallbacks mMoveCallbacks;
966
967    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
968
969    // Cache of users who need badging.
970    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
971
972    /** Token for keys in mPendingVerification. */
973    private int mPendingVerificationToken = 0;
974
975    volatile boolean mSystemReady;
976    volatile boolean mSafeMode;
977    volatile boolean mHasSystemUidErrors;
978    private volatile boolean mEphemeralAppsDisabled;
979
980    ApplicationInfo mAndroidApplication;
981    final ActivityInfo mResolveActivity = new ActivityInfo();
982    final ResolveInfo mResolveInfo = new ResolveInfo();
983    ComponentName mResolveComponentName;
984    PackageParser.Package mPlatformPackage;
985    ComponentName mCustomResolverComponentName;
986
987    boolean mResolverReplaced = false;
988
989    private final @Nullable ComponentName mIntentFilterVerifierComponent;
990    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
991
992    private int mIntentFilterVerificationToken = 0;
993
994    /** The service connection to the ephemeral resolver */
995    final EphemeralResolverConnection mInstantAppResolverConnection;
996    /** Component used to show resolver settings for Instant Apps */
997    final ComponentName mInstantAppResolverSettingsComponent;
998
999    /** Activity used to install instant applications */
1000    ActivityInfo mInstantAppInstallerActivity;
1001    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1002
1003    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1004            = new SparseArray<IntentFilterVerificationState>();
1005
1006    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1007
1008    // List of packages names to keep cached, even if they are uninstalled for all users
1009    private List<String> mKeepUninstalledPackages;
1010
1011    private UserManagerInternal mUserManagerInternal;
1012
1013    private DeviceIdleController.LocalService mDeviceIdleController;
1014
1015    private File mCacheDir;
1016
1017    private ArraySet<String> mPrivappPermissionsViolations;
1018
1019    private Future<?> mPrepareAppDataFuture;
1020
1021    private static class IFVerificationParams {
1022        PackageParser.Package pkg;
1023        boolean replacing;
1024        int userId;
1025        int verifierUid;
1026
1027        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1028                int _userId, int _verifierUid) {
1029            pkg = _pkg;
1030            replacing = _replacing;
1031            userId = _userId;
1032            replacing = _replacing;
1033            verifierUid = _verifierUid;
1034        }
1035    }
1036
1037    private interface IntentFilterVerifier<T extends IntentFilter> {
1038        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1039                                               T filter, String packageName);
1040        void startVerifications(int userId);
1041        void receiveVerificationResponse(int verificationId);
1042    }
1043
1044    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1045        private Context mContext;
1046        private ComponentName mIntentFilterVerifierComponent;
1047        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1048
1049        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1050            mContext = context;
1051            mIntentFilterVerifierComponent = verifierComponent;
1052        }
1053
1054        private String getDefaultScheme() {
1055            return IntentFilter.SCHEME_HTTPS;
1056        }
1057
1058        @Override
1059        public void startVerifications(int userId) {
1060            // Launch verifications requests
1061            int count = mCurrentIntentFilterVerifications.size();
1062            for (int n=0; n<count; n++) {
1063                int verificationId = mCurrentIntentFilterVerifications.get(n);
1064                final IntentFilterVerificationState ivs =
1065                        mIntentFilterVerificationStates.get(verificationId);
1066
1067                String packageName = ivs.getPackageName();
1068
1069                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1070                final int filterCount = filters.size();
1071                ArraySet<String> domainsSet = new ArraySet<>();
1072                for (int m=0; m<filterCount; m++) {
1073                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1074                    domainsSet.addAll(filter.getHostsList());
1075                }
1076                synchronized (mPackages) {
1077                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1078                            packageName, domainsSet) != null) {
1079                        scheduleWriteSettingsLocked();
1080                    }
1081                }
1082                sendVerificationRequest(verificationId, ivs);
1083            }
1084            mCurrentIntentFilterVerifications.clear();
1085        }
1086
1087        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1088            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1091                    verificationId);
1092            verificationIntent.putExtra(
1093                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1094                    getDefaultScheme());
1095            verificationIntent.putExtra(
1096                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1097                    ivs.getHostsString());
1098            verificationIntent.putExtra(
1099                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1100                    ivs.getPackageName());
1101            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1102            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1103
1104            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1105            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1106                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1107                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1108
1109            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1110            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1111                    "Sending IntentFilter verification broadcast");
1112        }
1113
1114        public void receiveVerificationResponse(int verificationId) {
1115            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1116
1117            final boolean verified = ivs.isVerified();
1118
1119            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1120            final int count = filters.size();
1121            if (DEBUG_DOMAIN_VERIFICATION) {
1122                Slog.i(TAG, "Received verification response " + verificationId
1123                        + " for " + count + " filters, verified=" + verified);
1124            }
1125            for (int n=0; n<count; n++) {
1126                PackageParser.ActivityIntentInfo filter = filters.get(n);
1127                filter.setVerified(verified);
1128
1129                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1130                        + " verified with result:" + verified + " and hosts:"
1131                        + ivs.getHostsString());
1132            }
1133
1134            mIntentFilterVerificationStates.remove(verificationId);
1135
1136            final String packageName = ivs.getPackageName();
1137            IntentFilterVerificationInfo ivi = null;
1138
1139            synchronized (mPackages) {
1140                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1141            }
1142            if (ivi == null) {
1143                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1144                        + verificationId + " packageName:" + packageName);
1145                return;
1146            }
1147            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1148                    "Updating IntentFilterVerificationInfo for package " + packageName
1149                            +" verificationId:" + verificationId);
1150
1151            synchronized (mPackages) {
1152                if (verified) {
1153                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1154                } else {
1155                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1156                }
1157                scheduleWriteSettingsLocked();
1158
1159                final int userId = ivs.getUserId();
1160                if (userId != UserHandle.USER_ALL) {
1161                    final int userStatus =
1162                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1163
1164                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1165                    boolean needUpdate = false;
1166
1167                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1168                    // already been set by the User thru the Disambiguation dialog
1169                    switch (userStatus) {
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                            } else {
1174                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1175                            }
1176                            needUpdate = true;
1177                            break;
1178
1179                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1180                            if (verified) {
1181                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1182                                needUpdate = true;
1183                            }
1184                            break;
1185
1186                        default:
1187                            // Nothing to do
1188                    }
1189
1190                    if (needUpdate) {
1191                        mSettings.updateIntentFilterVerificationStatusLPw(
1192                                packageName, updatedStatus, userId);
1193                        scheduleWritePackageRestrictionsLocked(userId);
1194                    }
1195                }
1196            }
1197        }
1198
1199        @Override
1200        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1201                    ActivityIntentInfo filter, String packageName) {
1202            if (!hasValidDomains(filter)) {
1203                return false;
1204            }
1205            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1206            if (ivs == null) {
1207                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1208                        packageName);
1209            }
1210            if (DEBUG_DOMAIN_VERIFICATION) {
1211                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1212            }
1213            ivs.addFilter(filter);
1214            return true;
1215        }
1216
1217        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1218                int userId, int verificationId, String packageName) {
1219            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1220                    verifierUid, userId, packageName);
1221            ivs.setPendingState();
1222            synchronized (mPackages) {
1223                mIntentFilterVerificationStates.append(verificationId, ivs);
1224                mCurrentIntentFilterVerifications.add(verificationId);
1225            }
1226            return ivs;
1227        }
1228    }
1229
1230    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1231        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1232                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1233                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1234    }
1235
1236    // Set of pending broadcasts for aggregating enable/disable of components.
1237    static class PendingPackageBroadcasts {
1238        // for each user id, a map of <package name -> components within that package>
1239        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1240
1241        public PendingPackageBroadcasts() {
1242            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1243        }
1244
1245        public ArrayList<String> get(int userId, String packageName) {
1246            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1247            return packages.get(packageName);
1248        }
1249
1250        public void put(int userId, String packageName, ArrayList<String> components) {
1251            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1252            packages.put(packageName, components);
1253        }
1254
1255        public void remove(int userId, String packageName) {
1256            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1257            if (packages != null) {
1258                packages.remove(packageName);
1259            }
1260        }
1261
1262        public void remove(int userId) {
1263            mUidMap.remove(userId);
1264        }
1265
1266        public int userIdCount() {
1267            return mUidMap.size();
1268        }
1269
1270        public int userIdAt(int n) {
1271            return mUidMap.keyAt(n);
1272        }
1273
1274        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1275            return mUidMap.get(userId);
1276        }
1277
1278        public int size() {
1279            // total number of pending broadcast entries across all userIds
1280            int num = 0;
1281            for (int i = 0; i< mUidMap.size(); i++) {
1282                num += mUidMap.valueAt(i).size();
1283            }
1284            return num;
1285        }
1286
1287        public void clear() {
1288            mUidMap.clear();
1289        }
1290
1291        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1292            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1293            if (map == null) {
1294                map = new ArrayMap<String, ArrayList<String>>();
1295                mUidMap.put(userId, map);
1296            }
1297            return map;
1298        }
1299    }
1300    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1301
1302    // Service Connection to remote media container service to copy
1303    // package uri's from external media onto secure containers
1304    // or internal storage.
1305    private IMediaContainerService mContainerService = null;
1306
1307    static final int SEND_PENDING_BROADCAST = 1;
1308    static final int MCS_BOUND = 3;
1309    static final int END_COPY = 4;
1310    static final int INIT_COPY = 5;
1311    static final int MCS_UNBIND = 6;
1312    static final int START_CLEANING_PACKAGE = 7;
1313    static final int FIND_INSTALL_LOC = 8;
1314    static final int POST_INSTALL = 9;
1315    static final int MCS_RECONNECT = 10;
1316    static final int MCS_GIVE_UP = 11;
1317    static final int UPDATED_MEDIA_STATUS = 12;
1318    static final int WRITE_SETTINGS = 13;
1319    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1320    static final int PACKAGE_VERIFIED = 15;
1321    static final int CHECK_PENDING_VERIFICATION = 16;
1322    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1323    static final int INTENT_FILTER_VERIFIED = 18;
1324    static final int WRITE_PACKAGE_LIST = 19;
1325    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1326
1327    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1328
1329    // Delay time in millisecs
1330    static final int BROADCAST_DELAY = 10 * 1000;
1331
1332    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1333            2 * 60 * 60 * 1000L; /* two hours */
1334
1335    static UserManagerService sUserManager;
1336
1337    // Stores a list of users whose package restrictions file needs to be updated
1338    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1339
1340    final private DefaultContainerConnection mDefContainerConn =
1341            new DefaultContainerConnection();
1342    class DefaultContainerConnection implements ServiceConnection {
1343        public void onServiceConnected(ComponentName name, IBinder service) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1345            final IMediaContainerService imcs = IMediaContainerService.Stub
1346                    .asInterface(Binder.allowBlocking(service));
1347            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1348        }
1349
1350        public void onServiceDisconnected(ComponentName name) {
1351            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1352        }
1353    }
1354
1355    // Recordkeeping of restore-after-install operations that are currently in flight
1356    // between the Package Manager and the Backup Manager
1357    static class PostInstallData {
1358        public InstallArgs args;
1359        public PackageInstalledInfo res;
1360
1361        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1362            args = _a;
1363            res = _r;
1364        }
1365    }
1366
1367    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1368    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1369
1370    // XML tags for backup/restore of various bits of state
1371    private static final String TAG_PREFERRED_BACKUP = "pa";
1372    private static final String TAG_DEFAULT_APPS = "da";
1373    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1374
1375    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1376    private static final String TAG_ALL_GRANTS = "rt-grants";
1377    private static final String TAG_GRANT = "grant";
1378    private static final String ATTR_PACKAGE_NAME = "pkg";
1379
1380    private static final String TAG_PERMISSION = "perm";
1381    private static final String ATTR_PERMISSION_NAME = "name";
1382    private static final String ATTR_IS_GRANTED = "g";
1383    private static final String ATTR_USER_SET = "set";
1384    private static final String ATTR_USER_FIXED = "fixed";
1385    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1386
1387    // System/policy permission grants are not backed up
1388    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_POLICY_FIXED
1390            | FLAG_PERMISSION_SYSTEM_FIXED
1391            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1392
1393    // And we back up these user-adjusted states
1394    private static final int USER_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_USER_SET
1396            | FLAG_PERMISSION_USER_FIXED
1397            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1398
1399    final @Nullable String mRequiredVerifierPackage;
1400    final @NonNull String mRequiredInstallerPackage;
1401    final @NonNull String mRequiredUninstallerPackage;
1402    final @Nullable String mSetupWizardPackage;
1403    final @Nullable String mStorageManagerPackage;
1404    final @NonNull String mServicesSystemSharedLibraryPackageName;
1405    final @NonNull String mSharedSystemSharedLibraryPackageName;
1406
1407    final boolean mPermissionReviewRequired;
1408
1409    private final PackageUsage mPackageUsage = new PackageUsage();
1410    private final CompilerStats mCompilerStats = new CompilerStats();
1411
1412    class PackageHandler extends Handler {
1413        private boolean mBound = false;
1414        final ArrayList<HandlerParams> mPendingInstalls =
1415            new ArrayList<HandlerParams>();
1416
1417        private boolean connectToService() {
1418            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1419                    " DefaultContainerService");
1420            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1423                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1424                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425                mBound = true;
1426                return true;
1427            }
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429            return false;
1430        }
1431
1432        private void disconnectService() {
1433            mContainerService = null;
1434            mBound = false;
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1436            mContext.unbindService(mDefContainerConn);
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1438        }
1439
1440        PackageHandler(Looper looper) {
1441            super(looper);
1442        }
1443
1444        public void handleMessage(Message msg) {
1445            try {
1446                doHandleMessage(msg);
1447            } finally {
1448                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1449            }
1450        }
1451
1452        void doHandleMessage(Message msg) {
1453            switch (msg.what) {
1454                case INIT_COPY: {
1455                    HandlerParams params = (HandlerParams) msg.obj;
1456                    int idx = mPendingInstalls.size();
1457                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1458                    // If a bind was already initiated we dont really
1459                    // need to do anything. The pending install
1460                    // will be processed later on.
1461                    if (!mBound) {
1462                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1463                                System.identityHashCode(mHandler));
1464                        // If this is the only one pending we might
1465                        // have to bind to the service again.
1466                        if (!connectToService()) {
1467                            Slog.e(TAG, "Failed to bind to media container service");
1468                            params.serviceError();
1469                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1470                                    System.identityHashCode(mHandler));
1471                            if (params.traceMethod != null) {
1472                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1473                                        params.traceCookie);
1474                            }
1475                            return;
1476                        } else {
1477                            // Once we bind to the service, the first
1478                            // pending request will be processed.
1479                            mPendingInstalls.add(idx, params);
1480                        }
1481                    } else {
1482                        mPendingInstalls.add(idx, params);
1483                        // Already bound to the service. Just make
1484                        // sure we trigger off processing the first request.
1485                        if (idx == 0) {
1486                            mHandler.sendEmptyMessage(MCS_BOUND);
1487                        }
1488                    }
1489                    break;
1490                }
1491                case MCS_BOUND: {
1492                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1493                    if (msg.obj != null) {
1494                        mContainerService = (IMediaContainerService) msg.obj;
1495                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1496                                System.identityHashCode(mHandler));
1497                    }
1498                    if (mContainerService == null) {
1499                        if (!mBound) {
1500                            // Something seriously wrong since we are not bound and we are not
1501                            // waiting for connection. Bail out.
1502                            Slog.e(TAG, "Cannot bind to media container service");
1503                            for (HandlerParams params : mPendingInstalls) {
1504                                // Indicate service bind error
1505                                params.serviceError();
1506                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                        System.identityHashCode(params));
1508                                if (params.traceMethod != null) {
1509                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1510                                            params.traceMethod, params.traceCookie);
1511                                }
1512                                return;
1513                            }
1514                            mPendingInstalls.clear();
1515                        } else {
1516                            Slog.w(TAG, "Waiting to connect to media container service");
1517                        }
1518                    } else if (mPendingInstalls.size() > 0) {
1519                        HandlerParams params = mPendingInstalls.get(0);
1520                        if (params != null) {
1521                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                    System.identityHashCode(params));
1523                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1524                            if (params.startCopy()) {
1525                                // We are done...  look for more work or to
1526                                // go idle.
1527                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                        "Checking for more work or unbind...");
1529                                // Delete pending install
1530                                if (mPendingInstalls.size() > 0) {
1531                                    mPendingInstalls.remove(0);
1532                                }
1533                                if (mPendingInstalls.size() == 0) {
1534                                    if (mBound) {
1535                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                                "Posting delayed MCS_UNBIND");
1537                                        removeMessages(MCS_UNBIND);
1538                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1539                                        // Unbind after a little delay, to avoid
1540                                        // continual thrashing.
1541                                        sendMessageDelayed(ubmsg, 10000);
1542                                    }
1543                                } else {
1544                                    // There are more pending requests in queue.
1545                                    // Just post MCS_BOUND message to trigger processing
1546                                    // of next pending install.
1547                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                            "Posting MCS_BOUND for next work");
1549                                    mHandler.sendEmptyMessage(MCS_BOUND);
1550                                }
1551                            }
1552                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1553                        }
1554                    } else {
1555                        // Should never happen ideally.
1556                        Slog.w(TAG, "Empty queue");
1557                    }
1558                    break;
1559                }
1560                case MCS_RECONNECT: {
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1562                    if (mPendingInstalls.size() > 0) {
1563                        if (mBound) {
1564                            disconnectService();
1565                        }
1566                        if (!connectToService()) {
1567                            Slog.e(TAG, "Failed to bind to media container service");
1568                            for (HandlerParams params : mPendingInstalls) {
1569                                // Indicate service bind error
1570                                params.serviceError();
1571                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1572                                        System.identityHashCode(params));
1573                            }
1574                            mPendingInstalls.clear();
1575                        }
1576                    }
1577                    break;
1578                }
1579                case MCS_UNBIND: {
1580                    // If there is no actual work left, then time to unbind.
1581                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1582
1583                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1584                        if (mBound) {
1585                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1586
1587                            disconnectService();
1588                        }
1589                    } else if (mPendingInstalls.size() > 0) {
1590                        // There are more pending requests in queue.
1591                        // Just post MCS_BOUND message to trigger processing
1592                        // of next pending install.
1593                        mHandler.sendEmptyMessage(MCS_BOUND);
1594                    }
1595
1596                    break;
1597                }
1598                case MCS_GIVE_UP: {
1599                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1600                    HandlerParams params = mPendingInstalls.remove(0);
1601                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1602                            System.identityHashCode(params));
1603                    break;
1604                }
1605                case SEND_PENDING_BROADCAST: {
1606                    String packages[];
1607                    ArrayList<String> components[];
1608                    int size = 0;
1609                    int uids[];
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    synchronized (mPackages) {
1612                        if (mPendingBroadcasts == null) {
1613                            return;
1614                        }
1615                        size = mPendingBroadcasts.size();
1616                        if (size <= 0) {
1617                            // Nothing to be done. Just return
1618                            return;
1619                        }
1620                        packages = new String[size];
1621                        components = new ArrayList[size];
1622                        uids = new int[size];
1623                        int i = 0;  // filling out the above arrays
1624
1625                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1626                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1627                            Iterator<Map.Entry<String, ArrayList<String>>> it
1628                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1629                                            .entrySet().iterator();
1630                            while (it.hasNext() && i < size) {
1631                                Map.Entry<String, ArrayList<String>> ent = it.next();
1632                                packages[i] = ent.getKey();
1633                                components[i] = ent.getValue();
1634                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1635                                uids[i] = (ps != null)
1636                                        ? UserHandle.getUid(packageUserId, ps.appId)
1637                                        : -1;
1638                                i++;
1639                            }
1640                        }
1641                        size = i;
1642                        mPendingBroadcasts.clear();
1643                    }
1644                    // Send broadcasts
1645                    for (int i = 0; i < size; i++) {
1646                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                    break;
1650                }
1651                case START_CLEANING_PACKAGE: {
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1653                    final String packageName = (String)msg.obj;
1654                    final int userId = msg.arg1;
1655                    final boolean andCode = msg.arg2 != 0;
1656                    synchronized (mPackages) {
1657                        if (userId == UserHandle.USER_ALL) {
1658                            int[] users = sUserManager.getUserIds();
1659                            for (int user : users) {
1660                                mSettings.addPackageToCleanLPw(
1661                                        new PackageCleanItem(user, packageName, andCode));
1662                            }
1663                        } else {
1664                            mSettings.addPackageToCleanLPw(
1665                                    new PackageCleanItem(userId, packageName, andCode));
1666                        }
1667                    }
1668                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1669                    startCleaningPackages();
1670                } break;
1671                case POST_INSTALL: {
1672                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1673
1674                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1675                    final boolean didRestore = (msg.arg2 != 0);
1676                    mRunningInstalls.delete(msg.arg1);
1677
1678                    if (data != null) {
1679                        InstallArgs args = data.args;
1680                        PackageInstalledInfo parentRes = data.res;
1681
1682                        final boolean grantPermissions = (args.installFlags
1683                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1684                        final boolean killApp = (args.installFlags
1685                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1686                        final boolean virtualPreload = ((args.installFlags
1687                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1688                        final String[] grantedPermissions = args.installGrantPermissions;
1689
1690                        // Handle the parent package
1691                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1692                                virtualPreload, grantedPermissions, didRestore,
1693                                args.installerPackageName, args.observer);
1694
1695                        // Handle the child packages
1696                        final int childCount = (parentRes.addedChildPackages != null)
1697                                ? parentRes.addedChildPackages.size() : 0;
1698                        for (int i = 0; i < childCount; i++) {
1699                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1700                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1701                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1702                                    args.installerPackageName, args.observer);
1703                        }
1704
1705                        // Log tracing if needed
1706                        if (args.traceMethod != null) {
1707                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1708                                    args.traceCookie);
1709                        }
1710                    } else {
1711                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1712                    }
1713
1714                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1715                } break;
1716                case UPDATED_MEDIA_STATUS: {
1717                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1718                    boolean reportStatus = msg.arg1 == 1;
1719                    boolean doGc = msg.arg2 == 1;
1720                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1721                    if (doGc) {
1722                        // Force a gc to clear up stale containers.
1723                        Runtime.getRuntime().gc();
1724                    }
1725                    if (msg.obj != null) {
1726                        @SuppressWarnings("unchecked")
1727                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1728                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1729                        // Unload containers
1730                        unloadAllContainers(args);
1731                    }
1732                    if (reportStatus) {
1733                        try {
1734                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1735                                    "Invoking StorageManagerService call back");
1736                            PackageHelper.getStorageManager().finishMediaUpdate();
1737                        } catch (RemoteException e) {
1738                            Log.e(TAG, "StorageManagerService not running?");
1739                        }
1740                    }
1741                } break;
1742                case WRITE_SETTINGS: {
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1744                    synchronized (mPackages) {
1745                        removeMessages(WRITE_SETTINGS);
1746                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1747                        mSettings.writeLPr();
1748                        mDirtyUsers.clear();
1749                    }
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1751                } break;
1752                case WRITE_PACKAGE_RESTRICTIONS: {
1753                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1754                    synchronized (mPackages) {
1755                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1756                        for (int userId : mDirtyUsers) {
1757                            mSettings.writePackageRestrictionsLPr(userId);
1758                        }
1759                        mDirtyUsers.clear();
1760                    }
1761                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1762                } break;
1763                case WRITE_PACKAGE_LIST: {
1764                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1765                    synchronized (mPackages) {
1766                        removeMessages(WRITE_PACKAGE_LIST);
1767                        mSettings.writePackageListLPr(msg.arg1);
1768                    }
1769                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1770                } break;
1771                case CHECK_PENDING_VERIFICATION: {
1772                    final int verificationId = msg.arg1;
1773                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1774
1775                    if ((state != null) && !state.timeoutExtended()) {
1776                        final InstallArgs args = state.getInstallArgs();
1777                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1778
1779                        Slog.i(TAG, "Verification timed out for " + originUri);
1780                        mPendingVerification.remove(verificationId);
1781
1782                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1783
1784                        final UserHandle user = args.getUser();
1785                        if (getDefaultVerificationResponse(user)
1786                                == PackageManager.VERIFICATION_ALLOW) {
1787                            Slog.i(TAG, "Continuing with installation of " + originUri);
1788                            state.setVerifierResponse(Binder.getCallingUid(),
1789                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1790                            broadcastPackageVerified(verificationId, originUri,
1791                                    PackageManager.VERIFICATION_ALLOW, user);
1792                            try {
1793                                ret = args.copyApk(mContainerService, true);
1794                            } catch (RemoteException e) {
1795                                Slog.e(TAG, "Could not contact the ContainerService");
1796                            }
1797                        } else {
1798                            broadcastPackageVerified(verificationId, originUri,
1799                                    PackageManager.VERIFICATION_REJECT, user);
1800                        }
1801
1802                        Trace.asyncTraceEnd(
1803                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1804
1805                        processPendingInstall(args, ret);
1806                        mHandler.sendEmptyMessage(MCS_UNBIND);
1807                    }
1808                    break;
1809                }
1810                case PACKAGE_VERIFIED: {
1811                    final int verificationId = msg.arg1;
1812
1813                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1814                    if (state == null) {
1815                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1816                        break;
1817                    }
1818
1819                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1820
1821                    state.setVerifierResponse(response.callerUid, response.code);
1822
1823                    if (state.isVerificationComplete()) {
1824                        mPendingVerification.remove(verificationId);
1825
1826                        final InstallArgs args = state.getInstallArgs();
1827                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1828
1829                        int ret;
1830                        if (state.isInstallAllowed()) {
1831                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1832                            broadcastPackageVerified(verificationId, originUri,
1833                                    response.code, state.getInstallArgs().getUser());
1834                            try {
1835                                ret = args.copyApk(mContainerService, true);
1836                            } catch (RemoteException e) {
1837                                Slog.e(TAG, "Could not contact the ContainerService");
1838                            }
1839                        } else {
1840                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1841                        }
1842
1843                        Trace.asyncTraceEnd(
1844                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1845
1846                        processPendingInstall(args, ret);
1847                        mHandler.sendEmptyMessage(MCS_UNBIND);
1848                    }
1849
1850                    break;
1851                }
1852                case START_INTENT_FILTER_VERIFICATIONS: {
1853                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1854                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1855                            params.replacing, params.pkg);
1856                    break;
1857                }
1858                case INTENT_FILTER_VERIFIED: {
1859                    final int verificationId = msg.arg1;
1860
1861                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1862                            verificationId);
1863                    if (state == null) {
1864                        Slog.w(TAG, "Invalid IntentFilter verification token "
1865                                + verificationId + " received");
1866                        break;
1867                    }
1868
1869                    final int userId = state.getUserId();
1870
1871                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                            "Processing IntentFilter verification with token:"
1873                            + verificationId + " and userId:" + userId);
1874
1875                    final IntentFilterVerificationResponse response =
1876                            (IntentFilterVerificationResponse) msg.obj;
1877
1878                    state.setVerifierResponse(response.callerUid, response.code);
1879
1880                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1881                            "IntentFilter verification with token:" + verificationId
1882                            + " and userId:" + userId
1883                            + " is settings verifier response with response code:"
1884                            + response.code);
1885
1886                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1887                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1888                                + response.getFailedDomainsString());
1889                    }
1890
1891                    if (state.isVerificationComplete()) {
1892                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1893                    } else {
1894                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1895                                "IntentFilter verification with token:" + verificationId
1896                                + " was not said to be complete");
1897                    }
1898
1899                    break;
1900                }
1901                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1902                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1903                            mInstantAppResolverConnection,
1904                            (InstantAppRequest) msg.obj,
1905                            mInstantAppInstallerActivity,
1906                            mHandler);
1907                }
1908            }
1909        }
1910    }
1911
1912    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1913            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1914            boolean launchedForRestore, String installerPackage,
1915            IPackageInstallObserver2 installObserver) {
1916        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1917            // Send the removed broadcasts
1918            if (res.removedInfo != null) {
1919                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1920            }
1921
1922            // Now that we successfully installed the package, grant runtime
1923            // permissions if requested before broadcasting the install. Also
1924            // for legacy apps in permission review mode we clear the permission
1925            // review flag which is used to emulate runtime permissions for
1926            // legacy apps.
1927            if (grantPermissions) {
1928                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1929            }
1930
1931            final boolean update = res.removedInfo != null
1932                    && res.removedInfo.removedPackage != null;
1933            final String installerPackageName =
1934                    res.installerPackageName != null
1935                            ? res.installerPackageName
1936                            : res.removedInfo != null
1937                                    ? res.removedInfo.installerPackageName
1938                                    : null;
1939
1940            // If this is the first time we have child packages for a disabled privileged
1941            // app that had no children, we grant requested runtime permissions to the new
1942            // children if the parent on the system image had them already granted.
1943            if (res.pkg.parentPackage != null) {
1944                synchronized (mPackages) {
1945                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1946                }
1947            }
1948
1949            synchronized (mPackages) {
1950                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1951            }
1952
1953            final String packageName = res.pkg.applicationInfo.packageName;
1954
1955            // Determine the set of users who are adding this package for
1956            // the first time vs. those who are seeing an update.
1957            int[] firstUsers = EMPTY_INT_ARRAY;
1958            int[] updateUsers = EMPTY_INT_ARRAY;
1959            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1960            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1961            for (int newUser : res.newUsers) {
1962                if (ps.getInstantApp(newUser)) {
1963                    continue;
1964                }
1965                if (allNewUsers) {
1966                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1967                    continue;
1968                }
1969                boolean isNew = true;
1970                for (int origUser : res.origUsers) {
1971                    if (origUser == newUser) {
1972                        isNew = false;
1973                        break;
1974                    }
1975                }
1976                if (isNew) {
1977                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1978                } else {
1979                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1980                }
1981            }
1982
1983            // Send installed broadcasts if the package is not a static shared lib.
1984            if (res.pkg.staticSharedLibName == null) {
1985                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1986
1987                // Send added for users that see the package for the first time
1988                // sendPackageAddedForNewUsers also deals with system apps
1989                int appId = UserHandle.getAppId(res.uid);
1990                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1991                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1992                        virtualPreload /*startReceiver*/, appId, firstUsers);
1993
1994                // Send added for users that don't see the package for the first time
1995                Bundle extras = new Bundle(1);
1996                extras.putInt(Intent.EXTRA_UID, res.uid);
1997                if (update) {
1998                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1999                }
2000                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2001                        extras, 0 /*flags*/,
2002                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2003                if (installerPackageName != null) {
2004                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2005                            extras, 0 /*flags*/,
2006                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2007                }
2008
2009                // Send replaced for users that don't see the package for the first time
2010                if (update) {
2011                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2012                            packageName, extras, 0 /*flags*/,
2013                            null /*targetPackage*/, null /*finishedReceiver*/,
2014                            updateUsers);
2015                    if (installerPackageName != null) {
2016                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2017                                extras, 0 /*flags*/,
2018                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2019                    }
2020                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2021                            null /*package*/, null /*extras*/, 0 /*flags*/,
2022                            packageName /*targetPackage*/,
2023                            null /*finishedReceiver*/, updateUsers);
2024                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2025                    // First-install and we did a restore, so we're responsible for the
2026                    // first-launch broadcast.
2027                    if (DEBUG_BACKUP) {
2028                        Slog.i(TAG, "Post-restore of " + packageName
2029                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2030                    }
2031                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2032                }
2033
2034                // Send broadcast package appeared if forward locked/external for all users
2035                // treat asec-hosted packages like removable media on upgrade
2036                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2037                    if (DEBUG_INSTALL) {
2038                        Slog.i(TAG, "upgrading pkg " + res.pkg
2039                                + " is ASEC-hosted -> AVAILABLE");
2040                    }
2041                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2042                    ArrayList<String> pkgList = new ArrayList<>(1);
2043                    pkgList.add(packageName);
2044                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2045                }
2046            }
2047
2048            // Work that needs to happen on first install within each user
2049            if (firstUsers != null && firstUsers.length > 0) {
2050                synchronized (mPackages) {
2051                    for (int userId : firstUsers) {
2052                        // If this app is a browser and it's newly-installed for some
2053                        // users, clear any default-browser state in those users. The
2054                        // app's nature doesn't depend on the user, so we can just check
2055                        // its browser nature in any user and generalize.
2056                        if (packageIsBrowser(packageName, userId)) {
2057                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2058                        }
2059
2060                        // We may also need to apply pending (restored) runtime
2061                        // permission grants within these users.
2062                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2063                    }
2064                }
2065            }
2066
2067            // Log current value of "unknown sources" setting
2068            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2069                    getUnknownSourcesSettings());
2070
2071            // Remove the replaced package's older resources safely now
2072            // We delete after a gc for applications  on sdcard.
2073            if (res.removedInfo != null && res.removedInfo.args != null) {
2074                Runtime.getRuntime().gc();
2075                synchronized (mInstallLock) {
2076                    res.removedInfo.args.doPostDeleteLI(true);
2077                }
2078            } else {
2079                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2080                // and not block here.
2081                VMRuntime.getRuntime().requestConcurrentGC();
2082            }
2083
2084            // Notify DexManager that the package was installed for new users.
2085            // The updated users should already be indexed and the package code paths
2086            // should not change.
2087            // Don't notify the manager for ephemeral apps as they are not expected to
2088            // survive long enough to benefit of background optimizations.
2089            for (int userId : firstUsers) {
2090                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2091                // There's a race currently where some install events may interleave with an uninstall.
2092                // This can lead to package info being null (b/36642664).
2093                if (info != null) {
2094                    mDexManager.notifyPackageInstalled(info, userId);
2095                }
2096            }
2097        }
2098
2099        // If someone is watching installs - notify them
2100        if (installObserver != null) {
2101            try {
2102                Bundle extras = extrasForInstallResult(res);
2103                installObserver.onPackageInstalled(res.name, res.returnCode,
2104                        res.returnMsg, extras);
2105            } catch (RemoteException e) {
2106                Slog.i(TAG, "Observer no longer exists.");
2107            }
2108        }
2109    }
2110
2111    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2112            PackageParser.Package pkg) {
2113        if (pkg.parentPackage == null) {
2114            return;
2115        }
2116        if (pkg.requestedPermissions == null) {
2117            return;
2118        }
2119        final PackageSetting disabledSysParentPs = mSettings
2120                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2121        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2122                || !disabledSysParentPs.isPrivileged()
2123                || (disabledSysParentPs.childPackageNames != null
2124                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2125            return;
2126        }
2127        final int[] allUserIds = sUserManager.getUserIds();
2128        final int permCount = pkg.requestedPermissions.size();
2129        for (int i = 0; i < permCount; i++) {
2130            String permission = pkg.requestedPermissions.get(i);
2131            BasePermission bp = mSettings.mPermissions.get(permission);
2132            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2133                continue;
2134            }
2135            for (int userId : allUserIds) {
2136                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2137                        permission, userId)) {
2138                    grantRuntimePermission(pkg.packageName, permission, userId);
2139                }
2140            }
2141        }
2142    }
2143
2144    private StorageEventListener mStorageListener = new StorageEventListener() {
2145        @Override
2146        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2147            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2148                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2149                    final String volumeUuid = vol.getFsUuid();
2150
2151                    // Clean up any users or apps that were removed or recreated
2152                    // while this volume was missing
2153                    sUserManager.reconcileUsers(volumeUuid);
2154                    reconcileApps(volumeUuid);
2155
2156                    // Clean up any install sessions that expired or were
2157                    // cancelled while this volume was missing
2158                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2159
2160                    loadPrivatePackages(vol);
2161
2162                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2163                    unloadPrivatePackages(vol);
2164                }
2165            }
2166
2167            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2168                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2169                    updateExternalMediaStatus(true, false);
2170                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2171                    updateExternalMediaStatus(false, false);
2172                }
2173            }
2174        }
2175
2176        @Override
2177        public void onVolumeForgotten(String fsUuid) {
2178            if (TextUtils.isEmpty(fsUuid)) {
2179                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2180                return;
2181            }
2182
2183            // Remove any apps installed on the forgotten volume
2184            synchronized (mPackages) {
2185                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2186                for (PackageSetting ps : packages) {
2187                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2188                    deletePackageVersioned(new VersionedPackage(ps.name,
2189                            PackageManager.VERSION_CODE_HIGHEST),
2190                            new LegacyPackageDeleteObserver(null).getBinder(),
2191                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2192                    // Try very hard to release any references to this package
2193                    // so we don't risk the system server being killed due to
2194                    // open FDs
2195                    AttributeCache.instance().removePackage(ps.name);
2196                }
2197
2198                mSettings.onVolumeForgotten(fsUuid);
2199                mSettings.writeLPr();
2200            }
2201        }
2202    };
2203
2204    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2205            String[] grantedPermissions) {
2206        for (int userId : userIds) {
2207            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2208        }
2209    }
2210
2211    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2212            String[] grantedPermissions) {
2213        PackageSetting ps = (PackageSetting) pkg.mExtras;
2214        if (ps == null) {
2215            return;
2216        }
2217
2218        PermissionsState permissionsState = ps.getPermissionsState();
2219
2220        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2221                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2222
2223        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2224                >= Build.VERSION_CODES.M;
2225
2226        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2227
2228        for (String permission : pkg.requestedPermissions) {
2229            final BasePermission bp;
2230            synchronized (mPackages) {
2231                bp = mSettings.mPermissions.get(permission);
2232            }
2233            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2234                    && (!instantApp || bp.isInstant())
2235                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2236                    && (grantedPermissions == null
2237                           || ArrayUtils.contains(grantedPermissions, permission))) {
2238                final int flags = permissionsState.getPermissionFlags(permission, userId);
2239                if (supportsRuntimePermissions) {
2240                    // Installer cannot change immutable permissions.
2241                    if ((flags & immutableFlags) == 0) {
2242                        grantRuntimePermission(pkg.packageName, permission, userId);
2243                    }
2244                } else if (mPermissionReviewRequired) {
2245                    // In permission review mode we clear the review flag when we
2246                    // are asked to install the app with all permissions granted.
2247                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2248                        updatePermissionFlags(permission, pkg.packageName,
2249                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2250                    }
2251                }
2252            }
2253        }
2254    }
2255
2256    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2257        Bundle extras = null;
2258        switch (res.returnCode) {
2259            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2260                extras = new Bundle();
2261                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2262                        res.origPermission);
2263                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2264                        res.origPackage);
2265                break;
2266            }
2267            case PackageManager.INSTALL_SUCCEEDED: {
2268                extras = new Bundle();
2269                extras.putBoolean(Intent.EXTRA_REPLACING,
2270                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2271                break;
2272            }
2273        }
2274        return extras;
2275    }
2276
2277    void scheduleWriteSettingsLocked() {
2278        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2279            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2280        }
2281    }
2282
2283    void scheduleWritePackageListLocked(int userId) {
2284        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2285            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2286            msg.arg1 = userId;
2287            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2288        }
2289    }
2290
2291    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2292        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2293        scheduleWritePackageRestrictionsLocked(userId);
2294    }
2295
2296    void scheduleWritePackageRestrictionsLocked(int userId) {
2297        final int[] userIds = (userId == UserHandle.USER_ALL)
2298                ? sUserManager.getUserIds() : new int[]{userId};
2299        for (int nextUserId : userIds) {
2300            if (!sUserManager.exists(nextUserId)) return;
2301            mDirtyUsers.add(nextUserId);
2302            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2303                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2304            }
2305        }
2306    }
2307
2308    public static PackageManagerService main(Context context, Installer installer,
2309            boolean factoryTest, boolean onlyCore) {
2310        // Self-check for initial settings.
2311        PackageManagerServiceCompilerMapping.checkProperties();
2312
2313        PackageManagerService m = new PackageManagerService(context, installer,
2314                factoryTest, onlyCore);
2315        m.enableSystemUserPackages();
2316        ServiceManager.addService("package", m);
2317        final PackageManagerNative pmn = m.new PackageManagerNative();
2318        ServiceManager.addService("package_native", pmn);
2319        return m;
2320    }
2321
2322    private void enableSystemUserPackages() {
2323        if (!UserManager.isSplitSystemUser()) {
2324            return;
2325        }
2326        // For system user, enable apps based on the following conditions:
2327        // - app is whitelisted or belong to one of these groups:
2328        //   -- system app which has no launcher icons
2329        //   -- system app which has INTERACT_ACROSS_USERS permission
2330        //   -- system IME app
2331        // - app is not in the blacklist
2332        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2333        Set<String> enableApps = new ArraySet<>();
2334        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2335                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2336                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2337        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2338        enableApps.addAll(wlApps);
2339        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2340                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2341        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2342        enableApps.removeAll(blApps);
2343        Log.i(TAG, "Applications installed for system user: " + enableApps);
2344        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2345                UserHandle.SYSTEM);
2346        final int allAppsSize = allAps.size();
2347        synchronized (mPackages) {
2348            for (int i = 0; i < allAppsSize; i++) {
2349                String pName = allAps.get(i);
2350                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2351                // Should not happen, but we shouldn't be failing if it does
2352                if (pkgSetting == null) {
2353                    continue;
2354                }
2355                boolean install = enableApps.contains(pName);
2356                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2357                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2358                            + " for system user");
2359                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2360                }
2361            }
2362            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2363        }
2364    }
2365
2366    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2367        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2368                Context.DISPLAY_SERVICE);
2369        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2370    }
2371
2372    /**
2373     * Requests that files preopted on a secondary system partition be copied to the data partition
2374     * if possible.  Note that the actual copying of the files is accomplished by init for security
2375     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2376     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2377     */
2378    private static void requestCopyPreoptedFiles() {
2379        final int WAIT_TIME_MS = 100;
2380        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2381        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2382            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2383            // We will wait for up to 100 seconds.
2384            final long timeStart = SystemClock.uptimeMillis();
2385            final long timeEnd = timeStart + 100 * 1000;
2386            long timeNow = timeStart;
2387            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2388                try {
2389                    Thread.sleep(WAIT_TIME_MS);
2390                } catch (InterruptedException e) {
2391                    // Do nothing
2392                }
2393                timeNow = SystemClock.uptimeMillis();
2394                if (timeNow > timeEnd) {
2395                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2396                    Slog.wtf(TAG, "cppreopt did not finish!");
2397                    break;
2398                }
2399            }
2400
2401            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2402        }
2403    }
2404
2405    public PackageManagerService(Context context, Installer installer,
2406            boolean factoryTest, boolean onlyCore) {
2407        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2408        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2409        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2410                SystemClock.uptimeMillis());
2411
2412        if (mSdkVersion <= 0) {
2413            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2414        }
2415
2416        mContext = context;
2417
2418        mPermissionReviewRequired = context.getResources().getBoolean(
2419                R.bool.config_permissionReviewRequired);
2420
2421        mFactoryTest = factoryTest;
2422        mOnlyCore = onlyCore;
2423        mMetrics = new DisplayMetrics();
2424        mSettings = new Settings(mPackages);
2425        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2434                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2436                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437
2438        String separateProcesses = SystemProperties.get("debug.separate_processes");
2439        if (separateProcesses != null && separateProcesses.length() > 0) {
2440            if ("*".equals(separateProcesses)) {
2441                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2442                mSeparateProcesses = null;
2443                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2444            } else {
2445                mDefParseFlags = 0;
2446                mSeparateProcesses = separateProcesses.split(",");
2447                Slog.w(TAG, "Running with debug.separate_processes: "
2448                        + separateProcesses);
2449            }
2450        } else {
2451            mDefParseFlags = 0;
2452            mSeparateProcesses = null;
2453        }
2454
2455        mInstaller = installer;
2456        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2457                "*dexopt*");
2458        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2459        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2460
2461        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2462                FgThread.get().getLooper());
2463
2464        getDefaultDisplayMetrics(context, mMetrics);
2465
2466        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2467        SystemConfig systemConfig = SystemConfig.getInstance();
2468        mGlobalGids = systemConfig.getGlobalGids();
2469        mSystemPermissions = systemConfig.getSystemPermissions();
2470        mAvailableFeatures = systemConfig.getAvailableFeatures();
2471        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2472
2473        mProtectedPackages = new ProtectedPackages(mContext);
2474
2475        synchronized (mInstallLock) {
2476        // writer
2477        synchronized (mPackages) {
2478            mHandlerThread = new ServiceThread(TAG,
2479                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2480            mHandlerThread.start();
2481            mHandler = new PackageHandler(mHandlerThread.getLooper());
2482            mProcessLoggingHandler = new ProcessLoggingHandler();
2483            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2484
2485            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2486            mInstantAppRegistry = new InstantAppRegistry(this);
2487
2488            File dataDir = Environment.getDataDirectory();
2489            mAppInstallDir = new File(dataDir, "app");
2490            mAppLib32InstallDir = new File(dataDir, "app-lib");
2491            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2492            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2493            sUserManager = new UserManagerService(context, this,
2494                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2495
2496            // Propagate permission configuration in to package manager.
2497            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2498                    = systemConfig.getPermissions();
2499            for (int i=0; i<permConfig.size(); i++) {
2500                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2501                BasePermission bp = mSettings.mPermissions.get(perm.name);
2502                if (bp == null) {
2503                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2504                    mSettings.mPermissions.put(perm.name, bp);
2505                }
2506                if (perm.gids != null) {
2507                    bp.setGids(perm.gids, perm.perUser);
2508                }
2509            }
2510
2511            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2512            final int builtInLibCount = libConfig.size();
2513            for (int i = 0; i < builtInLibCount; i++) {
2514                String name = libConfig.keyAt(i);
2515                String path = libConfig.valueAt(i);
2516                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2517                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2518            }
2519
2520            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2521
2522            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2523            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2524            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2525
2526            // Clean up orphaned packages for which the code path doesn't exist
2527            // and they are an update to a system app - caused by bug/32321269
2528            final int packageSettingCount = mSettings.mPackages.size();
2529            for (int i = packageSettingCount - 1; i >= 0; i--) {
2530                PackageSetting ps = mSettings.mPackages.valueAt(i);
2531                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2532                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2533                    mSettings.mPackages.removeAt(i);
2534                    mSettings.enableSystemPackageLPw(ps.name);
2535                }
2536            }
2537
2538            if (mFirstBoot) {
2539                requestCopyPreoptedFiles();
2540            }
2541
2542            String customResolverActivity = Resources.getSystem().getString(
2543                    R.string.config_customResolverActivity);
2544            if (TextUtils.isEmpty(customResolverActivity)) {
2545                customResolverActivity = null;
2546            } else {
2547                mCustomResolverComponentName = ComponentName.unflattenFromString(
2548                        customResolverActivity);
2549            }
2550
2551            long startTime = SystemClock.uptimeMillis();
2552
2553            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2554                    startTime);
2555
2556            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2557            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2558
2559            if (bootClassPath == null) {
2560                Slog.w(TAG, "No BOOTCLASSPATH found!");
2561            }
2562
2563            if (systemServerClassPath == null) {
2564                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2565            }
2566
2567            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2568
2569            final VersionInfo ver = mSettings.getInternalVersion();
2570            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2571            if (mIsUpgrade) {
2572                logCriticalInfo(Log.INFO,
2573                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2574            }
2575
2576            // when upgrading from pre-M, promote system app permissions from install to runtime
2577            mPromoteSystemApps =
2578                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2579
2580            // When upgrading from pre-N, we need to handle package extraction like first boot,
2581            // as there is no profiling data available.
2582            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2583
2584            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2585
2586            // save off the names of pre-existing system packages prior to scanning; we don't
2587            // want to automatically grant runtime permissions for new system apps
2588            if (mPromoteSystemApps) {
2589                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2590                while (pkgSettingIter.hasNext()) {
2591                    PackageSetting ps = pkgSettingIter.next();
2592                    if (isSystemApp(ps)) {
2593                        mExistingSystemPackages.add(ps.name);
2594                    }
2595                }
2596            }
2597
2598            mCacheDir = preparePackageParserCache(mIsUpgrade);
2599
2600            // Set flag to monitor and not change apk file paths when
2601            // scanning install directories.
2602            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2603
2604            if (mIsUpgrade || mFirstBoot) {
2605                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2606            }
2607
2608            // Collect vendor overlay packages. (Do this before scanning any apps.)
2609            // For security and version matching reason, only consider
2610            // overlay packages if they reside in the right directory.
2611            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2612                    | PackageParser.PARSE_IS_SYSTEM
2613                    | PackageParser.PARSE_IS_SYSTEM_DIR
2614                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2615
2616            mParallelPackageParserCallback.findStaticOverlayPackages();
2617
2618            // Find base frameworks (resource packages without code).
2619            scanDirTracedLI(frameworkDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR
2622                    | PackageParser.PARSE_IS_PRIVILEGED,
2623                    scanFlags | SCAN_NO_DEX, 0);
2624
2625            // Collected privileged system packages.
2626            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2627            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR
2630                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2631
2632            // Collect ordinary system packages.
2633            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2634            scanDirTracedLI(systemAppDir, mDefParseFlags
2635                    | PackageParser.PARSE_IS_SYSTEM
2636                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2637
2638            // Collect all vendor packages.
2639            File vendorAppDir = new File("/vendor/app");
2640            try {
2641                vendorAppDir = vendorAppDir.getCanonicalFile();
2642            } catch (IOException e) {
2643                // failed to look up canonical path, continue with original one
2644            }
2645            scanDirTracedLI(vendorAppDir, mDefParseFlags
2646                    | PackageParser.PARSE_IS_SYSTEM
2647                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2648
2649            // Collect all OEM packages.
2650            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2651            scanDirTracedLI(oemAppDir, mDefParseFlags
2652                    | PackageParser.PARSE_IS_SYSTEM
2653                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2654
2655            // Prune any system packages that no longer exist.
2656            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2657            // Stub packages must either be replaced with full versions in the /data
2658            // partition or be disabled.
2659            final List<String> stubSystemApps = new ArrayList<>();
2660            if (!mOnlyCore) {
2661                // do this first before mucking with mPackages for the "expecting better" case
2662                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2663                while (pkgIterator.hasNext()) {
2664                    final PackageParser.Package pkg = pkgIterator.next();
2665                    if (pkg.isStub) {
2666                        stubSystemApps.add(pkg.packageName);
2667                    }
2668                }
2669
2670                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2671                while (psit.hasNext()) {
2672                    PackageSetting ps = psit.next();
2673
2674                    /*
2675                     * If this is not a system app, it can't be a
2676                     * disable system app.
2677                     */
2678                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2679                        continue;
2680                    }
2681
2682                    /*
2683                     * If the package is scanned, it's not erased.
2684                     */
2685                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2686                    if (scannedPkg != null) {
2687                        /*
2688                         * If the system app is both scanned and in the
2689                         * disabled packages list, then it must have been
2690                         * added via OTA. Remove it from the currently
2691                         * scanned package so the previously user-installed
2692                         * application can be scanned.
2693                         */
2694                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2695                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2696                                    + ps.name + "; removing system app.  Last known codePath="
2697                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2698                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2699                                    + scannedPkg.mVersionCode);
2700                            removePackageLI(scannedPkg, true);
2701                            mExpectingBetter.put(ps.name, ps.codePath);
2702                        }
2703
2704                        continue;
2705                    }
2706
2707                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2708                        psit.remove();
2709                        logCriticalInfo(Log.WARN, "System package " + ps.name
2710                                + " no longer exists; it's data will be wiped");
2711                        // Actual deletion of code and data will be handled by later
2712                        // reconciliation step
2713                    } else {
2714                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2715                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2716                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2717                        }
2718                    }
2719                }
2720            }
2721
2722            //look for any incomplete package installations
2723            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2724            for (int i = 0; i < deletePkgsList.size(); i++) {
2725                // Actual deletion of code and data will be handled by later
2726                // reconciliation step
2727                final String packageName = deletePkgsList.get(i).name;
2728                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2729                synchronized (mPackages) {
2730                    mSettings.removePackageLPw(packageName);
2731                }
2732            }
2733
2734            //delete tmp files
2735            deleteTempPackageFiles();
2736
2737            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2738
2739            // Remove any shared userIDs that have no associated packages
2740            mSettings.pruneSharedUsersLPw();
2741            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2742            final int systemPackagesCount = mPackages.size();
2743            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2744                    + " ms, packageCount: " + systemPackagesCount
2745                    + " , timePerPackage: "
2746                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2747                    + " , cached: " + cachedSystemApps);
2748            if (mIsUpgrade && systemPackagesCount > 0) {
2749                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2750                        ((int) systemScanTime) / systemPackagesCount);
2751            }
2752            if (!mOnlyCore) {
2753                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2754                        SystemClock.uptimeMillis());
2755                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2756
2757                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2758                        | PackageParser.PARSE_FORWARD_LOCK,
2759                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2760
2761                // Remove disable package settings for updated system apps that were
2762                // removed via an OTA. If the update is no longer present, remove the
2763                // app completely. Otherwise, revoke their system privileges.
2764                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2765                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2766                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2767
2768                    final String msg;
2769                    if (deletedPkg == null) {
2770                        // should have found an update, but, we didn't; remove everything
2771                        msg = "Updated system package " + deletedAppName
2772                                + " no longer exists; removing its data";
2773                        // Actual deletion of code and data will be handled by later
2774                        // reconciliation step
2775                    } else {
2776                        // found an update; revoke system privileges
2777                        msg = "Updated system package + " + deletedAppName
2778                                + " no longer exists; revoking system privileges";
2779
2780                        // Don't do anything if a stub is removed from the system image. If
2781                        // we were to remove the uncompressed version from the /data partition,
2782                        // this is where it'd be done.
2783
2784                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2785                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2786                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2787                    }
2788                    logCriticalInfo(Log.WARN, msg);
2789                }
2790
2791                /*
2792                 * Make sure all system apps that we expected to appear on
2793                 * the userdata partition actually showed up. If they never
2794                 * appeared, crawl back and revive the system version.
2795                 */
2796                for (int i = 0; i < mExpectingBetter.size(); i++) {
2797                    final String packageName = mExpectingBetter.keyAt(i);
2798                    if (!mPackages.containsKey(packageName)) {
2799                        final File scanFile = mExpectingBetter.valueAt(i);
2800
2801                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2802                                + " but never showed up; reverting to system");
2803
2804                        int reparseFlags = mDefParseFlags;
2805                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2806                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2807                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2808                                    | PackageParser.PARSE_IS_PRIVILEGED;
2809                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2810                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2811                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2812                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2813                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2814                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2815                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2816                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2817                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2818                        } else {
2819                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2820                            continue;
2821                        }
2822
2823                        mSettings.enableSystemPackageLPw(packageName);
2824
2825                        try {
2826                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2827                        } catch (PackageManagerException e) {
2828                            Slog.e(TAG, "Failed to parse original system package: "
2829                                    + e.getMessage());
2830                        }
2831                    }
2832                }
2833
2834                // Uncompress and install any stubbed system applications.
2835                // This must be done last to ensure all stubs are replaced or disabled.
2836                decompressSystemApplications(stubSystemApps, scanFlags);
2837
2838                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2839                                - cachedSystemApps;
2840
2841                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2842                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2843                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2844                        + " ms, packageCount: " + dataPackagesCount
2845                        + " , timePerPackage: "
2846                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2847                        + " , cached: " + cachedNonSystemApps);
2848                if (mIsUpgrade && dataPackagesCount > 0) {
2849                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2850                            ((int) dataScanTime) / dataPackagesCount);
2851                }
2852            }
2853            mExpectingBetter.clear();
2854
2855            // Resolve the storage manager.
2856            mStorageManagerPackage = getStorageManagerPackageName();
2857
2858            // Resolve protected action filters. Only the setup wizard is allowed to
2859            // have a high priority filter for these actions.
2860            mSetupWizardPackage = getSetupWizardPackageName();
2861            if (mProtectedFilters.size() > 0) {
2862                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2863                    Slog.i(TAG, "No setup wizard;"
2864                        + " All protected intents capped to priority 0");
2865                }
2866                for (ActivityIntentInfo filter : mProtectedFilters) {
2867                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2868                        if (DEBUG_FILTERS) {
2869                            Slog.i(TAG, "Found setup wizard;"
2870                                + " allow priority " + filter.getPriority() + ";"
2871                                + " package: " + filter.activity.info.packageName
2872                                + " activity: " + filter.activity.className
2873                                + " priority: " + filter.getPriority());
2874                        }
2875                        // skip setup wizard; allow it to keep the high priority filter
2876                        continue;
2877                    }
2878                    if (DEBUG_FILTERS) {
2879                        Slog.i(TAG, "Protected action; cap priority to 0;"
2880                                + " package: " + filter.activity.info.packageName
2881                                + " activity: " + filter.activity.className
2882                                + " origPrio: " + filter.getPriority());
2883                    }
2884                    filter.setPriority(0);
2885                }
2886            }
2887            mDeferProtectedFilters = false;
2888            mProtectedFilters.clear();
2889
2890            // Now that we know all of the shared libraries, update all clients to have
2891            // the correct library paths.
2892            updateAllSharedLibrariesLPw(null);
2893
2894            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2895                // NOTE: We ignore potential failures here during a system scan (like
2896                // the rest of the commands above) because there's precious little we
2897                // can do about it. A settings error is reported, though.
2898                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2899            }
2900
2901            // Now that we know all the packages we are keeping,
2902            // read and update their last usage times.
2903            mPackageUsage.read(mPackages);
2904            mCompilerStats.read();
2905
2906            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2907                    SystemClock.uptimeMillis());
2908            Slog.i(TAG, "Time to scan packages: "
2909                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2910                    + " seconds");
2911
2912            // If the platform SDK has changed since the last time we booted,
2913            // we need to re-grant app permission to catch any new ones that
2914            // appear.  This is really a hack, and means that apps can in some
2915            // cases get permissions that the user didn't initially explicitly
2916            // allow...  it would be nice to have some better way to handle
2917            // this situation.
2918            int updateFlags = UPDATE_PERMISSIONS_ALL;
2919            if (ver.sdkVersion != mSdkVersion) {
2920                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2921                        + mSdkVersion + "; regranting permissions for internal storage");
2922                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2923            }
2924            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2925            ver.sdkVersion = mSdkVersion;
2926
2927            // If this is the first boot or an update from pre-M, and it is a normal
2928            // boot, then we need to initialize the default preferred apps across
2929            // all defined users.
2930            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2931                for (UserInfo user : sUserManager.getUsers(true)) {
2932                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2933                    applyFactoryDefaultBrowserLPw(user.id);
2934                    primeDomainVerificationsLPw(user.id);
2935                }
2936            }
2937
2938            // Prepare storage for system user really early during boot,
2939            // since core system apps like SettingsProvider and SystemUI
2940            // can't wait for user to start
2941            final int storageFlags;
2942            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2943                storageFlags = StorageManager.FLAG_STORAGE_DE;
2944            } else {
2945                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2946            }
2947            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2948                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2949                    true /* onlyCoreApps */);
2950            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2951                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2952                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2953                traceLog.traceBegin("AppDataFixup");
2954                try {
2955                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2956                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2957                } catch (InstallerException e) {
2958                    Slog.w(TAG, "Trouble fixing GIDs", e);
2959                }
2960                traceLog.traceEnd();
2961
2962                traceLog.traceBegin("AppDataPrepare");
2963                if (deferPackages == null || deferPackages.isEmpty()) {
2964                    return;
2965                }
2966                int count = 0;
2967                for (String pkgName : deferPackages) {
2968                    PackageParser.Package pkg = null;
2969                    synchronized (mPackages) {
2970                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2971                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2972                            pkg = ps.pkg;
2973                        }
2974                    }
2975                    if (pkg != null) {
2976                        synchronized (mInstallLock) {
2977                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2978                                    true /* maybeMigrateAppData */);
2979                        }
2980                        count++;
2981                    }
2982                }
2983                traceLog.traceEnd();
2984                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2985            }, "prepareAppData");
2986
2987            // If this is first boot after an OTA, and a normal boot, then
2988            // we need to clear code cache directories.
2989            // Note that we do *not* clear the application profiles. These remain valid
2990            // across OTAs and are used to drive profile verification (post OTA) and
2991            // profile compilation (without waiting to collect a fresh set of profiles).
2992            if (mIsUpgrade && !onlyCore) {
2993                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2994                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2995                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2996                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2997                        // No apps are running this early, so no need to freeze
2998                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2999                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3000                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3001                    }
3002                }
3003                ver.fingerprint = Build.FINGERPRINT;
3004            }
3005
3006            checkDefaultBrowser();
3007
3008            // clear only after permissions and other defaults have been updated
3009            mExistingSystemPackages.clear();
3010            mPromoteSystemApps = false;
3011
3012            // All the changes are done during package scanning.
3013            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3014
3015            // can downgrade to reader
3016            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3017            mSettings.writeLPr();
3018            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3019            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3020                    SystemClock.uptimeMillis());
3021
3022            if (!mOnlyCore) {
3023                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3024                mRequiredInstallerPackage = getRequiredInstallerLPr();
3025                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3026                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3027                if (mIntentFilterVerifierComponent != null) {
3028                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3029                            mIntentFilterVerifierComponent);
3030                } else {
3031                    mIntentFilterVerifier = null;
3032                }
3033                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3034                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3035                        SharedLibraryInfo.VERSION_UNDEFINED);
3036                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3037                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3038                        SharedLibraryInfo.VERSION_UNDEFINED);
3039            } else {
3040                mRequiredVerifierPackage = null;
3041                mRequiredInstallerPackage = null;
3042                mRequiredUninstallerPackage = null;
3043                mIntentFilterVerifierComponent = null;
3044                mIntentFilterVerifier = null;
3045                mServicesSystemSharedLibraryPackageName = null;
3046                mSharedSystemSharedLibraryPackageName = null;
3047            }
3048
3049            mInstallerService = new PackageInstallerService(context, this);
3050            final Pair<ComponentName, String> instantAppResolverComponent =
3051                    getInstantAppResolverLPr();
3052            if (instantAppResolverComponent != null) {
3053                if (DEBUG_EPHEMERAL) {
3054                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3055                }
3056                mInstantAppResolverConnection = new EphemeralResolverConnection(
3057                        mContext, instantAppResolverComponent.first,
3058                        instantAppResolverComponent.second);
3059                mInstantAppResolverSettingsComponent =
3060                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3061            } else {
3062                mInstantAppResolverConnection = null;
3063                mInstantAppResolverSettingsComponent = null;
3064            }
3065            updateInstantAppInstallerLocked(null);
3066
3067            // Read and update the usage of dex files.
3068            // Do this at the end of PM init so that all the packages have their
3069            // data directory reconciled.
3070            // At this point we know the code paths of the packages, so we can validate
3071            // the disk file and build the internal cache.
3072            // The usage file is expected to be small so loading and verifying it
3073            // should take a fairly small time compare to the other activities (e.g. package
3074            // scanning).
3075            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3076            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3077            for (int userId : currentUserIds) {
3078                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3079            }
3080            mDexManager.load(userPackages);
3081            if (mIsUpgrade) {
3082                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3083                        (int) (SystemClock.uptimeMillis() - startTime));
3084            }
3085        } // synchronized (mPackages)
3086        } // synchronized (mInstallLock)
3087
3088        // Now after opening every single application zip, make sure they
3089        // are all flushed.  Not really needed, but keeps things nice and
3090        // tidy.
3091        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3092        Runtime.getRuntime().gc();
3093        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3094
3095        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3096        FallbackCategoryProvider.loadFallbacks();
3097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3098
3099        // The initial scanning above does many calls into installd while
3100        // holding the mPackages lock, but we're mostly interested in yelling
3101        // once we have a booted system.
3102        mInstaller.setWarnIfHeld(mPackages);
3103
3104        // Expose private service for system components to use.
3105        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3106        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3107    }
3108
3109    /**
3110     * Uncompress and install stub applications.
3111     * <p>In order to save space on the system partition, some applications are shipped in a
3112     * compressed form. In addition the compressed bits for the full application, the
3113     * system image contains a tiny stub comprised of only the Android manifest.
3114     * <p>During the first boot, attempt to uncompress and install the full application. If
3115     * the application can't be installed for any reason, disable the stub and prevent
3116     * uncompressing the full application during future boots.
3117     * <p>In order to forcefully attempt an installation of a full application, go to app
3118     * settings and enable the application.
3119     */
3120    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3121        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3122            final String pkgName = stubSystemApps.get(i);
3123            // skip if the system package is already disabled
3124            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3125                stubSystemApps.remove(i);
3126                continue;
3127            }
3128            // skip if the package isn't installed (?!); this should never happen
3129            final PackageParser.Package pkg = mPackages.get(pkgName);
3130            if (pkg == null) {
3131                stubSystemApps.remove(i);
3132                continue;
3133            }
3134            // skip if the package has been disabled by the user
3135            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3136            if (ps != null) {
3137                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3138                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3139                    stubSystemApps.remove(i);
3140                    continue;
3141                }
3142            }
3143
3144            if (DEBUG_COMPRESSION) {
3145                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3146            }
3147
3148            // uncompress the binary to its eventual destination on /data
3149            final File scanFile = decompressPackage(pkg);
3150            if (scanFile == null) {
3151                continue;
3152            }
3153
3154            // install the package to replace the stub on /system
3155            try {
3156                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3157                removePackageLI(pkg, true /*chatty*/);
3158                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3159                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3160                        UserHandle.USER_SYSTEM, "android");
3161                stubSystemApps.remove(i);
3162                continue;
3163            } catch (PackageManagerException e) {
3164                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3165            }
3166
3167            // any failed attempt to install the package will be cleaned up later
3168        }
3169
3170        // disable any stub still left; these failed to install the full application
3171        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3172            final String pkgName = stubSystemApps.get(i);
3173            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3174            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3175                    UserHandle.USER_SYSTEM, "android");
3176            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3177        }
3178    }
3179
3180    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3181        if (DEBUG_COMPRESSION) {
3182            Slog.i(TAG, "Decompress file"
3183                    + "; src: " + srcFile.getAbsolutePath()
3184                    + ", dst: " + dstFile.getAbsolutePath());
3185        }
3186        try (
3187                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3188                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3189        ) {
3190            Streams.copy(fileIn, fileOut);
3191            Os.chmod(dstFile.getAbsolutePath(), 0644);
3192            return PackageManager.INSTALL_SUCCEEDED;
3193        } catch (IOException e) {
3194            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3195                    + "; src: " + srcFile.getAbsolutePath()
3196                    + ", dst: " + dstFile.getAbsolutePath());
3197        }
3198        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3199    }
3200
3201    private File[] getCompressedFiles(String codePath) {
3202        final File stubCodePath = new File(codePath);
3203        final String stubName = stubCodePath.getName();
3204
3205        // The layout of a compressed package on a given partition is as follows :
3206        //
3207        // Compressed artifacts:
3208        //
3209        // /partition/ModuleName/foo.gz
3210        // /partation/ModuleName/bar.gz
3211        //
3212        // Stub artifact:
3213        //
3214        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3215        //
3216        // In other words, stub is on the same partition as the compressed artifacts
3217        // and in a directory that's suffixed with "-Stub".
3218        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3219        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3220            return null;
3221        }
3222
3223        final File stubParentDir = stubCodePath.getParentFile();
3224        if (stubParentDir == null) {
3225            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3226            return null;
3227        }
3228
3229        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3230        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3231            @Override
3232            public boolean accept(File dir, String name) {
3233                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3234            }
3235        });
3236
3237        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3238            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3239        }
3240
3241        return files;
3242    }
3243
3244    private boolean compressedFileExists(String codePath) {
3245        final File[] compressedFiles = getCompressedFiles(codePath);
3246        return compressedFiles != null && compressedFiles.length > 0;
3247    }
3248
3249    /**
3250     * Decompresses the given package on the system image onto
3251     * the /data partition.
3252     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3253     */
3254    private File decompressPackage(PackageParser.Package pkg) {
3255        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3256        if (compressedFiles == null || compressedFiles.length == 0) {
3257            if (DEBUG_COMPRESSION) {
3258                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3259            }
3260            return null;
3261        }
3262        final File dstCodePath =
3263                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3264        int ret = PackageManager.INSTALL_SUCCEEDED;
3265        try {
3266            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3267            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3268            for (File srcFile : compressedFiles) {
3269                final String srcFileName = srcFile.getName();
3270                final String dstFileName = srcFileName.substring(
3271                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3272                final File dstFile = new File(dstCodePath, dstFileName);
3273                ret = decompressFile(srcFile, dstFile);
3274                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3275                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3276                            + "; pkg: " + pkg.packageName
3277                            + ", file: " + dstFileName);
3278                    break;
3279                }
3280            }
3281        } catch (ErrnoException e) {
3282            logCriticalInfo(Log.ERROR, "Failed to decompress"
3283                    + "; pkg: " + pkg.packageName
3284                    + ", err: " + e.errno);
3285        }
3286        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3287            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3288            NativeLibraryHelper.Handle handle = null;
3289            try {
3290                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3291                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3292                        null /*abiOverride*/);
3293            } catch (IOException e) {
3294                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3295                        + "; pkg: " + pkg.packageName);
3296                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3297            } finally {
3298                IoUtils.closeQuietly(handle);
3299            }
3300        }
3301        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3302            if (dstCodePath == null || !dstCodePath.exists()) {
3303                return null;
3304            }
3305            removeCodePathLI(dstCodePath);
3306            return null;
3307        }
3308        return dstCodePath;
3309    }
3310
3311    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3312        // we're only interested in updating the installer appliction when 1) it's not
3313        // already set or 2) the modified package is the installer
3314        if (mInstantAppInstallerActivity != null
3315                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3316                        .equals(modifiedPackage)) {
3317            return;
3318        }
3319        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3320    }
3321
3322    private static File preparePackageParserCache(boolean isUpgrade) {
3323        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3324            return null;
3325        }
3326
3327        // Disable package parsing on eng builds to allow for faster incremental development.
3328        if (Build.IS_ENG) {
3329            return null;
3330        }
3331
3332        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3333            Slog.i(TAG, "Disabling package parser cache due to system property.");
3334            return null;
3335        }
3336
3337        // The base directory for the package parser cache lives under /data/system/.
3338        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3339                "package_cache");
3340        if (cacheBaseDir == null) {
3341            return null;
3342        }
3343
3344        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3345        // This also serves to "GC" unused entries when the package cache version changes (which
3346        // can only happen during upgrades).
3347        if (isUpgrade) {
3348            FileUtils.deleteContents(cacheBaseDir);
3349        }
3350
3351
3352        // Return the versioned package cache directory. This is something like
3353        // "/data/system/package_cache/1"
3354        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3355
3356        // The following is a workaround to aid development on non-numbered userdebug
3357        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3358        // the system partition is newer.
3359        //
3360        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3361        // that starts with "eng." to signify that this is an engineering build and not
3362        // destined for release.
3363        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3364            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3365
3366            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3367            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3368            // in general and should not be used for production changes. In this specific case,
3369            // we know that they will work.
3370            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3371            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3372                FileUtils.deleteContents(cacheBaseDir);
3373                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3374            }
3375        }
3376
3377        return cacheDir;
3378    }
3379
3380    @Override
3381    public boolean isFirstBoot() {
3382        // allow instant applications
3383        return mFirstBoot;
3384    }
3385
3386    @Override
3387    public boolean isOnlyCoreApps() {
3388        // allow instant applications
3389        return mOnlyCore;
3390    }
3391
3392    @Override
3393    public boolean isUpgrade() {
3394        // allow instant applications
3395        return mIsUpgrade;
3396    }
3397
3398    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3399        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3400
3401        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3402                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3403                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3404        if (matches.size() == 1) {
3405            return matches.get(0).getComponentInfo().packageName;
3406        } else if (matches.size() == 0) {
3407            Log.e(TAG, "There should probably be a verifier, but, none were found");
3408            return null;
3409        }
3410        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3411    }
3412
3413    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3414        synchronized (mPackages) {
3415            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3416            if (libraryEntry == null) {
3417                throw new IllegalStateException("Missing required shared library:" + name);
3418            }
3419            return libraryEntry.apk;
3420        }
3421    }
3422
3423    private @NonNull String getRequiredInstallerLPr() {
3424        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3425        intent.addCategory(Intent.CATEGORY_DEFAULT);
3426        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3427
3428        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3429                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3430                UserHandle.USER_SYSTEM);
3431        if (matches.size() == 1) {
3432            ResolveInfo resolveInfo = matches.get(0);
3433            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3434                throw new RuntimeException("The installer must be a privileged app");
3435            }
3436            return matches.get(0).getComponentInfo().packageName;
3437        } else {
3438            throw new RuntimeException("There must be exactly one installer; found " + matches);
3439        }
3440    }
3441
3442    private @NonNull String getRequiredUninstallerLPr() {
3443        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3444        intent.addCategory(Intent.CATEGORY_DEFAULT);
3445        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3446
3447        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3448                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3449                UserHandle.USER_SYSTEM);
3450        if (resolveInfo == null ||
3451                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3452            throw new RuntimeException("There must be exactly one uninstaller; found "
3453                    + resolveInfo);
3454        }
3455        return resolveInfo.getComponentInfo().packageName;
3456    }
3457
3458    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3459        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3460
3461        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3462                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3463                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3464        ResolveInfo best = null;
3465        final int N = matches.size();
3466        for (int i = 0; i < N; i++) {
3467            final ResolveInfo cur = matches.get(i);
3468            final String packageName = cur.getComponentInfo().packageName;
3469            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3470                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3471                continue;
3472            }
3473
3474            if (best == null || cur.priority > best.priority) {
3475                best = cur;
3476            }
3477        }
3478
3479        if (best != null) {
3480            return best.getComponentInfo().getComponentName();
3481        }
3482        Slog.w(TAG, "Intent filter verifier not found");
3483        return null;
3484    }
3485
3486    @Override
3487    public @Nullable ComponentName getInstantAppResolverComponent() {
3488        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3489            return null;
3490        }
3491        synchronized (mPackages) {
3492            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3493            if (instantAppResolver == null) {
3494                return null;
3495            }
3496            return instantAppResolver.first;
3497        }
3498    }
3499
3500    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3501        final String[] packageArray =
3502                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3503        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3504            if (DEBUG_EPHEMERAL) {
3505                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3506            }
3507            return null;
3508        }
3509
3510        final int callingUid = Binder.getCallingUid();
3511        final int resolveFlags =
3512                MATCH_DIRECT_BOOT_AWARE
3513                | MATCH_DIRECT_BOOT_UNAWARE
3514                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3515        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3516        final Intent resolverIntent = new Intent(actionName);
3517        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3518                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3519        // temporarily look for the old action
3520        if (resolvers.size() == 0) {
3521            if (DEBUG_EPHEMERAL) {
3522                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3523            }
3524            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3525            resolverIntent.setAction(actionName);
3526            resolvers = queryIntentServicesInternal(resolverIntent, null,
3527                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3528        }
3529        final int N = resolvers.size();
3530        if (N == 0) {
3531            if (DEBUG_EPHEMERAL) {
3532                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3533            }
3534            return null;
3535        }
3536
3537        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3538        for (int i = 0; i < N; i++) {
3539            final ResolveInfo info = resolvers.get(i);
3540
3541            if (info.serviceInfo == null) {
3542                continue;
3543            }
3544
3545            final String packageName = info.serviceInfo.packageName;
3546            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3547                if (DEBUG_EPHEMERAL) {
3548                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3549                            + " pkg: " + packageName + ", info:" + info);
3550                }
3551                continue;
3552            }
3553
3554            if (DEBUG_EPHEMERAL) {
3555                Slog.v(TAG, "Ephemeral resolver found;"
3556                        + " pkg: " + packageName + ", info:" + info);
3557            }
3558            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3559        }
3560        if (DEBUG_EPHEMERAL) {
3561            Slog.v(TAG, "Ephemeral resolver NOT found");
3562        }
3563        return null;
3564    }
3565
3566    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3567        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3568        intent.addCategory(Intent.CATEGORY_DEFAULT);
3569        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3570
3571        final int resolveFlags =
3572                MATCH_DIRECT_BOOT_AWARE
3573                | MATCH_DIRECT_BOOT_UNAWARE
3574                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3575        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3576                resolveFlags, UserHandle.USER_SYSTEM);
3577        // temporarily look for the old action
3578        if (matches.isEmpty()) {
3579            if (DEBUG_EPHEMERAL) {
3580                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3581            }
3582            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3583            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3584                    resolveFlags, UserHandle.USER_SYSTEM);
3585        }
3586        Iterator<ResolveInfo> iter = matches.iterator();
3587        while (iter.hasNext()) {
3588            final ResolveInfo rInfo = iter.next();
3589            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3590            if (ps != null) {
3591                final PermissionsState permissionsState = ps.getPermissionsState();
3592                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3593                    continue;
3594                }
3595            }
3596            iter.remove();
3597        }
3598        if (matches.size() == 0) {
3599            return null;
3600        } else if (matches.size() == 1) {
3601            return (ActivityInfo) matches.get(0).getComponentInfo();
3602        } else {
3603            throw new RuntimeException(
3604                    "There must be at most one ephemeral installer; found " + matches);
3605        }
3606    }
3607
3608    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3609            @NonNull ComponentName resolver) {
3610        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3611                .addCategory(Intent.CATEGORY_DEFAULT)
3612                .setPackage(resolver.getPackageName());
3613        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3614        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3615                UserHandle.USER_SYSTEM);
3616        // temporarily look for the old action
3617        if (matches.isEmpty()) {
3618            if (DEBUG_EPHEMERAL) {
3619                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3620            }
3621            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3622            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3623                    UserHandle.USER_SYSTEM);
3624        }
3625        if (matches.isEmpty()) {
3626            return null;
3627        }
3628        return matches.get(0).getComponentInfo().getComponentName();
3629    }
3630
3631    private void primeDomainVerificationsLPw(int userId) {
3632        if (DEBUG_DOMAIN_VERIFICATION) {
3633            Slog.d(TAG, "Priming domain verifications in user " + userId);
3634        }
3635
3636        SystemConfig systemConfig = SystemConfig.getInstance();
3637        ArraySet<String> packages = systemConfig.getLinkedApps();
3638
3639        for (String packageName : packages) {
3640            PackageParser.Package pkg = mPackages.get(packageName);
3641            if (pkg != null) {
3642                if (!pkg.isSystemApp()) {
3643                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3644                    continue;
3645                }
3646
3647                ArraySet<String> domains = null;
3648                for (PackageParser.Activity a : pkg.activities) {
3649                    for (ActivityIntentInfo filter : a.intents) {
3650                        if (hasValidDomains(filter)) {
3651                            if (domains == null) {
3652                                domains = new ArraySet<String>();
3653                            }
3654                            domains.addAll(filter.getHostsList());
3655                        }
3656                    }
3657                }
3658
3659                if (domains != null && domains.size() > 0) {
3660                    if (DEBUG_DOMAIN_VERIFICATION) {
3661                        Slog.v(TAG, "      + " + packageName);
3662                    }
3663                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3664                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3665                    // and then 'always' in the per-user state actually used for intent resolution.
3666                    final IntentFilterVerificationInfo ivi;
3667                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3668                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3669                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3670                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3671                } else {
3672                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3673                            + "' does not handle web links");
3674                }
3675            } else {
3676                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3677            }
3678        }
3679
3680        scheduleWritePackageRestrictionsLocked(userId);
3681        scheduleWriteSettingsLocked();
3682    }
3683
3684    private void applyFactoryDefaultBrowserLPw(int userId) {
3685        // The default browser app's package name is stored in a string resource,
3686        // with a product-specific overlay used for vendor customization.
3687        String browserPkg = mContext.getResources().getString(
3688                com.android.internal.R.string.default_browser);
3689        if (!TextUtils.isEmpty(browserPkg)) {
3690            // non-empty string => required to be a known package
3691            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3692            if (ps == null) {
3693                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3694                browserPkg = null;
3695            } else {
3696                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3697            }
3698        }
3699
3700        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3701        // default.  If there's more than one, just leave everything alone.
3702        if (browserPkg == null) {
3703            calculateDefaultBrowserLPw(userId);
3704        }
3705    }
3706
3707    private void calculateDefaultBrowserLPw(int userId) {
3708        List<String> allBrowsers = resolveAllBrowserApps(userId);
3709        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3710        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3711    }
3712
3713    private List<String> resolveAllBrowserApps(int userId) {
3714        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3715        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3716                PackageManager.MATCH_ALL, userId);
3717
3718        final int count = list.size();
3719        List<String> result = new ArrayList<String>(count);
3720        for (int i=0; i<count; i++) {
3721            ResolveInfo info = list.get(i);
3722            if (info.activityInfo == null
3723                    || !info.handleAllWebDataURI
3724                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3725                    || result.contains(info.activityInfo.packageName)) {
3726                continue;
3727            }
3728            result.add(info.activityInfo.packageName);
3729        }
3730
3731        return result;
3732    }
3733
3734    private boolean packageIsBrowser(String packageName, int userId) {
3735        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3736                PackageManager.MATCH_ALL, userId);
3737        final int N = list.size();
3738        for (int i = 0; i < N; i++) {
3739            ResolveInfo info = list.get(i);
3740            if (packageName.equals(info.activityInfo.packageName)) {
3741                return true;
3742            }
3743        }
3744        return false;
3745    }
3746
3747    private void checkDefaultBrowser() {
3748        final int myUserId = UserHandle.myUserId();
3749        final String packageName = getDefaultBrowserPackageName(myUserId);
3750        if (packageName != null) {
3751            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3752            if (info == null) {
3753                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3754                synchronized (mPackages) {
3755                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3756                }
3757            }
3758        }
3759    }
3760
3761    @Override
3762    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3763            throws RemoteException {
3764        try {
3765            return super.onTransact(code, data, reply, flags);
3766        } catch (RuntimeException e) {
3767            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3768                Slog.wtf(TAG, "Package Manager Crash", e);
3769            }
3770            throw e;
3771        }
3772    }
3773
3774    static int[] appendInts(int[] cur, int[] add) {
3775        if (add == null) return cur;
3776        if (cur == null) return add;
3777        final int N = add.length;
3778        for (int i=0; i<N; i++) {
3779            cur = appendInt(cur, add[i]);
3780        }
3781        return cur;
3782    }
3783
3784    /**
3785     * Returns whether or not a full application can see an instant application.
3786     * <p>
3787     * Currently, there are three cases in which this can occur:
3788     * <ol>
3789     * <li>The calling application is a "special" process. The special
3790     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3791     *     and {@code 0}</li>
3792     * <li>The calling application has the permission
3793     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3794     * <li>The calling application is the default launcher on the
3795     *     system partition.</li>
3796     * </ol>
3797     */
3798    private boolean canViewInstantApps(int callingUid, int userId) {
3799        if (callingUid == Process.SYSTEM_UID
3800                || callingUid == Process.SHELL_UID
3801                || callingUid == Process.ROOT_UID) {
3802            return true;
3803        }
3804        if (mContext.checkCallingOrSelfPermission(
3805                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3806            return true;
3807        }
3808        if (mContext.checkCallingOrSelfPermission(
3809                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3810            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3811            if (homeComponent != null
3812                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3813                return true;
3814            }
3815        }
3816        return false;
3817    }
3818
3819    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3820        if (!sUserManager.exists(userId)) return null;
3821        if (ps == null) {
3822            return null;
3823        }
3824        PackageParser.Package p = ps.pkg;
3825        if (p == null) {
3826            return null;
3827        }
3828        final int callingUid = Binder.getCallingUid();
3829        // Filter out ephemeral app metadata:
3830        //   * The system/shell/root can see metadata for any app
3831        //   * An installed app can see metadata for 1) other installed apps
3832        //     and 2) ephemeral apps that have explicitly interacted with it
3833        //   * Ephemeral apps can only see their own data and exposed installed apps
3834        //   * Holding a signature permission allows seeing instant apps
3835        if (filterAppAccessLPr(ps, callingUid, userId)) {
3836            return null;
3837        }
3838
3839        final PermissionsState permissionsState = ps.getPermissionsState();
3840
3841        // Compute GIDs only if requested
3842        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3843                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3844        // Compute granted permissions only if package has requested permissions
3845        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3846                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3847        final PackageUserState state = ps.readUserState(userId);
3848
3849        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3850                && ps.isSystem()) {
3851            flags |= MATCH_ANY_USER;
3852        }
3853
3854        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3855                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3856
3857        if (packageInfo == null) {
3858            return null;
3859        }
3860
3861        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3862                resolveExternalPackageNameLPr(p);
3863
3864        return packageInfo;
3865    }
3866
3867    @Override
3868    public void checkPackageStartable(String packageName, int userId) {
3869        final int callingUid = Binder.getCallingUid();
3870        if (getInstantAppPackageName(callingUid) != null) {
3871            throw new SecurityException("Instant applications don't have access to this method");
3872        }
3873        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3874        synchronized (mPackages) {
3875            final PackageSetting ps = mSettings.mPackages.get(packageName);
3876            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3877                throw new SecurityException("Package " + packageName + " was not found!");
3878            }
3879
3880            if (!ps.getInstalled(userId)) {
3881                throw new SecurityException(
3882                        "Package " + packageName + " was not installed for user " + userId + "!");
3883            }
3884
3885            if (mSafeMode && !ps.isSystem()) {
3886                throw new SecurityException("Package " + packageName + " not a system app!");
3887            }
3888
3889            if (mFrozenPackages.contains(packageName)) {
3890                throw new SecurityException("Package " + packageName + " is currently frozen!");
3891            }
3892
3893            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3894                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3895            }
3896        }
3897    }
3898
3899    @Override
3900    public boolean isPackageAvailable(String packageName, int userId) {
3901        if (!sUserManager.exists(userId)) return false;
3902        final int callingUid = Binder.getCallingUid();
3903        enforceCrossUserPermission(callingUid, userId,
3904                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3905        synchronized (mPackages) {
3906            PackageParser.Package p = mPackages.get(packageName);
3907            if (p != null) {
3908                final PackageSetting ps = (PackageSetting) p.mExtras;
3909                if (filterAppAccessLPr(ps, callingUid, userId)) {
3910                    return false;
3911                }
3912                if (ps != null) {
3913                    final PackageUserState state = ps.readUserState(userId);
3914                    if (state != null) {
3915                        return PackageParser.isAvailable(state);
3916                    }
3917                }
3918            }
3919        }
3920        return false;
3921    }
3922
3923    @Override
3924    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3925        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3926                flags, Binder.getCallingUid(), userId);
3927    }
3928
3929    @Override
3930    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3931            int flags, int userId) {
3932        return getPackageInfoInternal(versionedPackage.getPackageName(),
3933                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3934    }
3935
3936    /**
3937     * Important: The provided filterCallingUid is used exclusively to filter out packages
3938     * that can be seen based on user state. It's typically the original caller uid prior
3939     * to clearing. Because it can only be provided by trusted code, it's value can be
3940     * trusted and will be used as-is; unlike userId which will be validated by this method.
3941     */
3942    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3943            int flags, int filterCallingUid, int userId) {
3944        if (!sUserManager.exists(userId)) return null;
3945        flags = updateFlagsForPackage(flags, userId, packageName);
3946        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3947                false /* requireFullPermission */, false /* checkShell */, "get package info");
3948
3949        // reader
3950        synchronized (mPackages) {
3951            // Normalize package name to handle renamed packages and static libs
3952            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3953
3954            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3955            if (matchFactoryOnly) {
3956                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3957                if (ps != null) {
3958                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3959                        return null;
3960                    }
3961                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3962                        return null;
3963                    }
3964                    return generatePackageInfo(ps, flags, userId);
3965                }
3966            }
3967
3968            PackageParser.Package p = mPackages.get(packageName);
3969            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3970                return null;
3971            }
3972            if (DEBUG_PACKAGE_INFO)
3973                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3974            if (p != null) {
3975                final PackageSetting ps = (PackageSetting) p.mExtras;
3976                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3977                    return null;
3978                }
3979                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3980                    return null;
3981                }
3982                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3983            }
3984            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3985                final PackageSetting ps = mSettings.mPackages.get(packageName);
3986                if (ps == null) return null;
3987                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3988                    return null;
3989                }
3990                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3991                    return null;
3992                }
3993                return generatePackageInfo(ps, flags, userId);
3994            }
3995        }
3996        return null;
3997    }
3998
3999    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4000        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4001            return true;
4002        }
4003        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4004            return true;
4005        }
4006        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4007            return true;
4008        }
4009        return false;
4010    }
4011
4012    private boolean isComponentVisibleToInstantApp(
4013            @Nullable ComponentName component, @ComponentType int type) {
4014        if (type == TYPE_ACTIVITY) {
4015            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4016            return activity != null
4017                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4018                    : false;
4019        } else if (type == TYPE_RECEIVER) {
4020            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4021            return activity != null
4022                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4023                    : false;
4024        } else if (type == TYPE_SERVICE) {
4025            final PackageParser.Service service = mServices.mServices.get(component);
4026            return service != null
4027                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4028                    : false;
4029        } else if (type == TYPE_PROVIDER) {
4030            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4031            return provider != null
4032                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4033                    : false;
4034        } else if (type == TYPE_UNKNOWN) {
4035            return isComponentVisibleToInstantApp(component);
4036        }
4037        return false;
4038    }
4039
4040    /**
4041     * Returns whether or not access to the application should be filtered.
4042     * <p>
4043     * Access may be limited based upon whether the calling or target applications
4044     * are instant applications.
4045     *
4046     * @see #canAccessInstantApps(int)
4047     */
4048    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4049            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4050        // if we're in an isolated process, get the real calling UID
4051        if (Process.isIsolated(callingUid)) {
4052            callingUid = mIsolatedOwners.get(callingUid);
4053        }
4054        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4055        final boolean callerIsInstantApp = instantAppPkgName != null;
4056        if (ps == null) {
4057            if (callerIsInstantApp) {
4058                // pretend the application exists, but, needs to be filtered
4059                return true;
4060            }
4061            return false;
4062        }
4063        // if the target and caller are the same application, don't filter
4064        if (isCallerSameApp(ps.name, callingUid)) {
4065            return false;
4066        }
4067        if (callerIsInstantApp) {
4068            // request for a specific component; if it hasn't been explicitly exposed, filter
4069            if (component != null) {
4070                return !isComponentVisibleToInstantApp(component, componentType);
4071            }
4072            // request for application; if no components have been explicitly exposed, filter
4073            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4074        }
4075        if (ps.getInstantApp(userId)) {
4076            // caller can see all components of all instant applications, don't filter
4077            if (canViewInstantApps(callingUid, userId)) {
4078                return false;
4079            }
4080            // request for a specific instant application component, filter
4081            if (component != null) {
4082                return true;
4083            }
4084            // request for an instant application; if the caller hasn't been granted access, filter
4085            return !mInstantAppRegistry.isInstantAccessGranted(
4086                    userId, UserHandle.getAppId(callingUid), ps.appId);
4087        }
4088        return false;
4089    }
4090
4091    /**
4092     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4093     */
4094    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4095        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4096    }
4097
4098    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4099            int flags) {
4100        // Callers can access only the libs they depend on, otherwise they need to explicitly
4101        // ask for the shared libraries given the caller is allowed to access all static libs.
4102        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4103            // System/shell/root get to see all static libs
4104            final int appId = UserHandle.getAppId(uid);
4105            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4106                    || appId == Process.ROOT_UID) {
4107                return false;
4108            }
4109        }
4110
4111        // No package means no static lib as it is always on internal storage
4112        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4113            return false;
4114        }
4115
4116        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4117                ps.pkg.staticSharedLibVersion);
4118        if (libEntry == null) {
4119            return false;
4120        }
4121
4122        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4123        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4124        if (uidPackageNames == null) {
4125            return true;
4126        }
4127
4128        for (String uidPackageName : uidPackageNames) {
4129            if (ps.name.equals(uidPackageName)) {
4130                return false;
4131            }
4132            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4133            if (uidPs != null) {
4134                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4135                        libEntry.info.getName());
4136                if (index < 0) {
4137                    continue;
4138                }
4139                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4140                    return false;
4141                }
4142            }
4143        }
4144        return true;
4145    }
4146
4147    @Override
4148    public String[] currentToCanonicalPackageNames(String[] names) {
4149        final int callingUid = Binder.getCallingUid();
4150        if (getInstantAppPackageName(callingUid) != null) {
4151            return names;
4152        }
4153        final String[] out = new String[names.length];
4154        // reader
4155        synchronized (mPackages) {
4156            final int callingUserId = UserHandle.getUserId(callingUid);
4157            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4158            for (int i=names.length-1; i>=0; i--) {
4159                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4160                boolean translateName = false;
4161                if (ps != null && ps.realName != null) {
4162                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4163                    translateName = !targetIsInstantApp
4164                            || canViewInstantApps
4165                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4166                                    UserHandle.getAppId(callingUid), ps.appId);
4167                }
4168                out[i] = translateName ? ps.realName : names[i];
4169            }
4170        }
4171        return out;
4172    }
4173
4174    @Override
4175    public String[] canonicalToCurrentPackageNames(String[] names) {
4176        final int callingUid = Binder.getCallingUid();
4177        if (getInstantAppPackageName(callingUid) != null) {
4178            return names;
4179        }
4180        final String[] out = new String[names.length];
4181        // reader
4182        synchronized (mPackages) {
4183            final int callingUserId = UserHandle.getUserId(callingUid);
4184            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4185            for (int i=names.length-1; i>=0; i--) {
4186                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4187                boolean translateName = false;
4188                if (cur != null) {
4189                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4190                    final boolean targetIsInstantApp =
4191                            ps != null && ps.getInstantApp(callingUserId);
4192                    translateName = !targetIsInstantApp
4193                            || canViewInstantApps
4194                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4195                                    UserHandle.getAppId(callingUid), ps.appId);
4196                }
4197                out[i] = translateName ? cur : names[i];
4198            }
4199        }
4200        return out;
4201    }
4202
4203    @Override
4204    public int getPackageUid(String packageName, int flags, int userId) {
4205        if (!sUserManager.exists(userId)) return -1;
4206        final int callingUid = Binder.getCallingUid();
4207        flags = updateFlagsForPackage(flags, userId, packageName);
4208        enforceCrossUserPermission(callingUid, userId,
4209                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4210
4211        // reader
4212        synchronized (mPackages) {
4213            final PackageParser.Package p = mPackages.get(packageName);
4214            if (p != null && p.isMatch(flags)) {
4215                PackageSetting ps = (PackageSetting) p.mExtras;
4216                if (filterAppAccessLPr(ps, callingUid, userId)) {
4217                    return -1;
4218                }
4219                return UserHandle.getUid(userId, p.applicationInfo.uid);
4220            }
4221            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4222                final PackageSetting ps = mSettings.mPackages.get(packageName);
4223                if (ps != null && ps.isMatch(flags)
4224                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4225                    return UserHandle.getUid(userId, ps.appId);
4226                }
4227            }
4228        }
4229
4230        return -1;
4231    }
4232
4233    @Override
4234    public int[] getPackageGids(String packageName, int flags, int userId) {
4235        if (!sUserManager.exists(userId)) return null;
4236        final int callingUid = Binder.getCallingUid();
4237        flags = updateFlagsForPackage(flags, userId, packageName);
4238        enforceCrossUserPermission(callingUid, userId,
4239                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4240
4241        // reader
4242        synchronized (mPackages) {
4243            final PackageParser.Package p = mPackages.get(packageName);
4244            if (p != null && p.isMatch(flags)) {
4245                PackageSetting ps = (PackageSetting) p.mExtras;
4246                if (filterAppAccessLPr(ps, callingUid, userId)) {
4247                    return null;
4248                }
4249                // TODO: Shouldn't this be checking for package installed state for userId and
4250                // return null?
4251                return ps.getPermissionsState().computeGids(userId);
4252            }
4253            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4254                final PackageSetting ps = mSettings.mPackages.get(packageName);
4255                if (ps != null && ps.isMatch(flags)
4256                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4257                    return ps.getPermissionsState().computeGids(userId);
4258                }
4259            }
4260        }
4261
4262        return null;
4263    }
4264
4265    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4266        if (bp.perm != null) {
4267            return PackageParser.generatePermissionInfo(bp.perm, flags);
4268        }
4269        PermissionInfo pi = new PermissionInfo();
4270        pi.name = bp.name;
4271        pi.packageName = bp.sourcePackage;
4272        pi.nonLocalizedLabel = bp.name;
4273        pi.protectionLevel = bp.protectionLevel;
4274        return pi;
4275    }
4276
4277    @Override
4278    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4279        final int callingUid = Binder.getCallingUid();
4280        if (getInstantAppPackageName(callingUid) != null) {
4281            return null;
4282        }
4283        // reader
4284        synchronized (mPackages) {
4285            final BasePermission p = mSettings.mPermissions.get(name);
4286            if (p == null) {
4287                return null;
4288            }
4289            // If the caller is an app that targets pre 26 SDK drop protection flags.
4290            PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4291            if (permissionInfo != null) {
4292                final int protectionLevel = adjustPermissionProtectionFlagsLPr(
4293                        permissionInfo.protectionLevel, packageName, callingUid);
4294                if (permissionInfo.protectionLevel != protectionLevel) {
4295                    // If we return different protection level, don't use the cached info
4296                    if (p.perm != null && p.perm.info == permissionInfo) {
4297                        permissionInfo = new PermissionInfo(permissionInfo);
4298                    }
4299                    permissionInfo.protectionLevel = protectionLevel;
4300                }
4301            }
4302            return permissionInfo;
4303        }
4304    }
4305
4306    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4307            String packageName, int uid) {
4308        // Signature permission flags area always reported
4309        final int protectionLevelMasked = protectionLevel
4310                & (PermissionInfo.PROTECTION_NORMAL
4311                | PermissionInfo.PROTECTION_DANGEROUS
4312                | PermissionInfo.PROTECTION_SIGNATURE);
4313        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4314            return protectionLevel;
4315        }
4316
4317        // System sees all flags.
4318        final int appId = UserHandle.getAppId(uid);
4319        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4320                || appId == Process.SHELL_UID) {
4321            return protectionLevel;
4322        }
4323
4324        // Normalize package name to handle renamed packages and static libs
4325        packageName = resolveInternalPackageNameLPr(packageName,
4326                PackageManager.VERSION_CODE_HIGHEST);
4327
4328        // Apps that target O see flags for all protection levels.
4329        final PackageSetting ps = mSettings.mPackages.get(packageName);
4330        if (ps == null) {
4331            return protectionLevel;
4332        }
4333        if (ps.appId != appId) {
4334            return protectionLevel;
4335        }
4336
4337        final PackageParser.Package pkg = mPackages.get(packageName);
4338        if (pkg == null) {
4339            return protectionLevel;
4340        }
4341        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4342            return protectionLevelMasked;
4343        }
4344
4345        return protectionLevel;
4346    }
4347
4348    @Override
4349    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4350            int flags) {
4351        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4352            return null;
4353        }
4354        // reader
4355        synchronized (mPackages) {
4356            if (group != null && !mPermissionGroups.containsKey(group)) {
4357                // This is thrown as NameNotFoundException
4358                return null;
4359            }
4360
4361            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4362            for (BasePermission p : mSettings.mPermissions.values()) {
4363                if (group == null) {
4364                    if (p.perm == null || p.perm.info.group == null) {
4365                        out.add(generatePermissionInfo(p, flags));
4366                    }
4367                } else {
4368                    if (p.perm != null && group.equals(p.perm.info.group)) {
4369                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4370                    }
4371                }
4372            }
4373            return new ParceledListSlice<>(out);
4374        }
4375    }
4376
4377    @Override
4378    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4379        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4380            return null;
4381        }
4382        // reader
4383        synchronized (mPackages) {
4384            return PackageParser.generatePermissionGroupInfo(
4385                    mPermissionGroups.get(name), flags);
4386        }
4387    }
4388
4389    @Override
4390    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4391        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4392            return ParceledListSlice.emptyList();
4393        }
4394        // reader
4395        synchronized (mPackages) {
4396            final int N = mPermissionGroups.size();
4397            ArrayList<PermissionGroupInfo> out
4398                    = new ArrayList<PermissionGroupInfo>(N);
4399            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4400                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4401            }
4402            return new ParceledListSlice<>(out);
4403        }
4404    }
4405
4406    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4407            int filterCallingUid, int userId) {
4408        if (!sUserManager.exists(userId)) return null;
4409        PackageSetting ps = mSettings.mPackages.get(packageName);
4410        if (ps != null) {
4411            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4412                return null;
4413            }
4414            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4415                return null;
4416            }
4417            if (ps.pkg == null) {
4418                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4419                if (pInfo != null) {
4420                    return pInfo.applicationInfo;
4421                }
4422                return null;
4423            }
4424            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4425                    ps.readUserState(userId), userId);
4426            if (ai != null) {
4427                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4428            }
4429            return ai;
4430        }
4431        return null;
4432    }
4433
4434    @Override
4435    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4436        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4437    }
4438
4439    /**
4440     * Important: The provided filterCallingUid is used exclusively to filter out applications
4441     * that can be seen based on user state. It's typically the original caller uid prior
4442     * to clearing. Because it can only be provided by trusted code, it's value can be
4443     * trusted and will be used as-is; unlike userId which will be validated by this method.
4444     */
4445    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4446            int filterCallingUid, int userId) {
4447        if (!sUserManager.exists(userId)) return null;
4448        flags = updateFlagsForApplication(flags, userId, packageName);
4449        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4450                false /* requireFullPermission */, false /* checkShell */, "get application info");
4451
4452        // writer
4453        synchronized (mPackages) {
4454            // Normalize package name to handle renamed packages and static libs
4455            packageName = resolveInternalPackageNameLPr(packageName,
4456                    PackageManager.VERSION_CODE_HIGHEST);
4457
4458            PackageParser.Package p = mPackages.get(packageName);
4459            if (DEBUG_PACKAGE_INFO) Log.v(
4460                    TAG, "getApplicationInfo " + packageName
4461                    + ": " + p);
4462            if (p != null) {
4463                PackageSetting ps = mSettings.mPackages.get(packageName);
4464                if (ps == null) return null;
4465                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4466                    return null;
4467                }
4468                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4469                    return null;
4470                }
4471                // Note: isEnabledLP() does not apply here - always return info
4472                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4473                        p, flags, ps.readUserState(userId), userId);
4474                if (ai != null) {
4475                    ai.packageName = resolveExternalPackageNameLPr(p);
4476                }
4477                return ai;
4478            }
4479            if ("android".equals(packageName)||"system".equals(packageName)) {
4480                return mAndroidApplication;
4481            }
4482            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4483                // Already generates the external package name
4484                return generateApplicationInfoFromSettingsLPw(packageName,
4485                        flags, filterCallingUid, userId);
4486            }
4487        }
4488        return null;
4489    }
4490
4491    private String normalizePackageNameLPr(String packageName) {
4492        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4493        return normalizedPackageName != null ? normalizedPackageName : packageName;
4494    }
4495
4496    @Override
4497    public void deletePreloadsFileCache() {
4498        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4499            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4500        }
4501        File dir = Environment.getDataPreloadsFileCacheDirectory();
4502        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4503        FileUtils.deleteContents(dir);
4504    }
4505
4506    @Override
4507    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4508            final int storageFlags, final IPackageDataObserver observer) {
4509        mContext.enforceCallingOrSelfPermission(
4510                android.Manifest.permission.CLEAR_APP_CACHE, null);
4511        mHandler.post(() -> {
4512            boolean success = false;
4513            try {
4514                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4515                success = true;
4516            } catch (IOException e) {
4517                Slog.w(TAG, e);
4518            }
4519            if (observer != null) {
4520                try {
4521                    observer.onRemoveCompleted(null, success);
4522                } catch (RemoteException e) {
4523                    Slog.w(TAG, e);
4524                }
4525            }
4526        });
4527    }
4528
4529    @Override
4530    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4531            final int storageFlags, final IntentSender pi) {
4532        mContext.enforceCallingOrSelfPermission(
4533                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4534        mHandler.post(() -> {
4535            boolean success = false;
4536            try {
4537                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4538                success = true;
4539            } catch (IOException e) {
4540                Slog.w(TAG, e);
4541            }
4542            if (pi != null) {
4543                try {
4544                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4545                } catch (SendIntentException e) {
4546                    Slog.w(TAG, e);
4547                }
4548            }
4549        });
4550    }
4551
4552    /**
4553     * Blocking call to clear various types of cached data across the system
4554     * until the requested bytes are available.
4555     */
4556    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4558        final File file = storage.findPathForUuid(volumeUuid);
4559        if (file.getUsableSpace() >= bytes) return;
4560
4561        if (ENABLE_FREE_CACHE_V2) {
4562            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4563                    volumeUuid);
4564            final boolean aggressive = (storageFlags
4565                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4566            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4567
4568            // 1. Pre-flight to determine if we have any chance to succeed
4569            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4570            if (internalVolume && (aggressive || SystemProperties
4571                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4572                deletePreloadsFileCache();
4573                if (file.getUsableSpace() >= bytes) return;
4574            }
4575
4576            // 3. Consider parsed APK data (aggressive only)
4577            if (internalVolume && aggressive) {
4578                FileUtils.deleteContents(mCacheDir);
4579                if (file.getUsableSpace() >= bytes) return;
4580            }
4581
4582            // 4. Consider cached app data (above quotas)
4583            try {
4584                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4585                        Installer.FLAG_FREE_CACHE_V2);
4586            } catch (InstallerException ignored) {
4587            }
4588            if (file.getUsableSpace() >= bytes) return;
4589
4590            // 5. Consider shared libraries with refcount=0 and age>min cache period
4591            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4592                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4593                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4594                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4595                return;
4596            }
4597
4598            // 6. Consider dexopt output (aggressive only)
4599            // TODO: Implement
4600
4601            // 7. Consider installed instant apps unused longer than min cache period
4602            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4603                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4604                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4605                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4606                return;
4607            }
4608
4609            // 8. Consider cached app data (below quotas)
4610            try {
4611                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4612                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4613            } catch (InstallerException ignored) {
4614            }
4615            if (file.getUsableSpace() >= bytes) return;
4616
4617            // 9. Consider DropBox entries
4618            // TODO: Implement
4619
4620            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4621            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4622                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4623                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4624                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4625                return;
4626            }
4627        } else {
4628            try {
4629                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4630            } catch (InstallerException ignored) {
4631            }
4632            if (file.getUsableSpace() >= bytes) return;
4633        }
4634
4635        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4636    }
4637
4638    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4639            throws IOException {
4640        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4641        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4642
4643        List<VersionedPackage> packagesToDelete = null;
4644        final long now = System.currentTimeMillis();
4645
4646        synchronized (mPackages) {
4647            final int[] allUsers = sUserManager.getUserIds();
4648            final int libCount = mSharedLibraries.size();
4649            for (int i = 0; i < libCount; i++) {
4650                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4651                if (versionedLib == null) {
4652                    continue;
4653                }
4654                final int versionCount = versionedLib.size();
4655                for (int j = 0; j < versionCount; j++) {
4656                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4657                    // Skip packages that are not static shared libs.
4658                    if (!libInfo.isStatic()) {
4659                        break;
4660                    }
4661                    // Important: We skip static shared libs used for some user since
4662                    // in such a case we need to keep the APK on the device. The check for
4663                    // a lib being used for any user is performed by the uninstall call.
4664                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4665                    // Resolve the package name - we use synthetic package names internally
4666                    final String internalPackageName = resolveInternalPackageNameLPr(
4667                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4668                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4669                    // Skip unused static shared libs cached less than the min period
4670                    // to prevent pruning a lib needed by a subsequently installed package.
4671                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4672                        continue;
4673                    }
4674                    if (packagesToDelete == null) {
4675                        packagesToDelete = new ArrayList<>();
4676                    }
4677                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4678                            declaringPackage.getVersionCode()));
4679                }
4680            }
4681        }
4682
4683        if (packagesToDelete != null) {
4684            final int packageCount = packagesToDelete.size();
4685            for (int i = 0; i < packageCount; i++) {
4686                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4687                // Delete the package synchronously (will fail of the lib used for any user).
4688                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4689                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4690                                == PackageManager.DELETE_SUCCEEDED) {
4691                    if (volume.getUsableSpace() >= neededSpace) {
4692                        return true;
4693                    }
4694                }
4695            }
4696        }
4697
4698        return false;
4699    }
4700
4701    /**
4702     * Update given flags based on encryption status of current user.
4703     */
4704    private int updateFlags(int flags, int userId) {
4705        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4706                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4707            // Caller expressed an explicit opinion about what encryption
4708            // aware/unaware components they want to see, so fall through and
4709            // give them what they want
4710        } else {
4711            // Caller expressed no opinion, so match based on user state
4712            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4713                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4714            } else {
4715                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4716            }
4717        }
4718        return flags;
4719    }
4720
4721    private UserManagerInternal getUserManagerInternal() {
4722        if (mUserManagerInternal == null) {
4723            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4724        }
4725        return mUserManagerInternal;
4726    }
4727
4728    private DeviceIdleController.LocalService getDeviceIdleController() {
4729        if (mDeviceIdleController == null) {
4730            mDeviceIdleController =
4731                    LocalServices.getService(DeviceIdleController.LocalService.class);
4732        }
4733        return mDeviceIdleController;
4734    }
4735
4736    /**
4737     * Update given flags when being used to request {@link PackageInfo}.
4738     */
4739    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4740        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4741        boolean triaged = true;
4742        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4743                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4744            // Caller is asking for component details, so they'd better be
4745            // asking for specific encryption matching behavior, or be triaged
4746            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4747                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4748                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4749                triaged = false;
4750            }
4751        }
4752        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4753                | PackageManager.MATCH_SYSTEM_ONLY
4754                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4755            triaged = false;
4756        }
4757        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4758            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4759                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4760                    + Debug.getCallers(5));
4761        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4762                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4763            // If the caller wants all packages and has a restricted profile associated with it,
4764            // then match all users. This is to make sure that launchers that need to access work
4765            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4766            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4767            flags |= PackageManager.MATCH_ANY_USER;
4768        }
4769        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4770            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4771                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4772        }
4773        return updateFlags(flags, userId);
4774    }
4775
4776    /**
4777     * Update given flags when being used to request {@link ApplicationInfo}.
4778     */
4779    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4780        return updateFlagsForPackage(flags, userId, cookie);
4781    }
4782
4783    /**
4784     * Update given flags when being used to request {@link ComponentInfo}.
4785     */
4786    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4787        if (cookie instanceof Intent) {
4788            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4789                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4790            }
4791        }
4792
4793        boolean triaged = true;
4794        // Caller is asking for component details, so they'd better be
4795        // asking for specific encryption matching behavior, or be triaged
4796        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4797                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4798                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4799            triaged = false;
4800        }
4801        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4802            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4803                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4804        }
4805
4806        return updateFlags(flags, userId);
4807    }
4808
4809    /**
4810     * Update given intent when being used to request {@link ResolveInfo}.
4811     */
4812    private Intent updateIntentForResolve(Intent intent) {
4813        if (intent.getSelector() != null) {
4814            intent = intent.getSelector();
4815        }
4816        if (DEBUG_PREFERRED) {
4817            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4818        }
4819        return intent;
4820    }
4821
4822    /**
4823     * Update given flags when being used to request {@link ResolveInfo}.
4824     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4825     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4826     * flag set. However, this flag is only honoured in three circumstances:
4827     * <ul>
4828     * <li>when called from a system process</li>
4829     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4830     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4831     * action and a {@code android.intent.category.BROWSABLE} category</li>
4832     * </ul>
4833     */
4834    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4835        return updateFlagsForResolve(flags, userId, intent, callingUid,
4836                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4837    }
4838    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4839            boolean wantInstantApps) {
4840        return updateFlagsForResolve(flags, userId, intent, callingUid,
4841                wantInstantApps, false /*onlyExposedExplicitly*/);
4842    }
4843    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4844            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4845        // Safe mode means we shouldn't match any third-party components
4846        if (mSafeMode) {
4847            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4848        }
4849        if (getInstantAppPackageName(callingUid) != null) {
4850            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4851            if (onlyExposedExplicitly) {
4852                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4853            }
4854            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4855            flags |= PackageManager.MATCH_INSTANT;
4856        } else {
4857            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4858            final boolean allowMatchInstant =
4859                    (wantInstantApps
4860                            && Intent.ACTION_VIEW.equals(intent.getAction())
4861                            && hasWebURI(intent))
4862                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4863            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4864                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4865            if (!allowMatchInstant) {
4866                flags &= ~PackageManager.MATCH_INSTANT;
4867            }
4868        }
4869        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4870    }
4871
4872    @Override
4873    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4874        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4875    }
4876
4877    /**
4878     * Important: The provided filterCallingUid is used exclusively to filter out activities
4879     * that can be seen based on user state. It's typically the original caller uid prior
4880     * to clearing. Because it can only be provided by trusted code, it's value can be
4881     * trusted and will be used as-is; unlike userId which will be validated by this method.
4882     */
4883    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4884            int filterCallingUid, int userId) {
4885        if (!sUserManager.exists(userId)) return null;
4886        flags = updateFlagsForComponent(flags, userId, component);
4887        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4888                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4889        synchronized (mPackages) {
4890            PackageParser.Activity a = mActivities.mActivities.get(component);
4891
4892            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4893            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4894                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4895                if (ps == null) return null;
4896                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4897                    return null;
4898                }
4899                return PackageParser.generateActivityInfo(
4900                        a, flags, ps.readUserState(userId), userId);
4901            }
4902            if (mResolveComponentName.equals(component)) {
4903                return PackageParser.generateActivityInfo(
4904                        mResolveActivity, flags, new PackageUserState(), userId);
4905            }
4906        }
4907        return null;
4908    }
4909
4910    @Override
4911    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4912            String resolvedType) {
4913        synchronized (mPackages) {
4914            if (component.equals(mResolveComponentName)) {
4915                // The resolver supports EVERYTHING!
4916                return true;
4917            }
4918            final int callingUid = Binder.getCallingUid();
4919            final int callingUserId = UserHandle.getUserId(callingUid);
4920            PackageParser.Activity a = mActivities.mActivities.get(component);
4921            if (a == null) {
4922                return false;
4923            }
4924            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4925            if (ps == null) {
4926                return false;
4927            }
4928            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4929                return false;
4930            }
4931            for (int i=0; i<a.intents.size(); i++) {
4932                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4933                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4934                    return true;
4935                }
4936            }
4937            return false;
4938        }
4939    }
4940
4941    @Override
4942    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4943        if (!sUserManager.exists(userId)) return null;
4944        final int callingUid = Binder.getCallingUid();
4945        flags = updateFlagsForComponent(flags, userId, component);
4946        enforceCrossUserPermission(callingUid, userId,
4947                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4948        synchronized (mPackages) {
4949            PackageParser.Activity a = mReceivers.mActivities.get(component);
4950            if (DEBUG_PACKAGE_INFO) Log.v(
4951                TAG, "getReceiverInfo " + component + ": " + a);
4952            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4953                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4954                if (ps == null) return null;
4955                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4956                    return null;
4957                }
4958                return PackageParser.generateActivityInfo(
4959                        a, flags, ps.readUserState(userId), userId);
4960            }
4961        }
4962        return null;
4963    }
4964
4965    @Override
4966    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4967            int flags, int userId) {
4968        if (!sUserManager.exists(userId)) return null;
4969        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4970        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4971            return null;
4972        }
4973
4974        flags = updateFlagsForPackage(flags, userId, null);
4975
4976        final boolean canSeeStaticLibraries =
4977                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4978                        == PERMISSION_GRANTED
4979                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4980                        == PERMISSION_GRANTED
4981                || canRequestPackageInstallsInternal(packageName,
4982                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4983                        false  /* throwIfPermNotDeclared*/)
4984                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4985                        == PERMISSION_GRANTED;
4986
4987        synchronized (mPackages) {
4988            List<SharedLibraryInfo> result = null;
4989
4990            final int libCount = mSharedLibraries.size();
4991            for (int i = 0; i < libCount; i++) {
4992                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4993                if (versionedLib == null) {
4994                    continue;
4995                }
4996
4997                final int versionCount = versionedLib.size();
4998                for (int j = 0; j < versionCount; j++) {
4999                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
5000                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
5001                        break;
5002                    }
5003                    final long identity = Binder.clearCallingIdentity();
5004                    try {
5005                        PackageInfo packageInfo = getPackageInfoVersioned(
5006                                libInfo.getDeclaringPackage(), flags
5007                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5008                        if (packageInfo == null) {
5009                            continue;
5010                        }
5011                    } finally {
5012                        Binder.restoreCallingIdentity(identity);
5013                    }
5014
5015                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5016                            libInfo.getVersion(), libInfo.getType(),
5017                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5018                            flags, userId));
5019
5020                    if (result == null) {
5021                        result = new ArrayList<>();
5022                    }
5023                    result.add(resLibInfo);
5024                }
5025            }
5026
5027            return result != null ? new ParceledListSlice<>(result) : null;
5028        }
5029    }
5030
5031    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5032            SharedLibraryInfo libInfo, int flags, int userId) {
5033        List<VersionedPackage> versionedPackages = null;
5034        final int packageCount = mSettings.mPackages.size();
5035        for (int i = 0; i < packageCount; i++) {
5036            PackageSetting ps = mSettings.mPackages.valueAt(i);
5037
5038            if (ps == null) {
5039                continue;
5040            }
5041
5042            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5043                continue;
5044            }
5045
5046            final String libName = libInfo.getName();
5047            if (libInfo.isStatic()) {
5048                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5049                if (libIdx < 0) {
5050                    continue;
5051                }
5052                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5053                    continue;
5054                }
5055                if (versionedPackages == null) {
5056                    versionedPackages = new ArrayList<>();
5057                }
5058                // If the dependent is a static shared lib, use the public package name
5059                String dependentPackageName = ps.name;
5060                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5061                    dependentPackageName = ps.pkg.manifestPackageName;
5062                }
5063                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5064            } else if (ps.pkg != null) {
5065                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5066                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5067                    if (versionedPackages == null) {
5068                        versionedPackages = new ArrayList<>();
5069                    }
5070                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5071                }
5072            }
5073        }
5074
5075        return versionedPackages;
5076    }
5077
5078    @Override
5079    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5080        if (!sUserManager.exists(userId)) return null;
5081        final int callingUid = Binder.getCallingUid();
5082        flags = updateFlagsForComponent(flags, userId, component);
5083        enforceCrossUserPermission(callingUid, userId,
5084                false /* requireFullPermission */, false /* checkShell */, "get service info");
5085        synchronized (mPackages) {
5086            PackageParser.Service s = mServices.mServices.get(component);
5087            if (DEBUG_PACKAGE_INFO) Log.v(
5088                TAG, "getServiceInfo " + component + ": " + s);
5089            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5090                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5091                if (ps == null) return null;
5092                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5093                    return null;
5094                }
5095                return PackageParser.generateServiceInfo(
5096                        s, flags, ps.readUserState(userId), userId);
5097            }
5098        }
5099        return null;
5100    }
5101
5102    @Override
5103    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5104        if (!sUserManager.exists(userId)) return null;
5105        final int callingUid = Binder.getCallingUid();
5106        flags = updateFlagsForComponent(flags, userId, component);
5107        enforceCrossUserPermission(callingUid, userId,
5108                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5109        synchronized (mPackages) {
5110            PackageParser.Provider p = mProviders.mProviders.get(component);
5111            if (DEBUG_PACKAGE_INFO) Log.v(
5112                TAG, "getProviderInfo " + component + ": " + p);
5113            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5115                if (ps == null) return null;
5116                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5117                    return null;
5118                }
5119                return PackageParser.generateProviderInfo(
5120                        p, flags, ps.readUserState(userId), userId);
5121            }
5122        }
5123        return null;
5124    }
5125
5126    @Override
5127    public String[] getSystemSharedLibraryNames() {
5128        // allow instant applications
5129        synchronized (mPackages) {
5130            Set<String> libs = null;
5131            final int libCount = mSharedLibraries.size();
5132            for (int i = 0; i < libCount; i++) {
5133                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5134                if (versionedLib == null) {
5135                    continue;
5136                }
5137                final int versionCount = versionedLib.size();
5138                for (int j = 0; j < versionCount; j++) {
5139                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5140                    if (!libEntry.info.isStatic()) {
5141                        if (libs == null) {
5142                            libs = new ArraySet<>();
5143                        }
5144                        libs.add(libEntry.info.getName());
5145                        break;
5146                    }
5147                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5148                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5149                            UserHandle.getUserId(Binder.getCallingUid()),
5150                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5151                        if (libs == null) {
5152                            libs = new ArraySet<>();
5153                        }
5154                        libs.add(libEntry.info.getName());
5155                        break;
5156                    }
5157                }
5158            }
5159
5160            if (libs != null) {
5161                String[] libsArray = new String[libs.size()];
5162                libs.toArray(libsArray);
5163                return libsArray;
5164            }
5165
5166            return null;
5167        }
5168    }
5169
5170    @Override
5171    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5172        // allow instant applications
5173        synchronized (mPackages) {
5174            return mServicesSystemSharedLibraryPackageName;
5175        }
5176    }
5177
5178    @Override
5179    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5180        // allow instant applications
5181        synchronized (mPackages) {
5182            return mSharedSystemSharedLibraryPackageName;
5183        }
5184    }
5185
5186    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5187        for (int i = userList.length - 1; i >= 0; --i) {
5188            final int userId = userList[i];
5189            // don't add instant app to the list of updates
5190            if (pkgSetting.getInstantApp(userId)) {
5191                continue;
5192            }
5193            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5194            if (changedPackages == null) {
5195                changedPackages = new SparseArray<>();
5196                mChangedPackages.put(userId, changedPackages);
5197            }
5198            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5199            if (sequenceNumbers == null) {
5200                sequenceNumbers = new HashMap<>();
5201                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5202            }
5203            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5204            if (sequenceNumber != null) {
5205                changedPackages.remove(sequenceNumber);
5206            }
5207            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5208            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5209        }
5210        mChangedPackagesSequenceNumber++;
5211    }
5212
5213    @Override
5214    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5215        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5216            return null;
5217        }
5218        synchronized (mPackages) {
5219            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5220                return null;
5221            }
5222            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5223            if (changedPackages == null) {
5224                return null;
5225            }
5226            final List<String> packageNames =
5227                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5228            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5229                final String packageName = changedPackages.get(i);
5230                if (packageName != null) {
5231                    packageNames.add(packageName);
5232                }
5233            }
5234            return packageNames.isEmpty()
5235                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5236        }
5237    }
5238
5239    @Override
5240    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5241        // allow instant applications
5242        ArrayList<FeatureInfo> res;
5243        synchronized (mAvailableFeatures) {
5244            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5245            res.addAll(mAvailableFeatures.values());
5246        }
5247        final FeatureInfo fi = new FeatureInfo();
5248        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5249                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5250        res.add(fi);
5251
5252        return new ParceledListSlice<>(res);
5253    }
5254
5255    @Override
5256    public boolean hasSystemFeature(String name, int version) {
5257        // allow instant applications
5258        synchronized (mAvailableFeatures) {
5259            final FeatureInfo feat = mAvailableFeatures.get(name);
5260            if (feat == null) {
5261                return false;
5262            } else {
5263                return feat.version >= version;
5264            }
5265        }
5266    }
5267
5268    @Override
5269    public int checkPermission(String permName, String pkgName, int userId) {
5270        if (!sUserManager.exists(userId)) {
5271            return PackageManager.PERMISSION_DENIED;
5272        }
5273        final int callingUid = Binder.getCallingUid();
5274
5275        synchronized (mPackages) {
5276            final PackageParser.Package p = mPackages.get(pkgName);
5277            if (p != null && p.mExtras != null) {
5278                final PackageSetting ps = (PackageSetting) p.mExtras;
5279                if (filterAppAccessLPr(ps, callingUid, userId)) {
5280                    return PackageManager.PERMISSION_DENIED;
5281                }
5282                final boolean instantApp = ps.getInstantApp(userId);
5283                final PermissionsState permissionsState = ps.getPermissionsState();
5284                if (permissionsState.hasPermission(permName, userId)) {
5285                    if (instantApp) {
5286                        BasePermission bp = mSettings.mPermissions.get(permName);
5287                        if (bp != null && bp.isInstant()) {
5288                            return PackageManager.PERMISSION_GRANTED;
5289                        }
5290                    } else {
5291                        return PackageManager.PERMISSION_GRANTED;
5292                    }
5293                }
5294                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5295                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5296                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5297                    return PackageManager.PERMISSION_GRANTED;
5298                }
5299            }
5300        }
5301
5302        return PackageManager.PERMISSION_DENIED;
5303    }
5304
5305    @Override
5306    public int checkUidPermission(String permName, int uid) {
5307        final int callingUid = Binder.getCallingUid();
5308        final int callingUserId = UserHandle.getUserId(callingUid);
5309        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5310        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5311        final int userId = UserHandle.getUserId(uid);
5312        if (!sUserManager.exists(userId)) {
5313            return PackageManager.PERMISSION_DENIED;
5314        }
5315
5316        synchronized (mPackages) {
5317            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5318            if (obj != null) {
5319                if (obj instanceof SharedUserSetting) {
5320                    if (isCallerInstantApp) {
5321                        return PackageManager.PERMISSION_DENIED;
5322                    }
5323                } else if (obj instanceof PackageSetting) {
5324                    final PackageSetting ps = (PackageSetting) obj;
5325                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5326                        return PackageManager.PERMISSION_DENIED;
5327                    }
5328                }
5329                final SettingBase settingBase = (SettingBase) obj;
5330                final PermissionsState permissionsState = settingBase.getPermissionsState();
5331                if (permissionsState.hasPermission(permName, userId)) {
5332                    if (isUidInstantApp) {
5333                        BasePermission bp = mSettings.mPermissions.get(permName);
5334                        if (bp != null && bp.isInstant()) {
5335                            return PackageManager.PERMISSION_GRANTED;
5336                        }
5337                    } else {
5338                        return PackageManager.PERMISSION_GRANTED;
5339                    }
5340                }
5341                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5342                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5343                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5344                    return PackageManager.PERMISSION_GRANTED;
5345                }
5346            } else {
5347                ArraySet<String> perms = mSystemPermissions.get(uid);
5348                if (perms != null) {
5349                    if (perms.contains(permName)) {
5350                        return PackageManager.PERMISSION_GRANTED;
5351                    }
5352                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5353                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5354                        return PackageManager.PERMISSION_GRANTED;
5355                    }
5356                }
5357            }
5358        }
5359
5360        return PackageManager.PERMISSION_DENIED;
5361    }
5362
5363    @Override
5364    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5365        if (UserHandle.getCallingUserId() != userId) {
5366            mContext.enforceCallingPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "isPermissionRevokedByPolicy for user " + userId);
5369        }
5370
5371        if (checkPermission(permission, packageName, userId)
5372                == PackageManager.PERMISSION_GRANTED) {
5373            return false;
5374        }
5375
5376        final int callingUid = Binder.getCallingUid();
5377        if (getInstantAppPackageName(callingUid) != null) {
5378            if (!isCallerSameApp(packageName, callingUid)) {
5379                return false;
5380            }
5381        } else {
5382            if (isInstantApp(packageName, userId)) {
5383                return false;
5384            }
5385        }
5386
5387        final long identity = Binder.clearCallingIdentity();
5388        try {
5389            final int flags = getPermissionFlags(permission, packageName, userId);
5390            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5391        } finally {
5392            Binder.restoreCallingIdentity(identity);
5393        }
5394    }
5395
5396    @Override
5397    public String getPermissionControllerPackageName() {
5398        synchronized (mPackages) {
5399            return mRequiredInstallerPackage;
5400        }
5401    }
5402
5403    /**
5404     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5405     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5406     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5407     * @param message the message to log on security exception
5408     */
5409    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5410            boolean checkShell, String message) {
5411        if (userId < 0) {
5412            throw new IllegalArgumentException("Invalid userId " + userId);
5413        }
5414        if (checkShell) {
5415            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5416        }
5417        if (userId == UserHandle.getUserId(callingUid)) return;
5418        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5419            if (requireFullPermission) {
5420                mContext.enforceCallingOrSelfPermission(
5421                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5422            } else {
5423                try {
5424                    mContext.enforceCallingOrSelfPermission(
5425                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5426                } catch (SecurityException se) {
5427                    mContext.enforceCallingOrSelfPermission(
5428                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5429                }
5430            }
5431        }
5432    }
5433
5434    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5435        if (callingUid == Process.SHELL_UID) {
5436            if (userHandle >= 0
5437                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5438                throw new SecurityException("Shell does not have permission to access user "
5439                        + userHandle);
5440            } else if (userHandle < 0) {
5441                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5442                        + Debug.getCallers(3));
5443            }
5444        }
5445    }
5446
5447    private BasePermission findPermissionTreeLP(String permName) {
5448        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5449            if (permName.startsWith(bp.name) &&
5450                    permName.length() > bp.name.length() &&
5451                    permName.charAt(bp.name.length()) == '.') {
5452                return bp;
5453            }
5454        }
5455        return null;
5456    }
5457
5458    private BasePermission checkPermissionTreeLP(String permName) {
5459        if (permName != null) {
5460            BasePermission bp = findPermissionTreeLP(permName);
5461            if (bp != null) {
5462                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5463                    return bp;
5464                }
5465                throw new SecurityException("Calling uid "
5466                        + Binder.getCallingUid()
5467                        + " is not allowed to add to permission tree "
5468                        + bp.name + " owned by uid " + bp.uid);
5469            }
5470        }
5471        throw new SecurityException("No permission tree found for " + permName);
5472    }
5473
5474    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5475        if (s1 == null) {
5476            return s2 == null;
5477        }
5478        if (s2 == null) {
5479            return false;
5480        }
5481        if (s1.getClass() != s2.getClass()) {
5482            return false;
5483        }
5484        return s1.equals(s2);
5485    }
5486
5487    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5488        if (pi1.icon != pi2.icon) return false;
5489        if (pi1.logo != pi2.logo) return false;
5490        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5491        if (!compareStrings(pi1.name, pi2.name)) return false;
5492        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5493        // We'll take care of setting this one.
5494        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5495        // These are not currently stored in settings.
5496        //if (!compareStrings(pi1.group, pi2.group)) return false;
5497        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5498        //if (pi1.labelRes != pi2.labelRes) return false;
5499        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5500        return true;
5501    }
5502
5503    int permissionInfoFootprint(PermissionInfo info) {
5504        int size = info.name.length();
5505        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5506        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5507        return size;
5508    }
5509
5510    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5511        int size = 0;
5512        for (BasePermission perm : mSettings.mPermissions.values()) {
5513            if (perm.uid == tree.uid) {
5514                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5515            }
5516        }
5517        return size;
5518    }
5519
5520    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5521        // We calculate the max size of permissions defined by this uid and throw
5522        // if that plus the size of 'info' would exceed our stated maximum.
5523        if (tree.uid != Process.SYSTEM_UID) {
5524            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5525            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5526                throw new SecurityException("Permission tree size cap exceeded");
5527            }
5528        }
5529    }
5530
5531    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5532        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5533            throw new SecurityException("Instant apps can't add permissions");
5534        }
5535        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5536            throw new SecurityException("Label must be specified in permission");
5537        }
5538        BasePermission tree = checkPermissionTreeLP(info.name);
5539        BasePermission bp = mSettings.mPermissions.get(info.name);
5540        boolean added = bp == null;
5541        boolean changed = true;
5542        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5543        if (added) {
5544            enforcePermissionCapLocked(info, tree);
5545            bp = new BasePermission(info.name, tree.sourcePackage,
5546                    BasePermission.TYPE_DYNAMIC);
5547        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5548            throw new SecurityException(
5549                    "Not allowed to modify non-dynamic permission "
5550                    + info.name);
5551        } else {
5552            if (bp.protectionLevel == fixedLevel
5553                    && bp.perm.owner.equals(tree.perm.owner)
5554                    && bp.uid == tree.uid
5555                    && comparePermissionInfos(bp.perm.info, info)) {
5556                changed = false;
5557            }
5558        }
5559        bp.protectionLevel = fixedLevel;
5560        info = new PermissionInfo(info);
5561        info.protectionLevel = fixedLevel;
5562        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5563        bp.perm.info.packageName = tree.perm.info.packageName;
5564        bp.uid = tree.uid;
5565        if (added) {
5566            mSettings.mPermissions.put(info.name, bp);
5567        }
5568        if (changed) {
5569            if (!async) {
5570                mSettings.writeLPr();
5571            } else {
5572                scheduleWriteSettingsLocked();
5573            }
5574        }
5575        return added;
5576    }
5577
5578    @Override
5579    public boolean addPermission(PermissionInfo info) {
5580        synchronized (mPackages) {
5581            return addPermissionLocked(info, false);
5582        }
5583    }
5584
5585    @Override
5586    public boolean addPermissionAsync(PermissionInfo info) {
5587        synchronized (mPackages) {
5588            return addPermissionLocked(info, true);
5589        }
5590    }
5591
5592    @Override
5593    public void removePermission(String name) {
5594        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5595            throw new SecurityException("Instant applications don't have access to this method");
5596        }
5597        synchronized (mPackages) {
5598            checkPermissionTreeLP(name);
5599            BasePermission bp = mSettings.mPermissions.get(name);
5600            if (bp != null) {
5601                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5602                    throw new SecurityException(
5603                            "Not allowed to modify non-dynamic permission "
5604                            + name);
5605                }
5606                mSettings.mPermissions.remove(name);
5607                mSettings.writeLPr();
5608            }
5609        }
5610    }
5611
5612    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5613            PackageParser.Package pkg, BasePermission bp) {
5614        int index = pkg.requestedPermissions.indexOf(bp.name);
5615        if (index == -1) {
5616            throw new SecurityException("Package " + pkg.packageName
5617                    + " has not requested permission " + bp.name);
5618        }
5619        if (!bp.isRuntime() && !bp.isDevelopment()) {
5620            throw new SecurityException("Permission " + bp.name
5621                    + " is not a changeable permission type");
5622        }
5623    }
5624
5625    @Override
5626    public void grantRuntimePermission(String packageName, String name, final int userId) {
5627        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5628    }
5629
5630    private void grantRuntimePermission(String packageName, String name, final int userId,
5631            boolean overridePolicy) {
5632        if (!sUserManager.exists(userId)) {
5633            Log.e(TAG, "No such user:" + userId);
5634            return;
5635        }
5636        final int callingUid = Binder.getCallingUid();
5637
5638        mContext.enforceCallingOrSelfPermission(
5639                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5640                "grantRuntimePermission");
5641
5642        enforceCrossUserPermission(callingUid, userId,
5643                true /* requireFullPermission */, true /* checkShell */,
5644                "grantRuntimePermission");
5645
5646        final int uid;
5647        final PackageSetting ps;
5648
5649        synchronized (mPackages) {
5650            final PackageParser.Package pkg = mPackages.get(packageName);
5651            if (pkg == null) {
5652                throw new IllegalArgumentException("Unknown package: " + packageName);
5653            }
5654            final BasePermission bp = mSettings.mPermissions.get(name);
5655            if (bp == null) {
5656                throw new IllegalArgumentException("Unknown permission: " + name);
5657            }
5658            ps = (PackageSetting) pkg.mExtras;
5659            if (ps == null
5660                    || filterAppAccessLPr(ps, callingUid, userId)) {
5661                throw new IllegalArgumentException("Unknown package: " + packageName);
5662            }
5663
5664            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5665
5666            // If a permission review is required for legacy apps we represent
5667            // their permissions as always granted runtime ones since we need
5668            // to keep the review required permission flag per user while an
5669            // install permission's state is shared across all users.
5670            if (mPermissionReviewRequired
5671                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5672                    && bp.isRuntime()) {
5673                return;
5674            }
5675
5676            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5677
5678            final PermissionsState permissionsState = ps.getPermissionsState();
5679
5680            final int flags = permissionsState.getPermissionFlags(name, userId);
5681            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5682                throw new SecurityException("Cannot grant system fixed permission "
5683                        + name + " for package " + packageName);
5684            }
5685            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5686                throw new SecurityException("Cannot grant policy fixed permission "
5687                        + name + " for package " + packageName);
5688            }
5689
5690            if (bp.isDevelopment()) {
5691                // Development permissions must be handled specially, since they are not
5692                // normal runtime permissions.  For now they apply to all users.
5693                if (permissionsState.grantInstallPermission(bp) !=
5694                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5695                    scheduleWriteSettingsLocked();
5696                }
5697                return;
5698            }
5699
5700            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5701                throw new SecurityException("Cannot grant non-ephemeral permission"
5702                        + name + " for package " + packageName);
5703            }
5704
5705            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5706                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5707                return;
5708            }
5709
5710            final int result = permissionsState.grantRuntimePermission(bp, userId);
5711            switch (result) {
5712                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5713                    return;
5714                }
5715
5716                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5717                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5718                    mHandler.post(new Runnable() {
5719                        @Override
5720                        public void run() {
5721                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5722                        }
5723                    });
5724                }
5725                break;
5726            }
5727
5728            if (bp.isRuntime()) {
5729                logPermissionGranted(mContext, name, packageName);
5730            }
5731
5732            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5733
5734            // Not critical if that is lost - app has to request again.
5735            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5736        }
5737
5738        // Only need to do this if user is initialized. Otherwise it's a new user
5739        // and there are no processes running as the user yet and there's no need
5740        // to make an expensive call to remount processes for the changed permissions.
5741        if (READ_EXTERNAL_STORAGE.equals(name)
5742                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5743            final long token = Binder.clearCallingIdentity();
5744            try {
5745                if (sUserManager.isInitialized(userId)) {
5746                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5747                            StorageManagerInternal.class);
5748                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5749                }
5750            } finally {
5751                Binder.restoreCallingIdentity(token);
5752            }
5753        }
5754    }
5755
5756    @Override
5757    public void revokeRuntimePermission(String packageName, String name, int userId) {
5758        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5759    }
5760
5761    private void revokeRuntimePermission(String packageName, String name, int userId,
5762            boolean overridePolicy) {
5763        if (!sUserManager.exists(userId)) {
5764            Log.e(TAG, "No such user:" + userId);
5765            return;
5766        }
5767
5768        mContext.enforceCallingOrSelfPermission(
5769                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5770                "revokeRuntimePermission");
5771
5772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5773                true /* requireFullPermission */, true /* checkShell */,
5774                "revokeRuntimePermission");
5775
5776        final int appId;
5777
5778        synchronized (mPackages) {
5779            final PackageParser.Package pkg = mPackages.get(packageName);
5780            if (pkg == null) {
5781                throw new IllegalArgumentException("Unknown package: " + packageName);
5782            }
5783            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5784            if (ps == null
5785                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5786                throw new IllegalArgumentException("Unknown package: " + packageName);
5787            }
5788            final BasePermission bp = mSettings.mPermissions.get(name);
5789            if (bp == null) {
5790                throw new IllegalArgumentException("Unknown permission: " + name);
5791            }
5792
5793            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5794
5795            // If a permission review is required for legacy apps we represent
5796            // their permissions as always granted runtime ones since we need
5797            // to keep the review required permission flag per user while an
5798            // install permission's state is shared across all users.
5799            if (mPermissionReviewRequired
5800                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5801                    && bp.isRuntime()) {
5802                return;
5803            }
5804
5805            final PermissionsState permissionsState = ps.getPermissionsState();
5806
5807            final int flags = permissionsState.getPermissionFlags(name, userId);
5808            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5809                throw new SecurityException("Cannot revoke system fixed permission "
5810                        + name + " for package " + packageName);
5811            }
5812            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5813                throw new SecurityException("Cannot revoke policy fixed permission "
5814                        + name + " for package " + packageName);
5815            }
5816
5817            if (bp.isDevelopment()) {
5818                // Development permissions must be handled specially, since they are not
5819                // normal runtime permissions.  For now they apply to all users.
5820                if (permissionsState.revokeInstallPermission(bp) !=
5821                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5822                    scheduleWriteSettingsLocked();
5823                }
5824                return;
5825            }
5826
5827            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5828                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5829                return;
5830            }
5831
5832            if (bp.isRuntime()) {
5833                logPermissionRevoked(mContext, name, packageName);
5834            }
5835
5836            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5837
5838            // Critical, after this call app should never have the permission.
5839            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5840
5841            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5842        }
5843
5844        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5845    }
5846
5847    /**
5848     * Get the first event id for the permission.
5849     *
5850     * <p>There are four events for each permission: <ul>
5851     *     <li>Request permission: first id + 0</li>
5852     *     <li>Grant permission: first id + 1</li>
5853     *     <li>Request for permission denied: first id + 2</li>
5854     *     <li>Revoke permission: first id + 3</li>
5855     * </ul></p>
5856     *
5857     * @param name name of the permission
5858     *
5859     * @return The first event id for the permission
5860     */
5861    private static int getBaseEventId(@NonNull String name) {
5862        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5863
5864        if (eventIdIndex == -1) {
5865            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5866                    || Build.IS_USER) {
5867                Log.i(TAG, "Unknown permission " + name);
5868
5869                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5870            } else {
5871                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5872                //
5873                // Also update
5874                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5875                // - metrics_constants.proto
5876                throw new IllegalStateException("Unknown permission " + name);
5877            }
5878        }
5879
5880        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5881    }
5882
5883    /**
5884     * Log that a permission was revoked.
5885     *
5886     * @param context Context of the caller
5887     * @param name name of the permission
5888     * @param packageName package permission if for
5889     */
5890    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5891            @NonNull String packageName) {
5892        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5893    }
5894
5895    /**
5896     * Log that a permission request was granted.
5897     *
5898     * @param context Context of the caller
5899     * @param name name of the permission
5900     * @param packageName package permission if for
5901     */
5902    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5903            @NonNull String packageName) {
5904        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5905    }
5906
5907    @Override
5908    public void resetRuntimePermissions() {
5909        mContext.enforceCallingOrSelfPermission(
5910                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5911                "revokeRuntimePermission");
5912
5913        int callingUid = Binder.getCallingUid();
5914        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5915            mContext.enforceCallingOrSelfPermission(
5916                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5917                    "resetRuntimePermissions");
5918        }
5919
5920        synchronized (mPackages) {
5921            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5922            for (int userId : UserManagerService.getInstance().getUserIds()) {
5923                final int packageCount = mPackages.size();
5924                for (int i = 0; i < packageCount; i++) {
5925                    PackageParser.Package pkg = mPackages.valueAt(i);
5926                    if (!(pkg.mExtras instanceof PackageSetting)) {
5927                        continue;
5928                    }
5929                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5930                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5931                }
5932            }
5933        }
5934    }
5935
5936    @Override
5937    public int getPermissionFlags(String name, String packageName, int userId) {
5938        if (!sUserManager.exists(userId)) {
5939            return 0;
5940        }
5941
5942        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5943
5944        final int callingUid = Binder.getCallingUid();
5945        enforceCrossUserPermission(callingUid, userId,
5946                true /* requireFullPermission */, false /* checkShell */,
5947                "getPermissionFlags");
5948
5949        synchronized (mPackages) {
5950            final PackageParser.Package pkg = mPackages.get(packageName);
5951            if (pkg == null) {
5952                return 0;
5953            }
5954            final BasePermission bp = mSettings.mPermissions.get(name);
5955            if (bp == null) {
5956                return 0;
5957            }
5958            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5959            if (ps == null
5960                    || filterAppAccessLPr(ps, callingUid, userId)) {
5961                return 0;
5962            }
5963            PermissionsState permissionsState = ps.getPermissionsState();
5964            return permissionsState.getPermissionFlags(name, userId);
5965        }
5966    }
5967
5968    @Override
5969    public void updatePermissionFlags(String name, String packageName, int flagMask,
5970            int flagValues, int userId) {
5971        if (!sUserManager.exists(userId)) {
5972            return;
5973        }
5974
5975        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5976
5977        final int callingUid = Binder.getCallingUid();
5978        enforceCrossUserPermission(callingUid, userId,
5979                true /* requireFullPermission */, true /* checkShell */,
5980                "updatePermissionFlags");
5981
5982        // Only the system can change these flags and nothing else.
5983        if (getCallingUid() != Process.SYSTEM_UID) {
5984            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5985            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5986            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5987            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5988            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5989        }
5990
5991        synchronized (mPackages) {
5992            final PackageParser.Package pkg = mPackages.get(packageName);
5993            if (pkg == null) {
5994                throw new IllegalArgumentException("Unknown package: " + packageName);
5995            }
5996            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5997            if (ps == null
5998                    || filterAppAccessLPr(ps, callingUid, userId)) {
5999                throw new IllegalArgumentException("Unknown package: " + packageName);
6000            }
6001
6002            final BasePermission bp = mSettings.mPermissions.get(name);
6003            if (bp == null) {
6004                throw new IllegalArgumentException("Unknown permission: " + name);
6005            }
6006
6007            PermissionsState permissionsState = ps.getPermissionsState();
6008
6009            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
6010
6011            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
6012                // Install and runtime permissions are stored in different places,
6013                // so figure out what permission changed and persist the change.
6014                if (permissionsState.getInstallPermissionState(name) != null) {
6015                    scheduleWriteSettingsLocked();
6016                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
6017                        || hadState) {
6018                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6019                }
6020            }
6021        }
6022    }
6023
6024    /**
6025     * Update the permission flags for all packages and runtime permissions of a user in order
6026     * to allow device or profile owner to remove POLICY_FIXED.
6027     */
6028    @Override
6029    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
6030        if (!sUserManager.exists(userId)) {
6031            return;
6032        }
6033
6034        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
6035
6036        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6037                true /* requireFullPermission */, true /* checkShell */,
6038                "updatePermissionFlagsForAllApps");
6039
6040        // Only the system can change system fixed flags.
6041        if (getCallingUid() != Process.SYSTEM_UID) {
6042            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6043            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6044        }
6045
6046        synchronized (mPackages) {
6047            boolean changed = false;
6048            final int packageCount = mPackages.size();
6049            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6050                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6051                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6052                if (ps == null) {
6053                    continue;
6054                }
6055                PermissionsState permissionsState = ps.getPermissionsState();
6056                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6057                        userId, flagMask, flagValues);
6058            }
6059            if (changed) {
6060                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6061            }
6062        }
6063    }
6064
6065    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6066        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6067                != PackageManager.PERMISSION_GRANTED
6068            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6069                != PackageManager.PERMISSION_GRANTED) {
6070            throw new SecurityException(message + " requires "
6071                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6072                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6073        }
6074    }
6075
6076    @Override
6077    public boolean shouldShowRequestPermissionRationale(String permissionName,
6078            String packageName, int userId) {
6079        if (UserHandle.getCallingUserId() != userId) {
6080            mContext.enforceCallingPermission(
6081                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6082                    "canShowRequestPermissionRationale for user " + userId);
6083        }
6084
6085        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6086        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6087            return false;
6088        }
6089
6090        if (checkPermission(permissionName, packageName, userId)
6091                == PackageManager.PERMISSION_GRANTED) {
6092            return false;
6093        }
6094
6095        final int flags;
6096
6097        final long identity = Binder.clearCallingIdentity();
6098        try {
6099            flags = getPermissionFlags(permissionName,
6100                    packageName, userId);
6101        } finally {
6102            Binder.restoreCallingIdentity(identity);
6103        }
6104
6105        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6106                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6107                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6108
6109        if ((flags & fixedFlags) != 0) {
6110            return false;
6111        }
6112
6113        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6114    }
6115
6116    @Override
6117    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6118        mContext.enforceCallingOrSelfPermission(
6119                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6120                "addOnPermissionsChangeListener");
6121
6122        synchronized (mPackages) {
6123            mOnPermissionChangeListeners.addListenerLocked(listener);
6124        }
6125    }
6126
6127    @Override
6128    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6129        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6130            throw new SecurityException("Instant applications don't have access to this method");
6131        }
6132        synchronized (mPackages) {
6133            mOnPermissionChangeListeners.removeListenerLocked(listener);
6134        }
6135    }
6136
6137    @Override
6138    public boolean isProtectedBroadcast(String actionName) {
6139        // allow instant applications
6140        synchronized (mProtectedBroadcasts) {
6141            if (mProtectedBroadcasts.contains(actionName)) {
6142                return true;
6143            } else if (actionName != null) {
6144                // TODO: remove these terrible hacks
6145                if (actionName.startsWith("android.net.netmon.lingerExpired")
6146                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6147                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6148                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6149                    return true;
6150                }
6151            }
6152        }
6153        return false;
6154    }
6155
6156    @Override
6157    public int checkSignatures(String pkg1, String pkg2) {
6158        synchronized (mPackages) {
6159            final PackageParser.Package p1 = mPackages.get(pkg1);
6160            final PackageParser.Package p2 = mPackages.get(pkg2);
6161            if (p1 == null || p1.mExtras == null
6162                    || p2 == null || p2.mExtras == null) {
6163                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6164            }
6165            final int callingUid = Binder.getCallingUid();
6166            final int callingUserId = UserHandle.getUserId(callingUid);
6167            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6168            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6169            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6170                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6171                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6172            }
6173            return compareSignatures(p1.mSignatures, p2.mSignatures);
6174        }
6175    }
6176
6177    @Override
6178    public int checkUidSignatures(int uid1, int uid2) {
6179        final int callingUid = Binder.getCallingUid();
6180        final int callingUserId = UserHandle.getUserId(callingUid);
6181        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6182        // Map to base uids.
6183        uid1 = UserHandle.getAppId(uid1);
6184        uid2 = UserHandle.getAppId(uid2);
6185        // reader
6186        synchronized (mPackages) {
6187            Signature[] s1;
6188            Signature[] s2;
6189            Object obj = mSettings.getUserIdLPr(uid1);
6190            if (obj != null) {
6191                if (obj instanceof SharedUserSetting) {
6192                    if (isCallerInstantApp) {
6193                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6194                    }
6195                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6196                } else if (obj instanceof PackageSetting) {
6197                    final PackageSetting ps = (PackageSetting) obj;
6198                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6199                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6200                    }
6201                    s1 = ps.signatures.mSignatures;
6202                } else {
6203                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6204                }
6205            } else {
6206                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6207            }
6208            obj = mSettings.getUserIdLPr(uid2);
6209            if (obj != null) {
6210                if (obj instanceof SharedUserSetting) {
6211                    if (isCallerInstantApp) {
6212                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6213                    }
6214                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6215                } else if (obj instanceof PackageSetting) {
6216                    final PackageSetting ps = (PackageSetting) obj;
6217                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6218                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6219                    }
6220                    s2 = ps.signatures.mSignatures;
6221                } else {
6222                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6223                }
6224            } else {
6225                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6226            }
6227            return compareSignatures(s1, s2);
6228        }
6229    }
6230
6231    /**
6232     * This method should typically only be used when granting or revoking
6233     * permissions, since the app may immediately restart after this call.
6234     * <p>
6235     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6236     * guard your work against the app being relaunched.
6237     */
6238    private void killUid(int appId, int userId, String reason) {
6239        final long identity = Binder.clearCallingIdentity();
6240        try {
6241            IActivityManager am = ActivityManager.getService();
6242            if (am != null) {
6243                try {
6244                    am.killUid(appId, userId, reason);
6245                } catch (RemoteException e) {
6246                    /* ignore - same process */
6247                }
6248            }
6249        } finally {
6250            Binder.restoreCallingIdentity(identity);
6251        }
6252    }
6253
6254    /**
6255     * Compares two sets of signatures. Returns:
6256     * <br />
6257     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6258     * <br />
6259     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6260     * <br />
6261     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6262     * <br />
6263     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6264     * <br />
6265     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6266     */
6267    static int compareSignatures(Signature[] s1, Signature[] s2) {
6268        if (s1 == null) {
6269            return s2 == null
6270                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6271                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6272        }
6273
6274        if (s2 == null) {
6275            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6276        }
6277
6278        if (s1.length != s2.length) {
6279            return PackageManager.SIGNATURE_NO_MATCH;
6280        }
6281
6282        // Since both signature sets are of size 1, we can compare without HashSets.
6283        if (s1.length == 1) {
6284            return s1[0].equals(s2[0]) ?
6285                    PackageManager.SIGNATURE_MATCH :
6286                    PackageManager.SIGNATURE_NO_MATCH;
6287        }
6288
6289        ArraySet<Signature> set1 = new ArraySet<Signature>();
6290        for (Signature sig : s1) {
6291            set1.add(sig);
6292        }
6293        ArraySet<Signature> set2 = new ArraySet<Signature>();
6294        for (Signature sig : s2) {
6295            set2.add(sig);
6296        }
6297        // Make sure s2 contains all signatures in s1.
6298        if (set1.equals(set2)) {
6299            return PackageManager.SIGNATURE_MATCH;
6300        }
6301        return PackageManager.SIGNATURE_NO_MATCH;
6302    }
6303
6304    /**
6305     * If the database version for this type of package (internal storage or
6306     * external storage) is less than the version where package signatures
6307     * were updated, return true.
6308     */
6309    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6310        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6311        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6312    }
6313
6314    /**
6315     * Used for backward compatibility to make sure any packages with
6316     * certificate chains get upgraded to the new style. {@code existingSigs}
6317     * will be in the old format (since they were stored on disk from before the
6318     * system upgrade) and {@code scannedSigs} will be in the newer format.
6319     */
6320    private int compareSignaturesCompat(PackageSignatures existingSigs,
6321            PackageParser.Package scannedPkg) {
6322        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6323            return PackageManager.SIGNATURE_NO_MATCH;
6324        }
6325
6326        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6327        for (Signature sig : existingSigs.mSignatures) {
6328            existingSet.add(sig);
6329        }
6330        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6331        for (Signature sig : scannedPkg.mSignatures) {
6332            try {
6333                Signature[] chainSignatures = sig.getChainSignatures();
6334                for (Signature chainSig : chainSignatures) {
6335                    scannedCompatSet.add(chainSig);
6336                }
6337            } catch (CertificateEncodingException e) {
6338                scannedCompatSet.add(sig);
6339            }
6340        }
6341        /*
6342         * Make sure the expanded scanned set contains all signatures in the
6343         * existing one.
6344         */
6345        if (scannedCompatSet.equals(existingSet)) {
6346            // Migrate the old signatures to the new scheme.
6347            existingSigs.assignSignatures(scannedPkg.mSignatures);
6348            // The new KeySets will be re-added later in the scanning process.
6349            synchronized (mPackages) {
6350                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6351            }
6352            return PackageManager.SIGNATURE_MATCH;
6353        }
6354        return PackageManager.SIGNATURE_NO_MATCH;
6355    }
6356
6357    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6358        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6359        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6360    }
6361
6362    private int compareSignaturesRecover(PackageSignatures existingSigs,
6363            PackageParser.Package scannedPkg) {
6364        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6365            return PackageManager.SIGNATURE_NO_MATCH;
6366        }
6367
6368        String msg = null;
6369        try {
6370            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6371                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6372                        + scannedPkg.packageName);
6373                return PackageManager.SIGNATURE_MATCH;
6374            }
6375        } catch (CertificateException e) {
6376            msg = e.getMessage();
6377        }
6378
6379        logCriticalInfo(Log.INFO,
6380                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6381        return PackageManager.SIGNATURE_NO_MATCH;
6382    }
6383
6384    @Override
6385    public List<String> getAllPackages() {
6386        final int callingUid = Binder.getCallingUid();
6387        final int callingUserId = UserHandle.getUserId(callingUid);
6388        synchronized (mPackages) {
6389            if (canViewInstantApps(callingUid, callingUserId)) {
6390                return new ArrayList<String>(mPackages.keySet());
6391            }
6392            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6393            final List<String> result = new ArrayList<>();
6394            if (instantAppPkgName != null) {
6395                // caller is an instant application; filter unexposed applications
6396                for (PackageParser.Package pkg : mPackages.values()) {
6397                    if (!pkg.visibleToInstantApps) {
6398                        continue;
6399                    }
6400                    result.add(pkg.packageName);
6401                }
6402            } else {
6403                // caller is a normal application; filter instant applications
6404                for (PackageParser.Package pkg : mPackages.values()) {
6405                    final PackageSetting ps =
6406                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6407                    if (ps != null
6408                            && ps.getInstantApp(callingUserId)
6409                            && !mInstantAppRegistry.isInstantAccessGranted(
6410                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6411                        continue;
6412                    }
6413                    result.add(pkg.packageName);
6414                }
6415            }
6416            return result;
6417        }
6418    }
6419
6420    @Override
6421    public String[] getPackagesForUid(int uid) {
6422        final int callingUid = Binder.getCallingUid();
6423        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6424        final int userId = UserHandle.getUserId(uid);
6425        uid = UserHandle.getAppId(uid);
6426        // reader
6427        synchronized (mPackages) {
6428            Object obj = mSettings.getUserIdLPr(uid);
6429            if (obj instanceof SharedUserSetting) {
6430                if (isCallerInstantApp) {
6431                    return null;
6432                }
6433                final SharedUserSetting sus = (SharedUserSetting) obj;
6434                final int N = sus.packages.size();
6435                String[] res = new String[N];
6436                final Iterator<PackageSetting> it = sus.packages.iterator();
6437                int i = 0;
6438                while (it.hasNext()) {
6439                    PackageSetting ps = it.next();
6440                    if (ps.getInstalled(userId)) {
6441                        res[i++] = ps.name;
6442                    } else {
6443                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6444                    }
6445                }
6446                return res;
6447            } else if (obj instanceof PackageSetting) {
6448                final PackageSetting ps = (PackageSetting) obj;
6449                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6450                    return new String[]{ps.name};
6451                }
6452            }
6453        }
6454        return null;
6455    }
6456
6457    @Override
6458    public String getNameForUid(int uid) {
6459        final int callingUid = Binder.getCallingUid();
6460        if (getInstantAppPackageName(callingUid) != null) {
6461            return null;
6462        }
6463        synchronized (mPackages) {
6464            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6465            if (obj instanceof SharedUserSetting) {
6466                final SharedUserSetting sus = (SharedUserSetting) obj;
6467                return sus.name + ":" + sus.userId;
6468            } else if (obj instanceof PackageSetting) {
6469                final PackageSetting ps = (PackageSetting) obj;
6470                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6471                    return null;
6472                }
6473                return ps.name;
6474            }
6475            return null;
6476        }
6477    }
6478
6479    @Override
6480    public String[] getNamesForUids(int[] uids) {
6481        if (uids == null || uids.length == 0) {
6482            return null;
6483        }
6484        final int callingUid = Binder.getCallingUid();
6485        if (getInstantAppPackageName(callingUid) != null) {
6486            return null;
6487        }
6488        final String[] names = new String[uids.length];
6489        synchronized (mPackages) {
6490            for (int i = uids.length - 1; i >= 0; i--) {
6491                final int uid = uids[i];
6492                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6493                if (obj instanceof SharedUserSetting) {
6494                    final SharedUserSetting sus = (SharedUserSetting) obj;
6495                    names[i] = "shared:" + sus.name;
6496                } else if (obj instanceof PackageSetting) {
6497                    final PackageSetting ps = (PackageSetting) obj;
6498                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6499                        names[i] = null;
6500                    } else {
6501                        names[i] = ps.name;
6502                    }
6503                } else {
6504                    names[i] = null;
6505                }
6506            }
6507        }
6508        return names;
6509    }
6510
6511    @Override
6512    public int getUidForSharedUser(String sharedUserName) {
6513        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6514            return -1;
6515        }
6516        if (sharedUserName == null) {
6517            return -1;
6518        }
6519        // reader
6520        synchronized (mPackages) {
6521            SharedUserSetting suid;
6522            try {
6523                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6524                if (suid != null) {
6525                    return suid.userId;
6526                }
6527            } catch (PackageManagerException ignore) {
6528                // can't happen, but, still need to catch it
6529            }
6530            return -1;
6531        }
6532    }
6533
6534    @Override
6535    public int getFlagsForUid(int uid) {
6536        final int callingUid = Binder.getCallingUid();
6537        if (getInstantAppPackageName(callingUid) != null) {
6538            return 0;
6539        }
6540        synchronized (mPackages) {
6541            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6542            if (obj instanceof SharedUserSetting) {
6543                final SharedUserSetting sus = (SharedUserSetting) obj;
6544                return sus.pkgFlags;
6545            } else if (obj instanceof PackageSetting) {
6546                final PackageSetting ps = (PackageSetting) obj;
6547                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6548                    return 0;
6549                }
6550                return ps.pkgFlags;
6551            }
6552        }
6553        return 0;
6554    }
6555
6556    @Override
6557    public int getPrivateFlagsForUid(int uid) {
6558        final int callingUid = Binder.getCallingUid();
6559        if (getInstantAppPackageName(callingUid) != null) {
6560            return 0;
6561        }
6562        synchronized (mPackages) {
6563            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6564            if (obj instanceof SharedUserSetting) {
6565                final SharedUserSetting sus = (SharedUserSetting) obj;
6566                return sus.pkgPrivateFlags;
6567            } else if (obj instanceof PackageSetting) {
6568                final PackageSetting ps = (PackageSetting) obj;
6569                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6570                    return 0;
6571                }
6572                return ps.pkgPrivateFlags;
6573            }
6574        }
6575        return 0;
6576    }
6577
6578    @Override
6579    public boolean isUidPrivileged(int uid) {
6580        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6581            return false;
6582        }
6583        uid = UserHandle.getAppId(uid);
6584        // reader
6585        synchronized (mPackages) {
6586            Object obj = mSettings.getUserIdLPr(uid);
6587            if (obj instanceof SharedUserSetting) {
6588                final SharedUserSetting sus = (SharedUserSetting) obj;
6589                final Iterator<PackageSetting> it = sus.packages.iterator();
6590                while (it.hasNext()) {
6591                    if (it.next().isPrivileged()) {
6592                        return true;
6593                    }
6594                }
6595            } else if (obj instanceof PackageSetting) {
6596                final PackageSetting ps = (PackageSetting) obj;
6597                return ps.isPrivileged();
6598            }
6599        }
6600        return false;
6601    }
6602
6603    @Override
6604    public String[] getAppOpPermissionPackages(String permissionName) {
6605        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6606            return null;
6607        }
6608        synchronized (mPackages) {
6609            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6610            if (pkgs == null) {
6611                return null;
6612            }
6613            return pkgs.toArray(new String[pkgs.size()]);
6614        }
6615    }
6616
6617    @Override
6618    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6619            int flags, int userId) {
6620        return resolveIntentInternal(
6621                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6622    }
6623
6624    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6625            int flags, int userId, boolean resolveForStart) {
6626        try {
6627            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6628
6629            if (!sUserManager.exists(userId)) return null;
6630            final int callingUid = Binder.getCallingUid();
6631            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6632            enforceCrossUserPermission(callingUid, userId,
6633                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6634
6635            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6636            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6637                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6638            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6639
6640            final ResolveInfo bestChoice =
6641                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6642            return bestChoice;
6643        } finally {
6644            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6645        }
6646    }
6647
6648    @Override
6649    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6650        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6651            throw new SecurityException(
6652                    "findPersistentPreferredActivity can only be run by the system");
6653        }
6654        if (!sUserManager.exists(userId)) {
6655            return null;
6656        }
6657        final int callingUid = Binder.getCallingUid();
6658        intent = updateIntentForResolve(intent);
6659        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6660        final int flags = updateFlagsForResolve(
6661                0, userId, intent, callingUid, false /*includeInstantApps*/);
6662        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6663                userId);
6664        synchronized (mPackages) {
6665            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6666                    userId);
6667        }
6668    }
6669
6670    @Override
6671    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6672            IntentFilter filter, int match, ComponentName activity) {
6673        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6674            return;
6675        }
6676        final int userId = UserHandle.getCallingUserId();
6677        if (DEBUG_PREFERRED) {
6678            Log.v(TAG, "setLastChosenActivity intent=" + intent
6679                + " resolvedType=" + resolvedType
6680                + " flags=" + flags
6681                + " filter=" + filter
6682                + " match=" + match
6683                + " activity=" + activity);
6684            filter.dump(new PrintStreamPrinter(System.out), "    ");
6685        }
6686        intent.setComponent(null);
6687        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6688                userId);
6689        // Find any earlier preferred or last chosen entries and nuke them
6690        findPreferredActivity(intent, resolvedType,
6691                flags, query, 0, false, true, false, userId);
6692        // Add the new activity as the last chosen for this filter
6693        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6694                "Setting last chosen");
6695    }
6696
6697    @Override
6698    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6699        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6700            return null;
6701        }
6702        final int userId = UserHandle.getCallingUserId();
6703        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6704        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6705                userId);
6706        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6707                false, false, false, userId);
6708    }
6709
6710    /**
6711     * Returns whether or not instant apps have been disabled remotely.
6712     */
6713    private boolean isEphemeralDisabled() {
6714        return mEphemeralAppsDisabled;
6715    }
6716
6717    private boolean isInstantAppAllowed(
6718            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6719            boolean skipPackageCheck) {
6720        if (mInstantAppResolverConnection == null) {
6721            return false;
6722        }
6723        if (mInstantAppInstallerActivity == null) {
6724            return false;
6725        }
6726        if (intent.getComponent() != null) {
6727            return false;
6728        }
6729        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6730            return false;
6731        }
6732        if (!skipPackageCheck && intent.getPackage() != null) {
6733            return false;
6734        }
6735        final boolean isWebUri = hasWebURI(intent);
6736        if (!isWebUri || intent.getData().getHost() == null) {
6737            return false;
6738        }
6739        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6740        // Or if there's already an ephemeral app installed that handles the action
6741        synchronized (mPackages) {
6742            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6743            for (int n = 0; n < count; n++) {
6744                final ResolveInfo info = resolvedActivities.get(n);
6745                final String packageName = info.activityInfo.packageName;
6746                final PackageSetting ps = mSettings.mPackages.get(packageName);
6747                if (ps != null) {
6748                    // only check domain verification status if the app is not a browser
6749                    if (!info.handleAllWebDataURI) {
6750                        // Try to get the status from User settings first
6751                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6752                        final int status = (int) (packedStatus >> 32);
6753                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6754                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6755                            if (DEBUG_EPHEMERAL) {
6756                                Slog.v(TAG, "DENY instant app;"
6757                                    + " pkg: " + packageName + ", status: " + status);
6758                            }
6759                            return false;
6760                        }
6761                    }
6762                    if (ps.getInstantApp(userId)) {
6763                        if (DEBUG_EPHEMERAL) {
6764                            Slog.v(TAG, "DENY instant app installed;"
6765                                    + " pkg: " + packageName);
6766                        }
6767                        return false;
6768                    }
6769                }
6770            }
6771        }
6772        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6773        return true;
6774    }
6775
6776    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6777            Intent origIntent, String resolvedType, String callingPackage,
6778            Bundle verificationBundle, int userId) {
6779        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6780                new InstantAppRequest(responseObj, origIntent, resolvedType,
6781                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6782        mHandler.sendMessage(msg);
6783    }
6784
6785    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6786            int flags, List<ResolveInfo> query, int userId) {
6787        if (query != null) {
6788            final int N = query.size();
6789            if (N == 1) {
6790                return query.get(0);
6791            } else if (N > 1) {
6792                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6793                // If there is more than one activity with the same priority,
6794                // then let the user decide between them.
6795                ResolveInfo r0 = query.get(0);
6796                ResolveInfo r1 = query.get(1);
6797                if (DEBUG_INTENT_MATCHING || debug) {
6798                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6799                            + r1.activityInfo.name + "=" + r1.priority);
6800                }
6801                // If the first activity has a higher priority, or a different
6802                // default, then it is always desirable to pick it.
6803                if (r0.priority != r1.priority
6804                        || r0.preferredOrder != r1.preferredOrder
6805                        || r0.isDefault != r1.isDefault) {
6806                    return query.get(0);
6807                }
6808                // If we have saved a preference for a preferred activity for
6809                // this Intent, use that.
6810                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6811                        flags, query, r0.priority, true, false, debug, userId);
6812                if (ri != null) {
6813                    return ri;
6814                }
6815                // If we have an ephemeral app, use it
6816                for (int i = 0; i < N; i++) {
6817                    ri = query.get(i);
6818                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6819                        final String packageName = ri.activityInfo.packageName;
6820                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6821                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6822                        final int status = (int)(packedStatus >> 32);
6823                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6824                            return ri;
6825                        }
6826                    }
6827                }
6828                ri = new ResolveInfo(mResolveInfo);
6829                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6830                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6831                // If all of the options come from the same package, show the application's
6832                // label and icon instead of the generic resolver's.
6833                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6834                // and then throw away the ResolveInfo itself, meaning that the caller loses
6835                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6836                // a fallback for this case; we only set the target package's resources on
6837                // the ResolveInfo, not the ActivityInfo.
6838                final String intentPackage = intent.getPackage();
6839                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6840                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6841                    ri.resolvePackageName = intentPackage;
6842                    if (userNeedsBadging(userId)) {
6843                        ri.noResourceId = true;
6844                    } else {
6845                        ri.icon = appi.icon;
6846                    }
6847                    ri.iconResourceId = appi.icon;
6848                    ri.labelRes = appi.labelRes;
6849                }
6850                ri.activityInfo.applicationInfo = new ApplicationInfo(
6851                        ri.activityInfo.applicationInfo);
6852                if (userId != 0) {
6853                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6854                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6855                }
6856                // Make sure that the resolver is displayable in car mode
6857                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6858                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6859                return ri;
6860            }
6861        }
6862        return null;
6863    }
6864
6865    /**
6866     * Return true if the given list is not empty and all of its contents have
6867     * an activityInfo with the given package name.
6868     */
6869    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6870        if (ArrayUtils.isEmpty(list)) {
6871            return false;
6872        }
6873        for (int i = 0, N = list.size(); i < N; i++) {
6874            final ResolveInfo ri = list.get(i);
6875            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6876            if (ai == null || !packageName.equals(ai.packageName)) {
6877                return false;
6878            }
6879        }
6880        return true;
6881    }
6882
6883    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6884            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6885        final int N = query.size();
6886        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6887                .get(userId);
6888        // Get the list of persistent preferred activities that handle the intent
6889        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6890        List<PersistentPreferredActivity> pprefs = ppir != null
6891                ? ppir.queryIntent(intent, resolvedType,
6892                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6893                        userId)
6894                : null;
6895        if (pprefs != null && pprefs.size() > 0) {
6896            final int M = pprefs.size();
6897            for (int i=0; i<M; i++) {
6898                final PersistentPreferredActivity ppa = pprefs.get(i);
6899                if (DEBUG_PREFERRED || debug) {
6900                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6901                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6902                            + "\n  component=" + ppa.mComponent);
6903                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6904                }
6905                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6906                        flags | MATCH_DISABLED_COMPONENTS, userId);
6907                if (DEBUG_PREFERRED || debug) {
6908                    Slog.v(TAG, "Found persistent preferred activity:");
6909                    if (ai != null) {
6910                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6911                    } else {
6912                        Slog.v(TAG, "  null");
6913                    }
6914                }
6915                if (ai == null) {
6916                    // This previously registered persistent preferred activity
6917                    // component is no longer known. Ignore it and do NOT remove it.
6918                    continue;
6919                }
6920                for (int j=0; j<N; j++) {
6921                    final ResolveInfo ri = query.get(j);
6922                    if (!ri.activityInfo.applicationInfo.packageName
6923                            .equals(ai.applicationInfo.packageName)) {
6924                        continue;
6925                    }
6926                    if (!ri.activityInfo.name.equals(ai.name)) {
6927                        continue;
6928                    }
6929                    //  Found a persistent preference that can handle the intent.
6930                    if (DEBUG_PREFERRED || debug) {
6931                        Slog.v(TAG, "Returning persistent preferred activity: " +
6932                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6933                    }
6934                    return ri;
6935                }
6936            }
6937        }
6938        return null;
6939    }
6940
6941    // TODO: handle preferred activities missing while user has amnesia
6942    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6943            List<ResolveInfo> query, int priority, boolean always,
6944            boolean removeMatches, boolean debug, int userId) {
6945        if (!sUserManager.exists(userId)) return null;
6946        final int callingUid = Binder.getCallingUid();
6947        flags = updateFlagsForResolve(
6948                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6949        intent = updateIntentForResolve(intent);
6950        // writer
6951        synchronized (mPackages) {
6952            // Try to find a matching persistent preferred activity.
6953            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6954                    debug, userId);
6955
6956            // If a persistent preferred activity matched, use it.
6957            if (pri != null) {
6958                return pri;
6959            }
6960
6961            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6962            // Get the list of preferred activities that handle the intent
6963            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6964            List<PreferredActivity> prefs = pir != null
6965                    ? pir.queryIntent(intent, resolvedType,
6966                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6967                            userId)
6968                    : null;
6969            if (prefs != null && prefs.size() > 0) {
6970                boolean changed = false;
6971                try {
6972                    // First figure out how good the original match set is.
6973                    // We will only allow preferred activities that came
6974                    // from the same match quality.
6975                    int match = 0;
6976
6977                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6978
6979                    final int N = query.size();
6980                    for (int j=0; j<N; j++) {
6981                        final ResolveInfo ri = query.get(j);
6982                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6983                                + ": 0x" + Integer.toHexString(match));
6984                        if (ri.match > match) {
6985                            match = ri.match;
6986                        }
6987                    }
6988
6989                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6990                            + Integer.toHexString(match));
6991
6992                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6993                    final int M = prefs.size();
6994                    for (int i=0; i<M; i++) {
6995                        final PreferredActivity pa = prefs.get(i);
6996                        if (DEBUG_PREFERRED || debug) {
6997                            Slog.v(TAG, "Checking PreferredActivity ds="
6998                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6999                                    + "\n  component=" + pa.mPref.mComponent);
7000                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7001                        }
7002                        if (pa.mPref.mMatch != match) {
7003                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
7004                                    + Integer.toHexString(pa.mPref.mMatch));
7005                            continue;
7006                        }
7007                        // If it's not an "always" type preferred activity and that's what we're
7008                        // looking for, skip it.
7009                        if (always && !pa.mPref.mAlways) {
7010                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
7011                            continue;
7012                        }
7013                        final ActivityInfo ai = getActivityInfo(
7014                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
7015                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
7016                                userId);
7017                        if (DEBUG_PREFERRED || debug) {
7018                            Slog.v(TAG, "Found preferred activity:");
7019                            if (ai != null) {
7020                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
7021                            } else {
7022                                Slog.v(TAG, "  null");
7023                            }
7024                        }
7025                        if (ai == null) {
7026                            // This previously registered preferred activity
7027                            // component is no longer known.  Most likely an update
7028                            // to the app was installed and in the new version this
7029                            // component no longer exists.  Clean it up by removing
7030                            // it from the preferred activities list, and skip it.
7031                            Slog.w(TAG, "Removing dangling preferred activity: "
7032                                    + pa.mPref.mComponent);
7033                            pir.removeFilter(pa);
7034                            changed = true;
7035                            continue;
7036                        }
7037                        for (int j=0; j<N; j++) {
7038                            final ResolveInfo ri = query.get(j);
7039                            if (!ri.activityInfo.applicationInfo.packageName
7040                                    .equals(ai.applicationInfo.packageName)) {
7041                                continue;
7042                            }
7043                            if (!ri.activityInfo.name.equals(ai.name)) {
7044                                continue;
7045                            }
7046
7047                            if (removeMatches) {
7048                                pir.removeFilter(pa);
7049                                changed = true;
7050                                if (DEBUG_PREFERRED) {
7051                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7052                                }
7053                                break;
7054                            }
7055
7056                            // Okay we found a previously set preferred or last chosen app.
7057                            // If the result set is different from when this
7058                            // was created, and is not a subset of the preferred set, we need to
7059                            // clear it and re-ask the user their preference, if we're looking for
7060                            // an "always" type entry.
7061                            if (always && !pa.mPref.sameSet(query)) {
7062                                if (pa.mPref.isSuperset(query)) {
7063                                    // some components of the set are no longer present in
7064                                    // the query, but the preferred activity can still be reused
7065                                    if (DEBUG_PREFERRED) {
7066                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
7067                                                + " still valid as only non-preferred components"
7068                                                + " were removed for " + intent + " type "
7069                                                + resolvedType);
7070                                    }
7071                                    // remove obsolete components and re-add the up-to-date filter
7072                                    PreferredActivity freshPa = new PreferredActivity(pa,
7073                                            pa.mPref.mMatch,
7074                                            pa.mPref.discardObsoleteComponents(query),
7075                                            pa.mPref.mComponent,
7076                                            pa.mPref.mAlways);
7077                                    pir.removeFilter(pa);
7078                                    pir.addFilter(freshPa);
7079                                    changed = true;
7080                                } else {
7081                                    Slog.i(TAG,
7082                                            "Result set changed, dropping preferred activity for "
7083                                                    + intent + " type " + resolvedType);
7084                                    if (DEBUG_PREFERRED) {
7085                                        Slog.v(TAG, "Removing preferred activity since set changed "
7086                                                + pa.mPref.mComponent);
7087                                    }
7088                                    pir.removeFilter(pa);
7089                                    // Re-add the filter as a "last chosen" entry (!always)
7090                                    PreferredActivity lastChosen = new PreferredActivity(
7091                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7092                                    pir.addFilter(lastChosen);
7093                                    changed = true;
7094                                    return null;
7095                                }
7096                            }
7097
7098                            // Yay! Either the set matched or we're looking for the last chosen
7099                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7100                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7101                            return ri;
7102                        }
7103                    }
7104                } finally {
7105                    if (changed) {
7106                        if (DEBUG_PREFERRED) {
7107                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7108                        }
7109                        scheduleWritePackageRestrictionsLocked(userId);
7110                    }
7111                }
7112            }
7113        }
7114        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7115        return null;
7116    }
7117
7118    /*
7119     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7120     */
7121    @Override
7122    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7123            int targetUserId) {
7124        mContext.enforceCallingOrSelfPermission(
7125                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7126        List<CrossProfileIntentFilter> matches =
7127                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7128        if (matches != null) {
7129            int size = matches.size();
7130            for (int i = 0; i < size; i++) {
7131                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7132            }
7133        }
7134        if (hasWebURI(intent)) {
7135            // cross-profile app linking works only towards the parent.
7136            final int callingUid = Binder.getCallingUid();
7137            final UserInfo parent = getProfileParent(sourceUserId);
7138            synchronized(mPackages) {
7139                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7140                        false /*includeInstantApps*/);
7141                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7142                        intent, resolvedType, flags, sourceUserId, parent.id);
7143                return xpDomainInfo != null;
7144            }
7145        }
7146        return false;
7147    }
7148
7149    private UserInfo getProfileParent(int userId) {
7150        final long identity = Binder.clearCallingIdentity();
7151        try {
7152            return sUserManager.getProfileParent(userId);
7153        } finally {
7154            Binder.restoreCallingIdentity(identity);
7155        }
7156    }
7157
7158    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7159            String resolvedType, int userId) {
7160        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7161        if (resolver != null) {
7162            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7163        }
7164        return null;
7165    }
7166
7167    @Override
7168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7169            String resolvedType, int flags, int userId) {
7170        try {
7171            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7172
7173            return new ParceledListSlice<>(
7174                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7175        } finally {
7176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7177        }
7178    }
7179
7180    /**
7181     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7182     * instant, returns {@code null}.
7183     */
7184    private String getInstantAppPackageName(int callingUid) {
7185        synchronized (mPackages) {
7186            // If the caller is an isolated app use the owner's uid for the lookup.
7187            if (Process.isIsolated(callingUid)) {
7188                callingUid = mIsolatedOwners.get(callingUid);
7189            }
7190            final int appId = UserHandle.getAppId(callingUid);
7191            final Object obj = mSettings.getUserIdLPr(appId);
7192            if (obj instanceof PackageSetting) {
7193                final PackageSetting ps = (PackageSetting) obj;
7194                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7195                return isInstantApp ? ps.pkg.packageName : null;
7196            }
7197        }
7198        return null;
7199    }
7200
7201    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7202            String resolvedType, int flags, int userId) {
7203        return queryIntentActivitiesInternal(
7204                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7205                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7206    }
7207
7208    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7209            String resolvedType, int flags, int filterCallingUid, int userId,
7210            boolean resolveForStart, boolean allowDynamicSplits) {
7211        if (!sUserManager.exists(userId)) return Collections.emptyList();
7212        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7213        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7214                false /* requireFullPermission */, false /* checkShell */,
7215                "query intent activities");
7216        final String pkgName = intent.getPackage();
7217        ComponentName comp = intent.getComponent();
7218        if (comp == null) {
7219            if (intent.getSelector() != null) {
7220                intent = intent.getSelector();
7221                comp = intent.getComponent();
7222            }
7223        }
7224
7225        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7226                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7227        if (comp != null) {
7228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7230            if (ai != null) {
7231                // When specifying an explicit component, we prevent the activity from being
7232                // used when either 1) the calling package is normal and the activity is within
7233                // an ephemeral application or 2) the calling package is ephemeral and the
7234                // activity is not visible to ephemeral applications.
7235                final boolean matchInstantApp =
7236                        (flags & PackageManager.MATCH_INSTANT) != 0;
7237                final boolean matchVisibleToInstantAppOnly =
7238                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7239                final boolean matchExplicitlyVisibleOnly =
7240                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7241                final boolean isCallerInstantApp =
7242                        instantAppPkgName != null;
7243                final boolean isTargetSameInstantApp =
7244                        comp.getPackageName().equals(instantAppPkgName);
7245                final boolean isTargetInstantApp =
7246                        (ai.applicationInfo.privateFlags
7247                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7248                final boolean isTargetVisibleToInstantApp =
7249                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7250                final boolean isTargetExplicitlyVisibleToInstantApp =
7251                        isTargetVisibleToInstantApp
7252                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7253                final boolean isTargetHiddenFromInstantApp =
7254                        !isTargetVisibleToInstantApp
7255                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7256                final boolean blockResolution =
7257                        !isTargetSameInstantApp
7258                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7259                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7260                                        && isTargetHiddenFromInstantApp));
7261                if (!blockResolution) {
7262                    final ResolveInfo ri = new ResolveInfo();
7263                    ri.activityInfo = ai;
7264                    list.add(ri);
7265                }
7266            }
7267            return applyPostResolutionFilter(
7268                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7269        }
7270
7271        // reader
7272        boolean sortResult = false;
7273        boolean addEphemeral = false;
7274        List<ResolveInfo> result;
7275        final boolean ephemeralDisabled = isEphemeralDisabled();
7276        synchronized (mPackages) {
7277            if (pkgName == null) {
7278                List<CrossProfileIntentFilter> matchingFilters =
7279                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7280                // Check for results that need to skip the current profile.
7281                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7282                        resolvedType, flags, userId);
7283                if (xpResolveInfo != null) {
7284                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7285                    xpResult.add(xpResolveInfo);
7286                    return applyPostResolutionFilter(
7287                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7288                            allowDynamicSplits, filterCallingUid, userId);
7289                }
7290
7291                // Check for results in the current profile.
7292                result = filterIfNotSystemUser(mActivities.queryIntent(
7293                        intent, resolvedType, flags, userId), userId);
7294                addEphemeral = !ephemeralDisabled
7295                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7296                // Check for cross profile results.
7297                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7298                xpResolveInfo = queryCrossProfileIntents(
7299                        matchingFilters, intent, resolvedType, flags, userId,
7300                        hasNonNegativePriorityResult);
7301                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7302                    boolean isVisibleToUser = filterIfNotSystemUser(
7303                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7304                    if (isVisibleToUser) {
7305                        result.add(xpResolveInfo);
7306                        sortResult = true;
7307                    }
7308                }
7309                if (hasWebURI(intent)) {
7310                    CrossProfileDomainInfo xpDomainInfo = null;
7311                    final UserInfo parent = getProfileParent(userId);
7312                    if (parent != null) {
7313                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7314                                flags, userId, parent.id);
7315                    }
7316                    if (xpDomainInfo != null) {
7317                        if (xpResolveInfo != null) {
7318                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7319                            // in the result.
7320                            result.remove(xpResolveInfo);
7321                        }
7322                        if (result.size() == 0 && !addEphemeral) {
7323                            // No result in current profile, but found candidate in parent user.
7324                            // And we are not going to add emphemeral app, so we can return the
7325                            // result straight away.
7326                            result.add(xpDomainInfo.resolveInfo);
7327                            return applyPostResolutionFilter(result, instantAppPkgName,
7328                                    allowDynamicSplits, filterCallingUid, userId);
7329                        }
7330                    } else if (result.size() <= 1 && !addEphemeral) {
7331                        // No result in parent user and <= 1 result in current profile, and we
7332                        // are not going to add emphemeral app, so we can return the result without
7333                        // further processing.
7334                        return applyPostResolutionFilter(result, instantAppPkgName,
7335                                allowDynamicSplits, filterCallingUid, userId);
7336                    }
7337                    // We have more than one candidate (combining results from current and parent
7338                    // profile), so we need filtering and sorting.
7339                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7340                            intent, flags, result, xpDomainInfo, userId);
7341                    sortResult = true;
7342                }
7343            } else {
7344                final PackageParser.Package pkg = mPackages.get(pkgName);
7345                result = null;
7346                if (pkg != null) {
7347                    result = filterIfNotSystemUser(
7348                            mActivities.queryIntentForPackage(
7349                                    intent, resolvedType, flags, pkg.activities, userId),
7350                            userId);
7351                }
7352                if (result == null || result.size() == 0) {
7353                    // the caller wants to resolve for a particular package; however, there
7354                    // were no installed results, so, try to find an ephemeral result
7355                    addEphemeral = !ephemeralDisabled
7356                            && isInstantAppAllowed(
7357                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7358                    if (result == null) {
7359                        result = new ArrayList<>();
7360                    }
7361                }
7362            }
7363        }
7364        if (addEphemeral) {
7365            result = maybeAddInstantAppInstaller(
7366                    result, intent, resolvedType, flags, userId, resolveForStart);
7367        }
7368        if (sortResult) {
7369            Collections.sort(result, mResolvePrioritySorter);
7370        }
7371        return applyPostResolutionFilter(
7372                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7373    }
7374
7375    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7376            String resolvedType, int flags, int userId, boolean resolveForStart) {
7377        // first, check to see if we've got an instant app already installed
7378        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7379        ResolveInfo localInstantApp = null;
7380        boolean blockResolution = false;
7381        if (!alreadyResolvedLocally) {
7382            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7383                    flags
7384                        | PackageManager.GET_RESOLVED_FILTER
7385                        | PackageManager.MATCH_INSTANT
7386                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7387                    userId);
7388            for (int i = instantApps.size() - 1; i >= 0; --i) {
7389                final ResolveInfo info = instantApps.get(i);
7390                final String packageName = info.activityInfo.packageName;
7391                final PackageSetting ps = mSettings.mPackages.get(packageName);
7392                if (ps.getInstantApp(userId)) {
7393                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7394                    final int status = (int)(packedStatus >> 32);
7395                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7396                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7397                        // there's a local instant application installed, but, the user has
7398                        // chosen to never use it; skip resolution and don't acknowledge
7399                        // an instant application is even available
7400                        if (DEBUG_EPHEMERAL) {
7401                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7402                        }
7403                        blockResolution = true;
7404                        break;
7405                    } else {
7406                        // we have a locally installed instant application; skip resolution
7407                        // but acknowledge there's an instant application available
7408                        if (DEBUG_EPHEMERAL) {
7409                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7410                        }
7411                        localInstantApp = info;
7412                        break;
7413                    }
7414                }
7415            }
7416        }
7417        // no app installed, let's see if one's available
7418        AuxiliaryResolveInfo auxiliaryResponse = null;
7419        if (!blockResolution) {
7420            if (localInstantApp == null) {
7421                // we don't have an instant app locally, resolve externally
7422                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7423                final InstantAppRequest requestObject = new InstantAppRequest(
7424                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7425                        null /*callingPackage*/, userId, null /*verificationBundle*/,
7426                        resolveForStart);
7427                auxiliaryResponse =
7428                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7429                                mContext, mInstantAppResolverConnection, requestObject);
7430                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7431            } else {
7432                // we have an instant application locally, but, we can't admit that since
7433                // callers shouldn't be able to determine prior browsing. create a dummy
7434                // auxiliary response so the downstream code behaves as if there's an
7435                // instant application available externally. when it comes time to start
7436                // the instant application, we'll do the right thing.
7437                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7438                auxiliaryResponse = new AuxiliaryResolveInfo(
7439                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7440                        ai.versionCode, null /*failureIntent*/);
7441            }
7442        }
7443        if (auxiliaryResponse != null) {
7444            if (DEBUG_EPHEMERAL) {
7445                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7446            }
7447            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7448            final PackageSetting ps =
7449                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7450            if (ps != null) {
7451                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7452                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7453                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7454                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7455                // make sure this resolver is the default
7456                ephemeralInstaller.isDefault = true;
7457                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7458                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7459                // add a non-generic filter
7460                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7461                ephemeralInstaller.filter.addDataPath(
7462                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7463                ephemeralInstaller.isInstantAppAvailable = true;
7464                result.add(ephemeralInstaller);
7465            }
7466        }
7467        return result;
7468    }
7469
7470    private static class CrossProfileDomainInfo {
7471        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7472        ResolveInfo resolveInfo;
7473        /* Best domain verification status of the activities found in the other profile */
7474        int bestDomainVerificationStatus;
7475    }
7476
7477    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7478            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7479        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7480                sourceUserId)) {
7481            return null;
7482        }
7483        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7484                resolvedType, flags, parentUserId);
7485
7486        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7487            return null;
7488        }
7489        CrossProfileDomainInfo result = null;
7490        int size = resultTargetUser.size();
7491        for (int i = 0; i < size; i++) {
7492            ResolveInfo riTargetUser = resultTargetUser.get(i);
7493            // Intent filter verification is only for filters that specify a host. So don't return
7494            // those that handle all web uris.
7495            if (riTargetUser.handleAllWebDataURI) {
7496                continue;
7497            }
7498            String packageName = riTargetUser.activityInfo.packageName;
7499            PackageSetting ps = mSettings.mPackages.get(packageName);
7500            if (ps == null) {
7501                continue;
7502            }
7503            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7504            int status = (int)(verificationState >> 32);
7505            if (result == null) {
7506                result = new CrossProfileDomainInfo();
7507                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7508                        sourceUserId, parentUserId);
7509                result.bestDomainVerificationStatus = status;
7510            } else {
7511                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7512                        result.bestDomainVerificationStatus);
7513            }
7514        }
7515        // Don't consider matches with status NEVER across profiles.
7516        if (result != null && result.bestDomainVerificationStatus
7517                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7518            return null;
7519        }
7520        return result;
7521    }
7522
7523    /**
7524     * Verification statuses are ordered from the worse to the best, except for
7525     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7526     */
7527    private int bestDomainVerificationStatus(int status1, int status2) {
7528        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7529            return status2;
7530        }
7531        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7532            return status1;
7533        }
7534        return (int) MathUtils.max(status1, status2);
7535    }
7536
7537    private boolean isUserEnabled(int userId) {
7538        long callingId = Binder.clearCallingIdentity();
7539        try {
7540            UserInfo userInfo = sUserManager.getUserInfo(userId);
7541            return userInfo != null && userInfo.isEnabled();
7542        } finally {
7543            Binder.restoreCallingIdentity(callingId);
7544        }
7545    }
7546
7547    /**
7548     * Filter out activities with systemUserOnly flag set, when current user is not System.
7549     *
7550     * @return filtered list
7551     */
7552    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7553        if (userId == UserHandle.USER_SYSTEM) {
7554            return resolveInfos;
7555        }
7556        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7557            ResolveInfo info = resolveInfos.get(i);
7558            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7559                resolveInfos.remove(i);
7560            }
7561        }
7562        return resolveInfos;
7563    }
7564
7565    /**
7566     * Filters out ephemeral activities.
7567     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7568     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7569     *
7570     * @param resolveInfos The pre-filtered list of resolved activities
7571     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7572     *          is performed.
7573     * @return A filtered list of resolved activities.
7574     */
7575    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7576            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7577        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7578            final ResolveInfo info = resolveInfos.get(i);
7579            // allow activities that are defined in the provided package
7580            if (allowDynamicSplits
7581                    && info.activityInfo.splitName != null
7582                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7583                            info.activityInfo.splitName)) {
7584                // requested activity is defined in a split that hasn't been installed yet.
7585                // add the installer to the resolve list
7586                if (DEBUG_INSTALL) {
7587                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7588                }
7589                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7590                final ComponentName installFailureActivity = findInstallFailureActivity(
7591                        info.activityInfo.packageName,  filterCallingUid, userId);
7592                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7593                        info.activityInfo.packageName, info.activityInfo.splitName,
7594                        installFailureActivity,
7595                        info.activityInfo.applicationInfo.versionCode,
7596                        null /*failureIntent*/);
7597                // make sure this resolver is the default
7598                installerInfo.isDefault = true;
7599                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7600                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7601                // add a non-generic filter
7602                installerInfo.filter = new IntentFilter();
7603                // load resources from the correct package
7604                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7605                resolveInfos.set(i, installerInfo);
7606                continue;
7607            }
7608            // caller is a full app, don't need to apply any other filtering
7609            if (ephemeralPkgName == null) {
7610                continue;
7611            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7612                // caller is same app; don't need to apply any other filtering
7613                continue;
7614            }
7615            // allow activities that have been explicitly exposed to ephemeral apps
7616            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7617            if (!isEphemeralApp
7618                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7619                continue;
7620            }
7621            resolveInfos.remove(i);
7622        }
7623        return resolveInfos;
7624    }
7625
7626    /**
7627     * Returns the activity component that can handle install failures.
7628     * <p>By default, the instant application installer handles failures. However, an
7629     * application may want to handle failures on its own. Applications do this by
7630     * creating an activity with an intent filter that handles the action
7631     * {@link Intent#ACTION_INSTALL_FAILURE}.
7632     */
7633    private @Nullable ComponentName findInstallFailureActivity(
7634            String packageName, int filterCallingUid, int userId) {
7635        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7636        failureActivityIntent.setPackage(packageName);
7637        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7638        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7639                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7640                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7641        final int NR = result.size();
7642        if (NR > 0) {
7643            for (int i = 0; i < NR; i++) {
7644                final ResolveInfo info = result.get(i);
7645                if (info.activityInfo.splitName != null) {
7646                    continue;
7647                }
7648                return new ComponentName(packageName, info.activityInfo.name);
7649            }
7650        }
7651        return null;
7652    }
7653
7654    /**
7655     * @param resolveInfos list of resolve infos in descending priority order
7656     * @return if the list contains a resolve info with non-negative priority
7657     */
7658    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7659        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7660    }
7661
7662    private static boolean hasWebURI(Intent intent) {
7663        if (intent.getData() == null) {
7664            return false;
7665        }
7666        final String scheme = intent.getScheme();
7667        if (TextUtils.isEmpty(scheme)) {
7668            return false;
7669        }
7670        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7671    }
7672
7673    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7674            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7675            int userId) {
7676        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7677
7678        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7679            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7680                    candidates.size());
7681        }
7682
7683        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7684        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7685        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7686        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7687        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7688        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7689
7690        synchronized (mPackages) {
7691            final int count = candidates.size();
7692            // First, try to use linked apps. Partition the candidates into four lists:
7693            // one for the final results, one for the "do not use ever", one for "undefined status"
7694            // and finally one for "browser app type".
7695            for (int n=0; n<count; n++) {
7696                ResolveInfo info = candidates.get(n);
7697                String packageName = info.activityInfo.packageName;
7698                PackageSetting ps = mSettings.mPackages.get(packageName);
7699                if (ps != null) {
7700                    // Add to the special match all list (Browser use case)
7701                    if (info.handleAllWebDataURI) {
7702                        matchAllList.add(info);
7703                        continue;
7704                    }
7705                    // Try to get the status from User settings first
7706                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7707                    int status = (int)(packedStatus >> 32);
7708                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7709                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7710                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7711                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7712                                    + " : linkgen=" + linkGeneration);
7713                        }
7714                        // Use link-enabled generation as preferredOrder, i.e.
7715                        // prefer newly-enabled over earlier-enabled.
7716                        info.preferredOrder = linkGeneration;
7717                        alwaysList.add(info);
7718                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7719                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7720                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7721                        }
7722                        neverList.add(info);
7723                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7724                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7725                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7726                        }
7727                        alwaysAskList.add(info);
7728                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7729                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7730                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7731                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7732                        }
7733                        undefinedList.add(info);
7734                    }
7735                }
7736            }
7737
7738            // We'll want to include browser possibilities in a few cases
7739            boolean includeBrowser = false;
7740
7741            // First try to add the "always" resolution(s) for the current user, if any
7742            if (alwaysList.size() > 0) {
7743                result.addAll(alwaysList);
7744            } else {
7745                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7746                result.addAll(undefinedList);
7747                // Maybe add one for the other profile.
7748                if (xpDomainInfo != null && (
7749                        xpDomainInfo.bestDomainVerificationStatus
7750                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7751                    result.add(xpDomainInfo.resolveInfo);
7752                }
7753                includeBrowser = true;
7754            }
7755
7756            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7757            // If there were 'always' entries their preferred order has been set, so we also
7758            // back that off to make the alternatives equivalent
7759            if (alwaysAskList.size() > 0) {
7760                for (ResolveInfo i : result) {
7761                    i.preferredOrder = 0;
7762                }
7763                result.addAll(alwaysAskList);
7764                includeBrowser = true;
7765            }
7766
7767            if (includeBrowser) {
7768                // Also add browsers (all of them or only the default one)
7769                if (DEBUG_DOMAIN_VERIFICATION) {
7770                    Slog.v(TAG, "   ...including browsers in candidate set");
7771                }
7772                if ((matchFlags & MATCH_ALL) != 0) {
7773                    result.addAll(matchAllList);
7774                } else {
7775                    // Browser/generic handling case.  If there's a default browser, go straight
7776                    // to that (but only if there is no other higher-priority match).
7777                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7778                    int maxMatchPrio = 0;
7779                    ResolveInfo defaultBrowserMatch = null;
7780                    final int numCandidates = matchAllList.size();
7781                    for (int n = 0; n < numCandidates; n++) {
7782                        ResolveInfo info = matchAllList.get(n);
7783                        // track the highest overall match priority...
7784                        if (info.priority > maxMatchPrio) {
7785                            maxMatchPrio = info.priority;
7786                        }
7787                        // ...and the highest-priority default browser match
7788                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7789                            if (defaultBrowserMatch == null
7790                                    || (defaultBrowserMatch.priority < info.priority)) {
7791                                if (debug) {
7792                                    Slog.v(TAG, "Considering default browser match " + info);
7793                                }
7794                                defaultBrowserMatch = info;
7795                            }
7796                        }
7797                    }
7798                    if (defaultBrowserMatch != null
7799                            && defaultBrowserMatch.priority >= maxMatchPrio
7800                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7801                    {
7802                        if (debug) {
7803                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7804                        }
7805                        result.add(defaultBrowserMatch);
7806                    } else {
7807                        result.addAll(matchAllList);
7808                    }
7809                }
7810
7811                // If there is nothing selected, add all candidates and remove the ones that the user
7812                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7813                if (result.size() == 0) {
7814                    result.addAll(candidates);
7815                    result.removeAll(neverList);
7816                }
7817            }
7818        }
7819        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7820            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7821                    result.size());
7822            for (ResolveInfo info : result) {
7823                Slog.v(TAG, "  + " + info.activityInfo);
7824            }
7825        }
7826        return result;
7827    }
7828
7829    // Returns a packed value as a long:
7830    //
7831    // high 'int'-sized word: link status: undefined/ask/never/always.
7832    // low 'int'-sized word: relative priority among 'always' results.
7833    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7834        long result = ps.getDomainVerificationStatusForUser(userId);
7835        // if none available, get the master status
7836        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7837            if (ps.getIntentFilterVerificationInfo() != null) {
7838                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7839            }
7840        }
7841        return result;
7842    }
7843
7844    private ResolveInfo querySkipCurrentProfileIntents(
7845            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7846            int flags, int sourceUserId) {
7847        if (matchingFilters != null) {
7848            int size = matchingFilters.size();
7849            for (int i = 0; i < size; i ++) {
7850                CrossProfileIntentFilter filter = matchingFilters.get(i);
7851                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7852                    // Checking if there are activities in the target user that can handle the
7853                    // intent.
7854                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7855                            resolvedType, flags, sourceUserId);
7856                    if (resolveInfo != null) {
7857                        return resolveInfo;
7858                    }
7859                }
7860            }
7861        }
7862        return null;
7863    }
7864
7865    // Return matching ResolveInfo in target user if any.
7866    private ResolveInfo queryCrossProfileIntents(
7867            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7868            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7869        if (matchingFilters != null) {
7870            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7871            // match the same intent. For performance reasons, it is better not to
7872            // run queryIntent twice for the same userId
7873            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7874            int size = matchingFilters.size();
7875            for (int i = 0; i < size; i++) {
7876                CrossProfileIntentFilter filter = matchingFilters.get(i);
7877                int targetUserId = filter.getTargetUserId();
7878                boolean skipCurrentProfile =
7879                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7880                boolean skipCurrentProfileIfNoMatchFound =
7881                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7882                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7883                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7884                    // Checking if there are activities in the target user that can handle the
7885                    // intent.
7886                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7887                            resolvedType, flags, sourceUserId);
7888                    if (resolveInfo != null) return resolveInfo;
7889                    alreadyTriedUserIds.put(targetUserId, true);
7890                }
7891            }
7892        }
7893        return null;
7894    }
7895
7896    /**
7897     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7898     * will forward the intent to the filter's target user.
7899     * Otherwise, returns null.
7900     */
7901    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7902            String resolvedType, int flags, int sourceUserId) {
7903        int targetUserId = filter.getTargetUserId();
7904        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7905                resolvedType, flags, targetUserId);
7906        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7907            // If all the matches in the target profile are suspended, return null.
7908            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7909                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7910                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7911                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7912                            targetUserId);
7913                }
7914            }
7915        }
7916        return null;
7917    }
7918
7919    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7920            int sourceUserId, int targetUserId) {
7921        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7922        long ident = Binder.clearCallingIdentity();
7923        boolean targetIsProfile;
7924        try {
7925            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7926        } finally {
7927            Binder.restoreCallingIdentity(ident);
7928        }
7929        String className;
7930        if (targetIsProfile) {
7931            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7932        } else {
7933            className = FORWARD_INTENT_TO_PARENT;
7934        }
7935        ComponentName forwardingActivityComponentName = new ComponentName(
7936                mAndroidApplication.packageName, className);
7937        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7938                sourceUserId);
7939        if (!targetIsProfile) {
7940            forwardingActivityInfo.showUserIcon = targetUserId;
7941            forwardingResolveInfo.noResourceId = true;
7942        }
7943        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7944        forwardingResolveInfo.priority = 0;
7945        forwardingResolveInfo.preferredOrder = 0;
7946        forwardingResolveInfo.match = 0;
7947        forwardingResolveInfo.isDefault = true;
7948        forwardingResolveInfo.filter = filter;
7949        forwardingResolveInfo.targetUserId = targetUserId;
7950        return forwardingResolveInfo;
7951    }
7952
7953    @Override
7954    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7955            Intent[] specifics, String[] specificTypes, Intent intent,
7956            String resolvedType, int flags, int userId) {
7957        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7958                specificTypes, intent, resolvedType, flags, userId));
7959    }
7960
7961    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7962            Intent[] specifics, String[] specificTypes, Intent intent,
7963            String resolvedType, int flags, int userId) {
7964        if (!sUserManager.exists(userId)) return Collections.emptyList();
7965        final int callingUid = Binder.getCallingUid();
7966        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7967                false /*includeInstantApps*/);
7968        enforceCrossUserPermission(callingUid, userId,
7969                false /*requireFullPermission*/, false /*checkShell*/,
7970                "query intent activity options");
7971        final String resultsAction = intent.getAction();
7972
7973        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7974                | PackageManager.GET_RESOLVED_FILTER, userId);
7975
7976        if (DEBUG_INTENT_MATCHING) {
7977            Log.v(TAG, "Query " + intent + ": " + results);
7978        }
7979
7980        int specificsPos = 0;
7981        int N;
7982
7983        // todo: note that the algorithm used here is O(N^2).  This
7984        // isn't a problem in our current environment, but if we start running
7985        // into situations where we have more than 5 or 10 matches then this
7986        // should probably be changed to something smarter...
7987
7988        // First we go through and resolve each of the specific items
7989        // that were supplied, taking care of removing any corresponding
7990        // duplicate items in the generic resolve list.
7991        if (specifics != null) {
7992            for (int i=0; i<specifics.length; i++) {
7993                final Intent sintent = specifics[i];
7994                if (sintent == null) {
7995                    continue;
7996                }
7997
7998                if (DEBUG_INTENT_MATCHING) {
7999                    Log.v(TAG, "Specific #" + i + ": " + sintent);
8000                }
8001
8002                String action = sintent.getAction();
8003                if (resultsAction != null && resultsAction.equals(action)) {
8004                    // If this action was explicitly requested, then don't
8005                    // remove things that have it.
8006                    action = null;
8007                }
8008
8009                ResolveInfo ri = null;
8010                ActivityInfo ai = null;
8011
8012                ComponentName comp = sintent.getComponent();
8013                if (comp == null) {
8014                    ri = resolveIntent(
8015                        sintent,
8016                        specificTypes != null ? specificTypes[i] : null,
8017                            flags, userId);
8018                    if (ri == null) {
8019                        continue;
8020                    }
8021                    if (ri == mResolveInfo) {
8022                        // ACK!  Must do something better with this.
8023                    }
8024                    ai = ri.activityInfo;
8025                    comp = new ComponentName(ai.applicationInfo.packageName,
8026                            ai.name);
8027                } else {
8028                    ai = getActivityInfo(comp, flags, userId);
8029                    if (ai == null) {
8030                        continue;
8031                    }
8032                }
8033
8034                // Look for any generic query activities that are duplicates
8035                // of this specific one, and remove them from the results.
8036                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8037                N = results.size();
8038                int j;
8039                for (j=specificsPos; j<N; j++) {
8040                    ResolveInfo sri = results.get(j);
8041                    if ((sri.activityInfo.name.equals(comp.getClassName())
8042                            && sri.activityInfo.applicationInfo.packageName.equals(
8043                                    comp.getPackageName()))
8044                        || (action != null && sri.filter.matchAction(action))) {
8045                        results.remove(j);
8046                        if (DEBUG_INTENT_MATCHING) Log.v(
8047                            TAG, "Removing duplicate item from " + j
8048                            + " due to specific " + specificsPos);
8049                        if (ri == null) {
8050                            ri = sri;
8051                        }
8052                        j--;
8053                        N--;
8054                    }
8055                }
8056
8057                // Add this specific item to its proper place.
8058                if (ri == null) {
8059                    ri = new ResolveInfo();
8060                    ri.activityInfo = ai;
8061                }
8062                results.add(specificsPos, ri);
8063                ri.specificIndex = i;
8064                specificsPos++;
8065            }
8066        }
8067
8068        // Now we go through the remaining generic results and remove any
8069        // duplicate actions that are found here.
8070        N = results.size();
8071        for (int i=specificsPos; i<N-1; i++) {
8072            final ResolveInfo rii = results.get(i);
8073            if (rii.filter == null) {
8074                continue;
8075            }
8076
8077            // Iterate over all of the actions of this result's intent
8078            // filter...  typically this should be just one.
8079            final Iterator<String> it = rii.filter.actionsIterator();
8080            if (it == null) {
8081                continue;
8082            }
8083            while (it.hasNext()) {
8084                final String action = it.next();
8085                if (resultsAction != null && resultsAction.equals(action)) {
8086                    // If this action was explicitly requested, then don't
8087                    // remove things that have it.
8088                    continue;
8089                }
8090                for (int j=i+1; j<N; j++) {
8091                    final ResolveInfo rij = results.get(j);
8092                    if (rij.filter != null && rij.filter.hasAction(action)) {
8093                        results.remove(j);
8094                        if (DEBUG_INTENT_MATCHING) Log.v(
8095                            TAG, "Removing duplicate item from " + j
8096                            + " due to action " + action + " at " + i);
8097                        j--;
8098                        N--;
8099                    }
8100                }
8101            }
8102
8103            // If the caller didn't request filter information, drop it now
8104            // so we don't have to marshall/unmarshall it.
8105            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8106                rii.filter = null;
8107            }
8108        }
8109
8110        // Filter out the caller activity if so requested.
8111        if (caller != null) {
8112            N = results.size();
8113            for (int i=0; i<N; i++) {
8114                ActivityInfo ainfo = results.get(i).activityInfo;
8115                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8116                        && caller.getClassName().equals(ainfo.name)) {
8117                    results.remove(i);
8118                    break;
8119                }
8120            }
8121        }
8122
8123        // If the caller didn't request filter information,
8124        // drop them now so we don't have to
8125        // marshall/unmarshall it.
8126        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8127            N = results.size();
8128            for (int i=0; i<N; i++) {
8129                results.get(i).filter = null;
8130            }
8131        }
8132
8133        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8134        return results;
8135    }
8136
8137    @Override
8138    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8139            String resolvedType, int flags, int userId) {
8140        return new ParceledListSlice<>(
8141                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8142                        false /*allowDynamicSplits*/));
8143    }
8144
8145    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8146            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8147        if (!sUserManager.exists(userId)) return Collections.emptyList();
8148        final int callingUid = Binder.getCallingUid();
8149        enforceCrossUserPermission(callingUid, userId,
8150                false /*requireFullPermission*/, false /*checkShell*/,
8151                "query intent receivers");
8152        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8153        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8154                false /*includeInstantApps*/);
8155        ComponentName comp = intent.getComponent();
8156        if (comp == null) {
8157            if (intent.getSelector() != null) {
8158                intent = intent.getSelector();
8159                comp = intent.getComponent();
8160            }
8161        }
8162        if (comp != null) {
8163            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8164            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8165            if (ai != null) {
8166                // When specifying an explicit component, we prevent the activity from being
8167                // used when either 1) the calling package is normal and the activity is within
8168                // an instant application or 2) the calling package is ephemeral and the
8169                // activity is not visible to instant applications.
8170                final boolean matchInstantApp =
8171                        (flags & PackageManager.MATCH_INSTANT) != 0;
8172                final boolean matchVisibleToInstantAppOnly =
8173                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8174                final boolean matchExplicitlyVisibleOnly =
8175                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8176                final boolean isCallerInstantApp =
8177                        instantAppPkgName != null;
8178                final boolean isTargetSameInstantApp =
8179                        comp.getPackageName().equals(instantAppPkgName);
8180                final boolean isTargetInstantApp =
8181                        (ai.applicationInfo.privateFlags
8182                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8183                final boolean isTargetVisibleToInstantApp =
8184                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8185                final boolean isTargetExplicitlyVisibleToInstantApp =
8186                        isTargetVisibleToInstantApp
8187                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8188                final boolean isTargetHiddenFromInstantApp =
8189                        !isTargetVisibleToInstantApp
8190                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8191                final boolean blockResolution =
8192                        !isTargetSameInstantApp
8193                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8194                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8195                                        && isTargetHiddenFromInstantApp));
8196                if (!blockResolution) {
8197                    ResolveInfo ri = new ResolveInfo();
8198                    ri.activityInfo = ai;
8199                    list.add(ri);
8200                }
8201            }
8202            return applyPostResolutionFilter(
8203                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8204        }
8205
8206        // reader
8207        synchronized (mPackages) {
8208            String pkgName = intent.getPackage();
8209            if (pkgName == null) {
8210                final List<ResolveInfo> result =
8211                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8212                return applyPostResolutionFilter(
8213                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8214            }
8215            final PackageParser.Package pkg = mPackages.get(pkgName);
8216            if (pkg != null) {
8217                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8218                        intent, resolvedType, flags, pkg.receivers, userId);
8219                return applyPostResolutionFilter(
8220                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8221            }
8222            return Collections.emptyList();
8223        }
8224    }
8225
8226    @Override
8227    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8228        final int callingUid = Binder.getCallingUid();
8229        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8230    }
8231
8232    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8233            int userId, int callingUid) {
8234        if (!sUserManager.exists(userId)) return null;
8235        flags = updateFlagsForResolve(
8236                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8237        List<ResolveInfo> query = queryIntentServicesInternal(
8238                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8239        if (query != null) {
8240            if (query.size() >= 1) {
8241                // If there is more than one service with the same priority,
8242                // just arbitrarily pick the first one.
8243                return query.get(0);
8244            }
8245        }
8246        return null;
8247    }
8248
8249    @Override
8250    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8251            String resolvedType, int flags, int userId) {
8252        final int callingUid = Binder.getCallingUid();
8253        return new ParceledListSlice<>(queryIntentServicesInternal(
8254                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8255    }
8256
8257    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8258            String resolvedType, int flags, int userId, int callingUid,
8259            boolean includeInstantApps) {
8260        if (!sUserManager.exists(userId)) return Collections.emptyList();
8261        enforceCrossUserPermission(callingUid, userId,
8262                false /*requireFullPermission*/, false /*checkShell*/,
8263                "query intent receivers");
8264        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8265        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8266        ComponentName comp = intent.getComponent();
8267        if (comp == null) {
8268            if (intent.getSelector() != null) {
8269                intent = intent.getSelector();
8270                comp = intent.getComponent();
8271            }
8272        }
8273        if (comp != null) {
8274            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8275            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8276            if (si != null) {
8277                // When specifying an explicit component, we prevent the service from being
8278                // used when either 1) the service is in an instant application and the
8279                // caller is not the same instant application or 2) the calling package is
8280                // ephemeral and the activity is not visible to ephemeral applications.
8281                final boolean matchInstantApp =
8282                        (flags & PackageManager.MATCH_INSTANT) != 0;
8283                final boolean matchVisibleToInstantAppOnly =
8284                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8285                final boolean isCallerInstantApp =
8286                        instantAppPkgName != null;
8287                final boolean isTargetSameInstantApp =
8288                        comp.getPackageName().equals(instantAppPkgName);
8289                final boolean isTargetInstantApp =
8290                        (si.applicationInfo.privateFlags
8291                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8292                final boolean isTargetHiddenFromInstantApp =
8293                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8294                final boolean blockResolution =
8295                        !isTargetSameInstantApp
8296                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8297                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8298                                        && isTargetHiddenFromInstantApp));
8299                if (!blockResolution) {
8300                    final ResolveInfo ri = new ResolveInfo();
8301                    ri.serviceInfo = si;
8302                    list.add(ri);
8303                }
8304            }
8305            return list;
8306        }
8307
8308        // reader
8309        synchronized (mPackages) {
8310            String pkgName = intent.getPackage();
8311            if (pkgName == null) {
8312                return applyPostServiceResolutionFilter(
8313                        mServices.queryIntent(intent, resolvedType, flags, userId),
8314                        instantAppPkgName);
8315            }
8316            final PackageParser.Package pkg = mPackages.get(pkgName);
8317            if (pkg != null) {
8318                return applyPostServiceResolutionFilter(
8319                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8320                                userId),
8321                        instantAppPkgName);
8322            }
8323            return Collections.emptyList();
8324        }
8325    }
8326
8327    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8328            String instantAppPkgName) {
8329        if (instantAppPkgName == null) {
8330            return resolveInfos;
8331        }
8332        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8333            final ResolveInfo info = resolveInfos.get(i);
8334            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8335            // allow services that are defined in the provided package
8336            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8337                if (info.serviceInfo.splitName != null
8338                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8339                                info.serviceInfo.splitName)) {
8340                    // requested service is defined in a split that hasn't been installed yet.
8341                    // add the installer to the resolve list
8342                    if (DEBUG_EPHEMERAL) {
8343                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8344                    }
8345                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8346                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8347                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8348                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8349                            null /*failureIntent*/);
8350                    // make sure this resolver is the default
8351                    installerInfo.isDefault = true;
8352                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8353                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8354                    // add a non-generic filter
8355                    installerInfo.filter = new IntentFilter();
8356                    // load resources from the correct package
8357                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8358                    resolveInfos.set(i, installerInfo);
8359                }
8360                continue;
8361            }
8362            // allow services that have been explicitly exposed to ephemeral apps
8363            if (!isEphemeralApp
8364                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8365                continue;
8366            }
8367            resolveInfos.remove(i);
8368        }
8369        return resolveInfos;
8370    }
8371
8372    @Override
8373    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8374            String resolvedType, int flags, int userId) {
8375        return new ParceledListSlice<>(
8376                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8377    }
8378
8379    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8380            Intent intent, String resolvedType, int flags, int userId) {
8381        if (!sUserManager.exists(userId)) return Collections.emptyList();
8382        final int callingUid = Binder.getCallingUid();
8383        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8384        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8385                false /*includeInstantApps*/);
8386        ComponentName comp = intent.getComponent();
8387        if (comp == null) {
8388            if (intent.getSelector() != null) {
8389                intent = intent.getSelector();
8390                comp = intent.getComponent();
8391            }
8392        }
8393        if (comp != null) {
8394            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8395            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8396            if (pi != null) {
8397                // When specifying an explicit component, we prevent the provider from being
8398                // used when either 1) the provider is in an instant application and the
8399                // caller is not the same instant application or 2) the calling package is an
8400                // instant application and the provider is not visible to instant applications.
8401                final boolean matchInstantApp =
8402                        (flags & PackageManager.MATCH_INSTANT) != 0;
8403                final boolean matchVisibleToInstantAppOnly =
8404                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8405                final boolean isCallerInstantApp =
8406                        instantAppPkgName != null;
8407                final boolean isTargetSameInstantApp =
8408                        comp.getPackageName().equals(instantAppPkgName);
8409                final boolean isTargetInstantApp =
8410                        (pi.applicationInfo.privateFlags
8411                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8412                final boolean isTargetHiddenFromInstantApp =
8413                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8414                final boolean blockResolution =
8415                        !isTargetSameInstantApp
8416                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8417                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8418                                        && isTargetHiddenFromInstantApp));
8419                if (!blockResolution) {
8420                    final ResolveInfo ri = new ResolveInfo();
8421                    ri.providerInfo = pi;
8422                    list.add(ri);
8423                }
8424            }
8425            return list;
8426        }
8427
8428        // reader
8429        synchronized (mPackages) {
8430            String pkgName = intent.getPackage();
8431            if (pkgName == null) {
8432                return applyPostContentProviderResolutionFilter(
8433                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8434                        instantAppPkgName);
8435            }
8436            final PackageParser.Package pkg = mPackages.get(pkgName);
8437            if (pkg != null) {
8438                return applyPostContentProviderResolutionFilter(
8439                        mProviders.queryIntentForPackage(
8440                        intent, resolvedType, flags, pkg.providers, userId),
8441                        instantAppPkgName);
8442            }
8443            return Collections.emptyList();
8444        }
8445    }
8446
8447    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8448            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8449        if (instantAppPkgName == null) {
8450            return resolveInfos;
8451        }
8452        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8453            final ResolveInfo info = resolveInfos.get(i);
8454            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8455            // allow providers that are defined in the provided package
8456            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8457                if (info.providerInfo.splitName != null
8458                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8459                                info.providerInfo.splitName)) {
8460                    // requested provider is defined in a split that hasn't been installed yet.
8461                    // add the installer to the resolve list
8462                    if (DEBUG_EPHEMERAL) {
8463                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8464                    }
8465                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8466                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8467                            info.providerInfo.packageName, info.providerInfo.splitName,
8468                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8469                            null /*failureIntent*/);
8470                    // make sure this resolver is the default
8471                    installerInfo.isDefault = true;
8472                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8473                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8474                    // add a non-generic filter
8475                    installerInfo.filter = new IntentFilter();
8476                    // load resources from the correct package
8477                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8478                    resolveInfos.set(i, installerInfo);
8479                }
8480                continue;
8481            }
8482            // allow providers that have been explicitly exposed to instant applications
8483            if (!isEphemeralApp
8484                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8485                continue;
8486            }
8487            resolveInfos.remove(i);
8488        }
8489        return resolveInfos;
8490    }
8491
8492    @Override
8493    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8494        final int callingUid = Binder.getCallingUid();
8495        if (getInstantAppPackageName(callingUid) != null) {
8496            return ParceledListSlice.emptyList();
8497        }
8498        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8499        flags = updateFlagsForPackage(flags, userId, null);
8500        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8501        enforceCrossUserPermission(callingUid, userId,
8502                true /* requireFullPermission */, false /* checkShell */,
8503                "get installed packages");
8504
8505        // writer
8506        synchronized (mPackages) {
8507            ArrayList<PackageInfo> list;
8508            if (listUninstalled) {
8509                list = new ArrayList<>(mSettings.mPackages.size());
8510                for (PackageSetting ps : mSettings.mPackages.values()) {
8511                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8512                        continue;
8513                    }
8514                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8515                        continue;
8516                    }
8517                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8518                    if (pi != null) {
8519                        list.add(pi);
8520                    }
8521                }
8522            } else {
8523                list = new ArrayList<>(mPackages.size());
8524                for (PackageParser.Package p : mPackages.values()) {
8525                    final PackageSetting ps = (PackageSetting) p.mExtras;
8526                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8527                        continue;
8528                    }
8529                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8530                        continue;
8531                    }
8532                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8533                            p.mExtras, flags, userId);
8534                    if (pi != null) {
8535                        list.add(pi);
8536                    }
8537                }
8538            }
8539
8540            return new ParceledListSlice<>(list);
8541        }
8542    }
8543
8544    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8545            String[] permissions, boolean[] tmp, int flags, int userId) {
8546        int numMatch = 0;
8547        final PermissionsState permissionsState = ps.getPermissionsState();
8548        for (int i=0; i<permissions.length; i++) {
8549            final String permission = permissions[i];
8550            if (permissionsState.hasPermission(permission, userId)) {
8551                tmp[i] = true;
8552                numMatch++;
8553            } else {
8554                tmp[i] = false;
8555            }
8556        }
8557        if (numMatch == 0) {
8558            return;
8559        }
8560        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8561
8562        // The above might return null in cases of uninstalled apps or install-state
8563        // skew across users/profiles.
8564        if (pi != null) {
8565            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8566                if (numMatch == permissions.length) {
8567                    pi.requestedPermissions = permissions;
8568                } else {
8569                    pi.requestedPermissions = new String[numMatch];
8570                    numMatch = 0;
8571                    for (int i=0; i<permissions.length; i++) {
8572                        if (tmp[i]) {
8573                            pi.requestedPermissions[numMatch] = permissions[i];
8574                            numMatch++;
8575                        }
8576                    }
8577                }
8578            }
8579            list.add(pi);
8580        }
8581    }
8582
8583    @Override
8584    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8585            String[] permissions, int flags, int userId) {
8586        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8587        flags = updateFlagsForPackage(flags, userId, permissions);
8588        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8589                true /* requireFullPermission */, false /* checkShell */,
8590                "get packages holding permissions");
8591        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8592
8593        // writer
8594        synchronized (mPackages) {
8595            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8596            boolean[] tmpBools = new boolean[permissions.length];
8597            if (listUninstalled) {
8598                for (PackageSetting ps : mSettings.mPackages.values()) {
8599                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8600                            userId);
8601                }
8602            } else {
8603                for (PackageParser.Package pkg : mPackages.values()) {
8604                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8605                    if (ps != null) {
8606                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8607                                userId);
8608                    }
8609                }
8610            }
8611
8612            return new ParceledListSlice<PackageInfo>(list);
8613        }
8614    }
8615
8616    @Override
8617    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8618        final int callingUid = Binder.getCallingUid();
8619        if (getInstantAppPackageName(callingUid) != null) {
8620            return ParceledListSlice.emptyList();
8621        }
8622        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8623        flags = updateFlagsForApplication(flags, userId, null);
8624        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8625
8626        // writer
8627        synchronized (mPackages) {
8628            ArrayList<ApplicationInfo> list;
8629            if (listUninstalled) {
8630                list = new ArrayList<>(mSettings.mPackages.size());
8631                for (PackageSetting ps : mSettings.mPackages.values()) {
8632                    ApplicationInfo ai;
8633                    int effectiveFlags = flags;
8634                    if (ps.isSystem()) {
8635                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8636                    }
8637                    if (ps.pkg != null) {
8638                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8639                            continue;
8640                        }
8641                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8642                            continue;
8643                        }
8644                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8645                                ps.readUserState(userId), userId);
8646                        if (ai != null) {
8647                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8648                        }
8649                    } else {
8650                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8651                        // and already converts to externally visible package name
8652                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8653                                callingUid, effectiveFlags, userId);
8654                    }
8655                    if (ai != null) {
8656                        list.add(ai);
8657                    }
8658                }
8659            } else {
8660                list = new ArrayList<>(mPackages.size());
8661                for (PackageParser.Package p : mPackages.values()) {
8662                    if (p.mExtras != null) {
8663                        PackageSetting ps = (PackageSetting) p.mExtras;
8664                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8665                            continue;
8666                        }
8667                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8668                            continue;
8669                        }
8670                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8671                                ps.readUserState(userId), userId);
8672                        if (ai != null) {
8673                            ai.packageName = resolveExternalPackageNameLPr(p);
8674                            list.add(ai);
8675                        }
8676                    }
8677                }
8678            }
8679
8680            return new ParceledListSlice<>(list);
8681        }
8682    }
8683
8684    @Override
8685    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8686        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8687            return null;
8688        }
8689        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8690            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8691                    "getEphemeralApplications");
8692        }
8693        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8694                true /* requireFullPermission */, false /* checkShell */,
8695                "getEphemeralApplications");
8696        synchronized (mPackages) {
8697            List<InstantAppInfo> instantApps = mInstantAppRegistry
8698                    .getInstantAppsLPr(userId);
8699            if (instantApps != null) {
8700                return new ParceledListSlice<>(instantApps);
8701            }
8702        }
8703        return null;
8704    }
8705
8706    @Override
8707    public boolean isInstantApp(String packageName, int userId) {
8708        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8709                true /* requireFullPermission */, false /* checkShell */,
8710                "isInstantApp");
8711        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8712            return false;
8713        }
8714
8715        synchronized (mPackages) {
8716            int callingUid = Binder.getCallingUid();
8717            if (Process.isIsolated(callingUid)) {
8718                callingUid = mIsolatedOwners.get(callingUid);
8719            }
8720            final PackageSetting ps = mSettings.mPackages.get(packageName);
8721            PackageParser.Package pkg = mPackages.get(packageName);
8722            final boolean returnAllowed =
8723                    ps != null
8724                    && (isCallerSameApp(packageName, callingUid)
8725                            || canViewInstantApps(callingUid, userId)
8726                            || mInstantAppRegistry.isInstantAccessGranted(
8727                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8728            if (returnAllowed) {
8729                return ps.getInstantApp(userId);
8730            }
8731        }
8732        return false;
8733    }
8734
8735    @Override
8736    public byte[] getInstantAppCookie(String packageName, int userId) {
8737        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8738            return null;
8739        }
8740
8741        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8742                true /* requireFullPermission */, false /* checkShell */,
8743                "getInstantAppCookie");
8744        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8745            return null;
8746        }
8747        synchronized (mPackages) {
8748            return mInstantAppRegistry.getInstantAppCookieLPw(
8749                    packageName, userId);
8750        }
8751    }
8752
8753    @Override
8754    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8755        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8756            return true;
8757        }
8758
8759        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8760                true /* requireFullPermission */, true /* checkShell */,
8761                "setInstantAppCookie");
8762        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8763            return false;
8764        }
8765        synchronized (mPackages) {
8766            return mInstantAppRegistry.setInstantAppCookieLPw(
8767                    packageName, cookie, userId);
8768        }
8769    }
8770
8771    @Override
8772    public Bitmap getInstantAppIcon(String packageName, int userId) {
8773        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8774            return null;
8775        }
8776
8777        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8778            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8779                    "getInstantAppIcon");
8780        }
8781        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8782                true /* requireFullPermission */, false /* checkShell */,
8783                "getInstantAppIcon");
8784
8785        synchronized (mPackages) {
8786            return mInstantAppRegistry.getInstantAppIconLPw(
8787                    packageName, userId);
8788        }
8789    }
8790
8791    private boolean isCallerSameApp(String packageName, int uid) {
8792        PackageParser.Package pkg = mPackages.get(packageName);
8793        return pkg != null
8794                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8795    }
8796
8797    @Override
8798    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8799        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8800            return ParceledListSlice.emptyList();
8801        }
8802        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8803    }
8804
8805    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8806        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8807
8808        // reader
8809        synchronized (mPackages) {
8810            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8811            final int userId = UserHandle.getCallingUserId();
8812            while (i.hasNext()) {
8813                final PackageParser.Package p = i.next();
8814                if (p.applicationInfo == null) continue;
8815
8816                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8817                        && !p.applicationInfo.isDirectBootAware();
8818                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8819                        && p.applicationInfo.isDirectBootAware();
8820
8821                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8822                        && (!mSafeMode || isSystemApp(p))
8823                        && (matchesUnaware || matchesAware)) {
8824                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8825                    if (ps != null) {
8826                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8827                                ps.readUserState(userId), userId);
8828                        if (ai != null) {
8829                            finalList.add(ai);
8830                        }
8831                    }
8832                }
8833            }
8834        }
8835
8836        return finalList;
8837    }
8838
8839    @Override
8840    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8841        if (!sUserManager.exists(userId)) return null;
8842        flags = updateFlagsForComponent(flags, userId, name);
8843        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8844        // reader
8845        synchronized (mPackages) {
8846            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8847            PackageSetting ps = provider != null
8848                    ? mSettings.mPackages.get(provider.owner.packageName)
8849                    : null;
8850            if (ps != null) {
8851                final boolean isInstantApp = ps.getInstantApp(userId);
8852                // normal application; filter out instant application provider
8853                if (instantAppPkgName == null && isInstantApp) {
8854                    return null;
8855                }
8856                // instant application; filter out other instant applications
8857                if (instantAppPkgName != null
8858                        && isInstantApp
8859                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8860                    return null;
8861                }
8862                // instant application; filter out non-exposed provider
8863                if (instantAppPkgName != null
8864                        && !isInstantApp
8865                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8866                    return null;
8867                }
8868                // provider not enabled
8869                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8870                    return null;
8871                }
8872                return PackageParser.generateProviderInfo(
8873                        provider, flags, ps.readUserState(userId), userId);
8874            }
8875            return null;
8876        }
8877    }
8878
8879    /**
8880     * @deprecated
8881     */
8882    @Deprecated
8883    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8884        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8885            return;
8886        }
8887        // reader
8888        synchronized (mPackages) {
8889            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8890                    .entrySet().iterator();
8891            final int userId = UserHandle.getCallingUserId();
8892            while (i.hasNext()) {
8893                Map.Entry<String, PackageParser.Provider> entry = i.next();
8894                PackageParser.Provider p = entry.getValue();
8895                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8896
8897                if (ps != null && p.syncable
8898                        && (!mSafeMode || (p.info.applicationInfo.flags
8899                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8900                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8901                            ps.readUserState(userId), userId);
8902                    if (info != null) {
8903                        outNames.add(entry.getKey());
8904                        outInfo.add(info);
8905                    }
8906                }
8907            }
8908        }
8909    }
8910
8911    @Override
8912    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8913            int uid, int flags, String metaDataKey) {
8914        final int callingUid = Binder.getCallingUid();
8915        final int userId = processName != null ? UserHandle.getUserId(uid)
8916                : UserHandle.getCallingUserId();
8917        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8918        flags = updateFlagsForComponent(flags, userId, processName);
8919        ArrayList<ProviderInfo> finalList = null;
8920        // reader
8921        synchronized (mPackages) {
8922            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8923            while (i.hasNext()) {
8924                final PackageParser.Provider p = i.next();
8925                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8926                if (ps != null && p.info.authority != null
8927                        && (processName == null
8928                                || (p.info.processName.equals(processName)
8929                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8930                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8931
8932                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8933                    // parameter.
8934                    if (metaDataKey != null
8935                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8936                        continue;
8937                    }
8938                    final ComponentName component =
8939                            new ComponentName(p.info.packageName, p.info.name);
8940                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8941                        continue;
8942                    }
8943                    if (finalList == null) {
8944                        finalList = new ArrayList<ProviderInfo>(3);
8945                    }
8946                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8947                            ps.readUserState(userId), userId);
8948                    if (info != null) {
8949                        finalList.add(info);
8950                    }
8951                }
8952            }
8953        }
8954
8955        if (finalList != null) {
8956            Collections.sort(finalList, mProviderInitOrderSorter);
8957            return new ParceledListSlice<ProviderInfo>(finalList);
8958        }
8959
8960        return ParceledListSlice.emptyList();
8961    }
8962
8963    @Override
8964    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8965        // reader
8966        synchronized (mPackages) {
8967            final int callingUid = Binder.getCallingUid();
8968            final int callingUserId = UserHandle.getUserId(callingUid);
8969            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8970            if (ps == null) return null;
8971            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8972                return null;
8973            }
8974            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8975            return PackageParser.generateInstrumentationInfo(i, flags);
8976        }
8977    }
8978
8979    @Override
8980    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8981            String targetPackage, int flags) {
8982        final int callingUid = Binder.getCallingUid();
8983        final int callingUserId = UserHandle.getUserId(callingUid);
8984        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8985        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8986            return ParceledListSlice.emptyList();
8987        }
8988        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8989    }
8990
8991    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8992            int flags) {
8993        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8994
8995        // reader
8996        synchronized (mPackages) {
8997            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8998            while (i.hasNext()) {
8999                final PackageParser.Instrumentation p = i.next();
9000                if (targetPackage == null
9001                        || targetPackage.equals(p.info.targetPackage)) {
9002                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9003                            flags);
9004                    if (ii != null) {
9005                        finalList.add(ii);
9006                    }
9007                }
9008            }
9009        }
9010
9011        return finalList;
9012    }
9013
9014    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
9015        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
9016        try {
9017            scanDirLI(dir, parseFlags, scanFlags, currentTime);
9018        } finally {
9019            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9020        }
9021    }
9022
9023    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
9024        final File[] files = dir.listFiles();
9025        if (ArrayUtils.isEmpty(files)) {
9026            Log.d(TAG, "No files in app dir " + dir);
9027            return;
9028        }
9029
9030        if (DEBUG_PACKAGE_SCANNING) {
9031            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
9032                    + " flags=0x" + Integer.toHexString(parseFlags));
9033        }
9034        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9035                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9036                mParallelPackageParserCallback);
9037
9038        // Submit files for parsing in parallel
9039        int fileCount = 0;
9040        for (File file : files) {
9041            final boolean isPackage = (isApkFile(file) || file.isDirectory())
9042                    && !PackageInstallerService.isStageName(file.getName());
9043            if (!isPackage) {
9044                // Ignore entries which are not packages
9045                continue;
9046            }
9047            parallelPackageParser.submit(file, parseFlags);
9048            fileCount++;
9049        }
9050
9051        // Process results one by one
9052        for (; fileCount > 0; fileCount--) {
9053            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9054            Throwable throwable = parseResult.throwable;
9055            int errorCode = PackageManager.INSTALL_SUCCEEDED;
9056
9057            if (throwable == null) {
9058                // Static shared libraries have synthetic package names
9059                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9060                    renameStaticSharedLibraryPackage(parseResult.pkg);
9061                }
9062                try {
9063                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
9064                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
9065                                currentTime, null);
9066                    }
9067                } catch (PackageManagerException e) {
9068                    errorCode = e.error;
9069                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9070                }
9071            } else if (throwable instanceof PackageParser.PackageParserException) {
9072                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9073                        throwable;
9074                errorCode = e.error;
9075                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9076            } else {
9077                throw new IllegalStateException("Unexpected exception occurred while parsing "
9078                        + parseResult.scanFile, throwable);
9079            }
9080
9081            // Delete invalid userdata apps
9082            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9083                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9084                logCriticalInfo(Log.WARN,
9085                        "Deleting invalid package at " + parseResult.scanFile);
9086                removeCodePathLI(parseResult.scanFile);
9087            }
9088        }
9089        parallelPackageParser.close();
9090    }
9091
9092    private static File getSettingsProblemFile() {
9093        File dataDir = Environment.getDataDirectory();
9094        File systemDir = new File(dataDir, "system");
9095        File fname = new File(systemDir, "uiderrors.txt");
9096        return fname;
9097    }
9098
9099    static void reportSettingsProblem(int priority, String msg) {
9100        logCriticalInfo(priority, msg);
9101    }
9102
9103    public static void logCriticalInfo(int priority, String msg) {
9104        Slog.println(priority, TAG, msg);
9105        EventLogTags.writePmCriticalInfo(msg);
9106        try {
9107            File fname = getSettingsProblemFile();
9108            FileOutputStream out = new FileOutputStream(fname, true);
9109            PrintWriter pw = new FastPrintWriter(out);
9110            SimpleDateFormat formatter = new SimpleDateFormat();
9111            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9112            pw.println(dateString + ": " + msg);
9113            pw.close();
9114            FileUtils.setPermissions(
9115                    fname.toString(),
9116                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9117                    -1, -1);
9118        } catch (java.io.IOException e) {
9119        }
9120    }
9121
9122    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9123        if (srcFile.isDirectory()) {
9124            final File baseFile = new File(pkg.baseCodePath);
9125            long maxModifiedTime = baseFile.lastModified();
9126            if (pkg.splitCodePaths != null) {
9127                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9128                    final File splitFile = new File(pkg.splitCodePaths[i]);
9129                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9130                }
9131            }
9132            return maxModifiedTime;
9133        }
9134        return srcFile.lastModified();
9135    }
9136
9137    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9138            final int policyFlags) throws PackageManagerException {
9139        // When upgrading from pre-N MR1, verify the package time stamp using the package
9140        // directory and not the APK file.
9141        final long lastModifiedTime = mIsPreNMR1Upgrade
9142                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9143        if (ps != null
9144                && ps.codePath.equals(srcFile)
9145                && ps.timeStamp == lastModifiedTime
9146                && !isCompatSignatureUpdateNeeded(pkg)
9147                && !isRecoverSignatureUpdateNeeded(pkg)) {
9148            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9149            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9150            ArraySet<PublicKey> signingKs;
9151            synchronized (mPackages) {
9152                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9153            }
9154            if (ps.signatures.mSignatures != null
9155                    && ps.signatures.mSignatures.length != 0
9156                    && signingKs != null) {
9157                // Optimization: reuse the existing cached certificates
9158                // if the package appears to be unchanged.
9159                pkg.mSignatures = ps.signatures.mSignatures;
9160                pkg.mSigningKeys = signingKs;
9161                return;
9162            }
9163
9164            Slog.w(TAG, "PackageSetting for " + ps.name
9165                    + " is missing signatures.  Collecting certs again to recover them.");
9166        } else {
9167            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9168        }
9169
9170        try {
9171            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9172            PackageParser.collectCertificates(pkg, policyFlags);
9173        } catch (PackageParserException e) {
9174            throw PackageManagerException.from(e);
9175        } finally {
9176            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9177        }
9178    }
9179
9180    /**
9181     *  Traces a package scan.
9182     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9183     */
9184    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9185            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9186        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9187        try {
9188            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9189        } finally {
9190            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9191        }
9192    }
9193
9194    /**
9195     *  Scans a package and returns the newly parsed package.
9196     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9197     */
9198    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9199            long currentTime, UserHandle user) throws PackageManagerException {
9200        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9201        PackageParser pp = new PackageParser();
9202        pp.setSeparateProcesses(mSeparateProcesses);
9203        pp.setOnlyCoreApps(mOnlyCore);
9204        pp.setDisplayMetrics(mMetrics);
9205        pp.setCallback(mPackageParserCallback);
9206
9207        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9208            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9209        }
9210
9211        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9212        final PackageParser.Package pkg;
9213        try {
9214            pkg = pp.parsePackage(scanFile, parseFlags);
9215        } catch (PackageParserException e) {
9216            throw PackageManagerException.from(e);
9217        } finally {
9218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9219        }
9220
9221        // Static shared libraries have synthetic package names
9222        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9223            renameStaticSharedLibraryPackage(pkg);
9224        }
9225
9226        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9227    }
9228
9229    /**
9230     *  Scans a package and returns the newly parsed package.
9231     *  @throws PackageManagerException on a parse error.
9232     */
9233    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9234            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9235            throws PackageManagerException {
9236        // If the package has children and this is the first dive in the function
9237        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9238        // packages (parent and children) would be successfully scanned before the
9239        // actual scan since scanning mutates internal state and we want to atomically
9240        // install the package and its children.
9241        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9242            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9243                scanFlags |= SCAN_CHECK_ONLY;
9244            }
9245        } else {
9246            scanFlags &= ~SCAN_CHECK_ONLY;
9247        }
9248
9249        // Scan the parent
9250        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9251                scanFlags, currentTime, user);
9252
9253        // Scan the children
9254        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9255        for (int i = 0; i < childCount; i++) {
9256            PackageParser.Package childPackage = pkg.childPackages.get(i);
9257            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9258                    currentTime, user);
9259        }
9260
9261
9262        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9263            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9264        }
9265
9266        return scannedPkg;
9267    }
9268
9269    /**
9270     *  Scans a package and returns the newly parsed package.
9271     *  @throws PackageManagerException on a parse error.
9272     */
9273    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9274            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9275            throws PackageManagerException {
9276        PackageSetting ps = null;
9277        PackageSetting updatedPkg;
9278        // reader
9279        synchronized (mPackages) {
9280            // Look to see if we already know about this package.
9281            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9282            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9283                // This package has been renamed to its original name.  Let's
9284                // use that.
9285                ps = mSettings.getPackageLPr(oldName);
9286            }
9287            // If there was no original package, see one for the real package name.
9288            if (ps == null) {
9289                ps = mSettings.getPackageLPr(pkg.packageName);
9290            }
9291            // Check to see if this package could be hiding/updating a system
9292            // package.  Must look for it either under the original or real
9293            // package name depending on our state.
9294            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9295            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9296
9297            // If this is a package we don't know about on the system partition, we
9298            // may need to remove disabled child packages on the system partition
9299            // or may need to not add child packages if the parent apk is updated
9300            // on the data partition and no longer defines this child package.
9301            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9302                // If this is a parent package for an updated system app and this system
9303                // app got an OTA update which no longer defines some of the child packages
9304                // we have to prune them from the disabled system packages.
9305                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9306                if (disabledPs != null) {
9307                    final int scannedChildCount = (pkg.childPackages != null)
9308                            ? pkg.childPackages.size() : 0;
9309                    final int disabledChildCount = disabledPs.childPackageNames != null
9310                            ? disabledPs.childPackageNames.size() : 0;
9311                    for (int i = 0; i < disabledChildCount; i++) {
9312                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9313                        boolean disabledPackageAvailable = false;
9314                        for (int j = 0; j < scannedChildCount; j++) {
9315                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9316                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9317                                disabledPackageAvailable = true;
9318                                break;
9319                            }
9320                         }
9321                         if (!disabledPackageAvailable) {
9322                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9323                         }
9324                    }
9325                }
9326            }
9327        }
9328
9329        final boolean isUpdatedPkg = updatedPkg != null;
9330        final boolean isUpdatedSystemPkg = isUpdatedPkg
9331                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9332        boolean isUpdatedPkgBetter = false;
9333        // First check if this is a system package that may involve an update
9334        if (isUpdatedSystemPkg) {
9335            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9336            // it needs to drop FLAG_PRIVILEGED.
9337            if (locationIsPrivileged(scanFile)) {
9338                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9339            } else {
9340                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9341            }
9342
9343            if (ps != null && !ps.codePath.equals(scanFile)) {
9344                // The path has changed from what was last scanned...  check the
9345                // version of the new path against what we have stored to determine
9346                // what to do.
9347                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9348                if (pkg.mVersionCode <= ps.versionCode) {
9349                    // The system package has been updated and the code path does not match
9350                    // Ignore entry. Skip it.
9351                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9352                            + " ignored: updated version " + ps.versionCode
9353                            + " better than this " + pkg.mVersionCode);
9354                    if (!updatedPkg.codePath.equals(scanFile)) {
9355                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9356                                + ps.name + " changing from " + updatedPkg.codePathString
9357                                + " to " + scanFile);
9358                        updatedPkg.codePath = scanFile;
9359                        updatedPkg.codePathString = scanFile.toString();
9360                        updatedPkg.resourcePath = scanFile;
9361                        updatedPkg.resourcePathString = scanFile.toString();
9362                    }
9363                    updatedPkg.pkg = pkg;
9364                    updatedPkg.versionCode = pkg.mVersionCode;
9365
9366                    // Update the disabled system child packages to point to the package too.
9367                    final int childCount = updatedPkg.childPackageNames != null
9368                            ? updatedPkg.childPackageNames.size() : 0;
9369                    for (int i = 0; i < childCount; i++) {
9370                        String childPackageName = updatedPkg.childPackageNames.get(i);
9371                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9372                                childPackageName);
9373                        if (updatedChildPkg != null) {
9374                            updatedChildPkg.pkg = pkg;
9375                            updatedChildPkg.versionCode = pkg.mVersionCode;
9376                        }
9377                    }
9378                } else {
9379                    // The current app on the system partition is better than
9380                    // what we have updated to on the data partition; switch
9381                    // back to the system partition version.
9382                    // At this point, its safely assumed that package installation for
9383                    // apps in system partition will go through. If not there won't be a working
9384                    // version of the app
9385                    // writer
9386                    synchronized (mPackages) {
9387                        // Just remove the loaded entries from package lists.
9388                        mPackages.remove(ps.name);
9389                    }
9390
9391                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9392                            + " reverting from " + ps.codePathString
9393                            + ": new version " + pkg.mVersionCode
9394                            + " better than installed " + ps.versionCode);
9395
9396                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9397                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9398                    synchronized (mInstallLock) {
9399                        args.cleanUpResourcesLI();
9400                    }
9401                    synchronized (mPackages) {
9402                        mSettings.enableSystemPackageLPw(ps.name);
9403                    }
9404                    isUpdatedPkgBetter = true;
9405                }
9406            }
9407        }
9408
9409        String resourcePath = null;
9410        String baseResourcePath = null;
9411        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9412            if (ps != null && ps.resourcePathString != null) {
9413                resourcePath = ps.resourcePathString;
9414                baseResourcePath = ps.resourcePathString;
9415            } else {
9416                // Should not happen at all. Just log an error.
9417                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9418            }
9419        } else {
9420            resourcePath = pkg.codePath;
9421            baseResourcePath = pkg.baseCodePath;
9422        }
9423
9424        // Set application objects path explicitly.
9425        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9426        pkg.setApplicationInfoCodePath(pkg.codePath);
9427        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9428        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9429        pkg.setApplicationInfoResourcePath(resourcePath);
9430        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9431        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9432
9433        // throw an exception if we have an update to a system application, but, it's not more
9434        // recent than the package we've already scanned
9435        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9436            // Set CPU Abis to application info.
9437            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9438                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
9439                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
9440            } else {
9441                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
9442                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
9443            }
9444
9445            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9446                    + scanFile + " ignored: updated version " + ps.versionCode
9447                    + " better than this " + pkg.mVersionCode);
9448        }
9449
9450        if (isUpdatedPkg) {
9451            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9452            // initially
9453            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9454
9455            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9456            // flag set initially
9457            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9458                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9459            }
9460        }
9461
9462        // Verify certificates against what was last scanned
9463        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9464
9465        /*
9466         * A new system app appeared, but we already had a non-system one of the
9467         * same name installed earlier.
9468         */
9469        boolean shouldHideSystemApp = false;
9470        if (!isUpdatedPkg && ps != null
9471                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9472            /*
9473             * Check to make sure the signatures match first. If they don't,
9474             * wipe the installed application and its data.
9475             */
9476            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9477                    != PackageManager.SIGNATURE_MATCH) {
9478                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9479                        + " signatures don't match existing userdata copy; removing");
9480                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9481                        "scanPackageInternalLI")) {
9482                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9483                }
9484                ps = null;
9485            } else {
9486                /*
9487                 * If the newly-added system app is an older version than the
9488                 * already installed version, hide it. It will be scanned later
9489                 * and re-added like an update.
9490                 */
9491                if (pkg.mVersionCode <= ps.versionCode) {
9492                    shouldHideSystemApp = true;
9493                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9494                            + " but new version " + pkg.mVersionCode + " better than installed "
9495                            + ps.versionCode + "; hiding system");
9496                } else {
9497                    /*
9498                     * The newly found system app is a newer version that the
9499                     * one previously installed. Simply remove the
9500                     * already-installed application and replace it with our own
9501                     * while keeping the application data.
9502                     */
9503                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9504                            + " reverting from " + ps.codePathString + ": new version "
9505                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9506                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9507                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9508                    synchronized (mInstallLock) {
9509                        args.cleanUpResourcesLI();
9510                    }
9511                }
9512            }
9513        }
9514
9515        // The apk is forward locked (not public) if its code and resources
9516        // are kept in different files. (except for app in either system or
9517        // vendor path).
9518        // TODO grab this value from PackageSettings
9519        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9520            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9521                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9522            }
9523        }
9524
9525        final int userId = ((user == null) ? 0 : user.getIdentifier());
9526        if (ps != null && ps.getInstantApp(userId)) {
9527            scanFlags |= SCAN_AS_INSTANT_APP;
9528        }
9529        if (ps != null && ps.getVirtulalPreload(userId)) {
9530            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9531        }
9532
9533        // Note that we invoke the following method only if we are about to unpack an application
9534        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9535                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9536
9537        /*
9538         * If the system app should be overridden by a previously installed
9539         * data, hide the system app now and let the /data/app scan pick it up
9540         * again.
9541         */
9542        if (shouldHideSystemApp) {
9543            synchronized (mPackages) {
9544                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9545            }
9546        }
9547
9548        return scannedPkg;
9549    }
9550
9551    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9552        // Derive the new package synthetic package name
9553        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9554                + pkg.staticSharedLibVersion);
9555    }
9556
9557    private static String fixProcessName(String defProcessName,
9558            String processName) {
9559        if (processName == null) {
9560            return defProcessName;
9561        }
9562        return processName;
9563    }
9564
9565    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9566            throws PackageManagerException {
9567        if (pkgSetting.signatures.mSignatures != null) {
9568            // Already existing package. Make sure signatures match
9569            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9570                    == PackageManager.SIGNATURE_MATCH;
9571            if (!match) {
9572                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9573                        == PackageManager.SIGNATURE_MATCH;
9574            }
9575            if (!match) {
9576                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9577                        == PackageManager.SIGNATURE_MATCH;
9578            }
9579            if (!match) {
9580                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9581                        + pkg.packageName + " signatures do not match the "
9582                        + "previously installed version; ignoring!");
9583            }
9584        }
9585
9586        // Check for shared user signatures
9587        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9588            // Already existing package. Make sure signatures match
9589            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9590                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9591            if (!match) {
9592                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9593                        == PackageManager.SIGNATURE_MATCH;
9594            }
9595            if (!match) {
9596                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9597                        == PackageManager.SIGNATURE_MATCH;
9598            }
9599            if (!match) {
9600                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9601                        "Package " + pkg.packageName
9602                        + " has no signatures that match those in shared user "
9603                        + pkgSetting.sharedUser.name + "; ignoring!");
9604            }
9605        }
9606    }
9607
9608    /**
9609     * Enforces that only the system UID or root's UID can call a method exposed
9610     * via Binder.
9611     *
9612     * @param message used as message if SecurityException is thrown
9613     * @throws SecurityException if the caller is not system or root
9614     */
9615    private static final void enforceSystemOrRoot(String message) {
9616        final int uid = Binder.getCallingUid();
9617        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9618            throw new SecurityException(message);
9619        }
9620    }
9621
9622    @Override
9623    public void performFstrimIfNeeded() {
9624        enforceSystemOrRoot("Only the system can request fstrim");
9625
9626        // Before everything else, see whether we need to fstrim.
9627        try {
9628            IStorageManager sm = PackageHelper.getStorageManager();
9629            if (sm != null) {
9630                boolean doTrim = false;
9631                final long interval = android.provider.Settings.Global.getLong(
9632                        mContext.getContentResolver(),
9633                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9634                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9635                if (interval > 0) {
9636                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9637                    if (timeSinceLast > interval) {
9638                        doTrim = true;
9639                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9640                                + "; running immediately");
9641                    }
9642                }
9643                if (doTrim) {
9644                    final boolean dexOptDialogShown;
9645                    synchronized (mPackages) {
9646                        dexOptDialogShown = mDexOptDialogShown;
9647                    }
9648                    if (!isFirstBoot() && dexOptDialogShown) {
9649                        try {
9650                            ActivityManager.getService().showBootMessage(
9651                                    mContext.getResources().getString(
9652                                            R.string.android_upgrading_fstrim), true);
9653                        } catch (RemoteException e) {
9654                        }
9655                    }
9656                    sm.runMaintenance();
9657                }
9658            } else {
9659                Slog.e(TAG, "storageManager service unavailable!");
9660            }
9661        } catch (RemoteException e) {
9662            // Can't happen; StorageManagerService is local
9663        }
9664    }
9665
9666    @Override
9667    public void updatePackagesIfNeeded() {
9668        enforceSystemOrRoot("Only the system can request package update");
9669
9670        // We need to re-extract after an OTA.
9671        boolean causeUpgrade = isUpgrade();
9672
9673        // First boot or factory reset.
9674        // Note: we also handle devices that are upgrading to N right now as if it is their
9675        //       first boot, as they do not have profile data.
9676        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9677
9678        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9679        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9680
9681        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9682            return;
9683        }
9684
9685        List<PackageParser.Package> pkgs;
9686        synchronized (mPackages) {
9687            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9688        }
9689
9690        final long startTime = System.nanoTime();
9691        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9692                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9693                    false /* bootComplete */);
9694
9695        final int elapsedTimeSeconds =
9696                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9697
9698        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9699        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9700        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9701        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9702        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9703    }
9704
9705    /*
9706     * Return the prebuilt profile path given a package base code path.
9707     */
9708    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9709        return pkg.baseCodePath + ".prof";
9710    }
9711
9712    /**
9713     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9714     * containing statistics about the invocation. The array consists of three elements,
9715     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9716     * and {@code numberOfPackagesFailed}.
9717     */
9718    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9719            String compilerFilter, boolean bootComplete) {
9720
9721        int numberOfPackagesVisited = 0;
9722        int numberOfPackagesOptimized = 0;
9723        int numberOfPackagesSkipped = 0;
9724        int numberOfPackagesFailed = 0;
9725        final int numberOfPackagesToDexopt = pkgs.size();
9726
9727        for (PackageParser.Package pkg : pkgs) {
9728            numberOfPackagesVisited++;
9729
9730            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9731                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9732                // that are already compiled.
9733                File profileFile = new File(getPrebuildProfilePath(pkg));
9734                // Copy profile if it exists.
9735                if (profileFile.exists()) {
9736                    try {
9737                        // We could also do this lazily before calling dexopt in
9738                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9739                        // is that we don't have a good way to say "do this only once".
9740                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9741                                pkg.applicationInfo.uid, pkg.packageName)) {
9742                            Log.e(TAG, "Installer failed to copy system profile!");
9743                        }
9744                    } catch (Exception e) {
9745                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9746                                e);
9747                    }
9748                }
9749            }
9750
9751            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9752                if (DEBUG_DEXOPT) {
9753                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9754                }
9755                numberOfPackagesSkipped++;
9756                continue;
9757            }
9758
9759            if (DEBUG_DEXOPT) {
9760                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9761                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9762            }
9763
9764            if (showDialog) {
9765                try {
9766                    ActivityManager.getService().showBootMessage(
9767                            mContext.getResources().getString(R.string.android_upgrading_apk,
9768                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9769                } catch (RemoteException e) {
9770                }
9771                synchronized (mPackages) {
9772                    mDexOptDialogShown = true;
9773                }
9774            }
9775
9776            // If the OTA updates a system app which was previously preopted to a non-preopted state
9777            // the app might end up being verified at runtime. That's because by default the apps
9778            // are verify-profile but for preopted apps there's no profile.
9779            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9780            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9781            // filter (by default 'quicken').
9782            // Note that at this stage unused apps are already filtered.
9783            if (isSystemApp(pkg) &&
9784                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9785                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9786                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9787            }
9788
9789            // checkProfiles is false to avoid merging profiles during boot which
9790            // might interfere with background compilation (b/28612421).
9791            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9792            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9793            // trade-off worth doing to save boot time work.
9794            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9795            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9796                    pkg.packageName,
9797                    compilerFilter,
9798                    dexoptFlags));
9799
9800            if (pkg.isSystemApp()) {
9801                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9802                // too much boot after an OTA.
9803                int secondaryDexoptFlags = dexoptFlags |
9804                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9805                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9806                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9807                        pkg.packageName,
9808                        compilerFilter,
9809                        secondaryDexoptFlags));
9810            }
9811
9812            // TODO(shubhamajmera): Record secondary dexopt stats.
9813            switch (primaryDexOptStaus) {
9814                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9815                    numberOfPackagesOptimized++;
9816                    break;
9817                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9818                    numberOfPackagesSkipped++;
9819                    break;
9820                case PackageDexOptimizer.DEX_OPT_FAILED:
9821                    numberOfPackagesFailed++;
9822                    break;
9823                default:
9824                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9825                    break;
9826            }
9827        }
9828
9829        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9830                numberOfPackagesFailed };
9831    }
9832
9833    @Override
9834    public void notifyPackageUse(String packageName, int reason) {
9835        synchronized (mPackages) {
9836            final int callingUid = Binder.getCallingUid();
9837            final int callingUserId = UserHandle.getUserId(callingUid);
9838            if (getInstantAppPackageName(callingUid) != null) {
9839                if (!isCallerSameApp(packageName, callingUid)) {
9840                    return;
9841                }
9842            } else {
9843                if (isInstantApp(packageName, callingUserId)) {
9844                    return;
9845                }
9846            }
9847            final PackageParser.Package p = mPackages.get(packageName);
9848            if (p == null) {
9849                return;
9850            }
9851            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9852        }
9853    }
9854
9855    @Override
9856    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9857            List<String> classPaths, String loaderIsa) {
9858        int userId = UserHandle.getCallingUserId();
9859        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9860        if (ai == null) {
9861            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9862                + loadingPackageName + ", user=" + userId);
9863            return;
9864        }
9865        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9866    }
9867
9868    @Override
9869    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9870            IDexModuleRegisterCallback callback) {
9871        int userId = UserHandle.getCallingUserId();
9872        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9873        DexManager.RegisterDexModuleResult result;
9874        if (ai == null) {
9875            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9876                     " calling user. package=" + packageName + ", user=" + userId);
9877            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9878        } else {
9879            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9880        }
9881
9882        if (callback != null) {
9883            mHandler.post(() -> {
9884                try {
9885                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9886                } catch (RemoteException e) {
9887                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9888                }
9889            });
9890        }
9891    }
9892
9893    /**
9894     * Ask the package manager to perform a dex-opt with the given compiler filter.
9895     *
9896     * Note: exposed only for the shell command to allow moving packages explicitly to a
9897     *       definite state.
9898     */
9899    @Override
9900    public boolean performDexOptMode(String packageName,
9901            boolean checkProfiles, String targetCompilerFilter, boolean force,
9902            boolean bootComplete, String splitName) {
9903        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9904                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9905                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9906        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9907                splitName, flags));
9908    }
9909
9910    /**
9911     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9912     * secondary dex files belonging to the given package.
9913     *
9914     * Note: exposed only for the shell command to allow moving packages explicitly to a
9915     *       definite state.
9916     */
9917    @Override
9918    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9919            boolean force) {
9920        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9921                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9922                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9923                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9924        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9925    }
9926
9927    /*package*/ boolean performDexOpt(DexoptOptions options) {
9928        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9929            return false;
9930        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9931            return false;
9932        }
9933
9934        if (options.isDexoptOnlySecondaryDex()) {
9935            return mDexManager.dexoptSecondaryDex(options);
9936        } else {
9937            int dexoptStatus = performDexOptWithStatus(options);
9938            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9939        }
9940    }
9941
9942    /**
9943     * Perform dexopt on the given package and return one of following result:
9944     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9945     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9946     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9947     */
9948    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9949        return performDexOptTraced(options);
9950    }
9951
9952    private int performDexOptTraced(DexoptOptions options) {
9953        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9954        try {
9955            return performDexOptInternal(options);
9956        } finally {
9957            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9958        }
9959    }
9960
9961    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9962    // if the package can now be considered up to date for the given filter.
9963    private int performDexOptInternal(DexoptOptions options) {
9964        PackageParser.Package p;
9965        synchronized (mPackages) {
9966            p = mPackages.get(options.getPackageName());
9967            if (p == null) {
9968                // Package could not be found. Report failure.
9969                return PackageDexOptimizer.DEX_OPT_FAILED;
9970            }
9971            mPackageUsage.maybeWriteAsync(mPackages);
9972            mCompilerStats.maybeWriteAsync();
9973        }
9974        long callingId = Binder.clearCallingIdentity();
9975        try {
9976            synchronized (mInstallLock) {
9977                return performDexOptInternalWithDependenciesLI(p, options);
9978            }
9979        } finally {
9980            Binder.restoreCallingIdentity(callingId);
9981        }
9982    }
9983
9984    public ArraySet<String> getOptimizablePackages() {
9985        ArraySet<String> pkgs = new ArraySet<String>();
9986        synchronized (mPackages) {
9987            for (PackageParser.Package p : mPackages.values()) {
9988                if (PackageDexOptimizer.canOptimizePackage(p)) {
9989                    pkgs.add(p.packageName);
9990                }
9991            }
9992        }
9993        return pkgs;
9994    }
9995
9996    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9997            DexoptOptions options) {
9998        // Select the dex optimizer based on the force parameter.
9999        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10000        //       allocate an object here.
10001        PackageDexOptimizer pdo = options.isForce()
10002                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10003                : mPackageDexOptimizer;
10004
10005        // Dexopt all dependencies first. Note: we ignore the return value and march on
10006        // on errors.
10007        // Note that we are going to call performDexOpt on those libraries as many times as
10008        // they are referenced in packages. When we do a batch of performDexOpt (for example
10009        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10010        // and the first package that uses the library will dexopt it. The
10011        // others will see that the compiled code for the library is up to date.
10012        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
10013        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10014        if (!deps.isEmpty()) {
10015            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10016                    options.getCompilerFilter(), options.getSplitName(),
10017                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10018            for (PackageParser.Package depPackage : deps) {
10019                // TODO: Analyze and investigate if we (should) profile libraries.
10020                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
10021                        getOrCreateCompilerPackageStats(depPackage),
10022                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
10023            }
10024        }
10025        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
10026                getOrCreateCompilerPackageStats(p),
10027                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10028    }
10029
10030    /**
10031     * Reconcile the information we have about the secondary dex files belonging to
10032     * {@code packagName} and the actual dex files. For all dex files that were
10033     * deleted, update the internal records and delete the generated oat files.
10034     */
10035    @Override
10036    public void reconcileSecondaryDexFiles(String packageName) {
10037        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10038            return;
10039        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10040            return;
10041        }
10042        mDexManager.reconcileSecondaryDexFiles(packageName);
10043    }
10044
10045    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10046    // a reference there.
10047    /*package*/ DexManager getDexManager() {
10048        return mDexManager;
10049    }
10050
10051    /**
10052     * Execute the background dexopt job immediately.
10053     */
10054    @Override
10055    public boolean runBackgroundDexoptJob() {
10056        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10057            return false;
10058        }
10059        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
10060    }
10061
10062    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
10063        if (p.usesLibraries != null || p.usesOptionalLibraries != null
10064                || p.usesStaticLibraries != null) {
10065            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10066            Set<String> collectedNames = new HashSet<>();
10067            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
10068
10069            retValue.remove(p);
10070
10071            return retValue;
10072        } else {
10073            return Collections.emptyList();
10074        }
10075    }
10076
10077    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10078            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10079        if (!collectedNames.contains(p.packageName)) {
10080            collectedNames.add(p.packageName);
10081            collected.add(p);
10082
10083            if (p.usesLibraries != null) {
10084                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10085                        null, collected, collectedNames);
10086            }
10087            if (p.usesOptionalLibraries != null) {
10088                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10089                        null, collected, collectedNames);
10090            }
10091            if (p.usesStaticLibraries != null) {
10092                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10093                        p.usesStaticLibrariesVersions, collected, collectedNames);
10094            }
10095        }
10096    }
10097
10098    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10099            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10100        final int libNameCount = libs.size();
10101        for (int i = 0; i < libNameCount; i++) {
10102            String libName = libs.get(i);
10103            int version = (versions != null && versions.length == libNameCount)
10104                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10105            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10106            if (libPkg != null) {
10107                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10108            }
10109        }
10110    }
10111
10112    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10113        synchronized (mPackages) {
10114            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10115            if (libEntry != null) {
10116                return mPackages.get(libEntry.apk);
10117            }
10118            return null;
10119        }
10120    }
10121
10122    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10123        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10124        if (versionedLib == null) {
10125            return null;
10126        }
10127        return versionedLib.get(version);
10128    }
10129
10130    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10131        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10132                pkg.staticSharedLibName);
10133        if (versionedLib == null) {
10134            return null;
10135        }
10136        int previousLibVersion = -1;
10137        final int versionCount = versionedLib.size();
10138        for (int i = 0; i < versionCount; i++) {
10139            final int libVersion = versionedLib.keyAt(i);
10140            if (libVersion < pkg.staticSharedLibVersion) {
10141                previousLibVersion = Math.max(previousLibVersion, libVersion);
10142            }
10143        }
10144        if (previousLibVersion >= 0) {
10145            return versionedLib.get(previousLibVersion);
10146        }
10147        return null;
10148    }
10149
10150    public void shutdown() {
10151        mPackageUsage.writeNow(mPackages);
10152        mCompilerStats.writeNow();
10153        mDexManager.writePackageDexUsageNow();
10154    }
10155
10156    @Override
10157    public void dumpProfiles(String packageName) {
10158        PackageParser.Package pkg;
10159        synchronized (mPackages) {
10160            pkg = mPackages.get(packageName);
10161            if (pkg == null) {
10162                throw new IllegalArgumentException("Unknown package: " + packageName);
10163            }
10164        }
10165        /* Only the shell, root, or the app user should be able to dump profiles. */
10166        int callingUid = Binder.getCallingUid();
10167        if (callingUid != Process.SHELL_UID &&
10168            callingUid != Process.ROOT_UID &&
10169            callingUid != pkg.applicationInfo.uid) {
10170            throw new SecurityException("dumpProfiles");
10171        }
10172
10173        synchronized (mInstallLock) {
10174            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10175            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10176            try {
10177                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10178                String codePaths = TextUtils.join(";", allCodePaths);
10179                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10180            } catch (InstallerException e) {
10181                Slog.w(TAG, "Failed to dump profiles", e);
10182            }
10183            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10184        }
10185    }
10186
10187    @Override
10188    public void forceDexOpt(String packageName) {
10189        enforceSystemOrRoot("forceDexOpt");
10190
10191        PackageParser.Package pkg;
10192        synchronized (mPackages) {
10193            pkg = mPackages.get(packageName);
10194            if (pkg == null) {
10195                throw new IllegalArgumentException("Unknown package: " + packageName);
10196            }
10197        }
10198
10199        synchronized (mInstallLock) {
10200            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10201
10202            // Whoever is calling forceDexOpt wants a compiled package.
10203            // Don't use profiles since that may cause compilation to be skipped.
10204            final int res = performDexOptInternalWithDependenciesLI(
10205                    pkg,
10206                    new DexoptOptions(packageName,
10207                            getDefaultCompilerFilter(),
10208                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10209
10210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10211            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10212                throw new IllegalStateException("Failed to dexopt: " + res);
10213            }
10214        }
10215    }
10216
10217    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10218        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10219            Slog.w(TAG, "Unable to update from " + oldPkg.name
10220                    + " to " + newPkg.packageName
10221                    + ": old package not in system partition");
10222            return false;
10223        } else if (mPackages.get(oldPkg.name) != null) {
10224            Slog.w(TAG, "Unable to update from " + oldPkg.name
10225                    + " to " + newPkg.packageName
10226                    + ": old package still exists");
10227            return false;
10228        }
10229        return true;
10230    }
10231
10232    void removeCodePathLI(File codePath) {
10233        if (codePath.isDirectory()) {
10234            try {
10235                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10236            } catch (InstallerException e) {
10237                Slog.w(TAG, "Failed to remove code path", e);
10238            }
10239        } else {
10240            codePath.delete();
10241        }
10242    }
10243
10244    private int[] resolveUserIds(int userId) {
10245        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10246    }
10247
10248    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10249        if (pkg == null) {
10250            Slog.wtf(TAG, "Package was null!", new Throwable());
10251            return;
10252        }
10253        clearAppDataLeafLIF(pkg, userId, flags);
10254        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10255        for (int i = 0; i < childCount; i++) {
10256            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10257        }
10258    }
10259
10260    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10261        final PackageSetting ps;
10262        synchronized (mPackages) {
10263            ps = mSettings.mPackages.get(pkg.packageName);
10264        }
10265        for (int realUserId : resolveUserIds(userId)) {
10266            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10267            try {
10268                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10269                        ceDataInode);
10270            } catch (InstallerException e) {
10271                Slog.w(TAG, String.valueOf(e));
10272            }
10273        }
10274    }
10275
10276    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10277        if (pkg == null) {
10278            Slog.wtf(TAG, "Package was null!", new Throwable());
10279            return;
10280        }
10281        destroyAppDataLeafLIF(pkg, userId, flags);
10282        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10283        for (int i = 0; i < childCount; i++) {
10284            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10285        }
10286    }
10287
10288    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10289        final PackageSetting ps;
10290        synchronized (mPackages) {
10291            ps = mSettings.mPackages.get(pkg.packageName);
10292        }
10293        for (int realUserId : resolveUserIds(userId)) {
10294            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10295            try {
10296                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10297                        ceDataInode);
10298            } catch (InstallerException e) {
10299                Slog.w(TAG, String.valueOf(e));
10300            }
10301            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10302        }
10303    }
10304
10305    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10306        if (pkg == null) {
10307            Slog.wtf(TAG, "Package was null!", new Throwable());
10308            return;
10309        }
10310        destroyAppProfilesLeafLIF(pkg);
10311        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10312        for (int i = 0; i < childCount; i++) {
10313            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10314        }
10315    }
10316
10317    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10318        try {
10319            mInstaller.destroyAppProfiles(pkg.packageName);
10320        } catch (InstallerException e) {
10321            Slog.w(TAG, String.valueOf(e));
10322        }
10323    }
10324
10325    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10326        if (pkg == null) {
10327            Slog.wtf(TAG, "Package was null!", new Throwable());
10328            return;
10329        }
10330        clearAppProfilesLeafLIF(pkg);
10331        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10332        for (int i = 0; i < childCount; i++) {
10333            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10334        }
10335    }
10336
10337    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10338        try {
10339            mInstaller.clearAppProfiles(pkg.packageName);
10340        } catch (InstallerException e) {
10341            Slog.w(TAG, String.valueOf(e));
10342        }
10343    }
10344
10345    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10346            long lastUpdateTime) {
10347        // Set parent install/update time
10348        PackageSetting ps = (PackageSetting) pkg.mExtras;
10349        if (ps != null) {
10350            ps.firstInstallTime = firstInstallTime;
10351            ps.lastUpdateTime = lastUpdateTime;
10352        }
10353        // Set children install/update time
10354        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10355        for (int i = 0; i < childCount; i++) {
10356            PackageParser.Package childPkg = pkg.childPackages.get(i);
10357            ps = (PackageSetting) childPkg.mExtras;
10358            if (ps != null) {
10359                ps.firstInstallTime = firstInstallTime;
10360                ps.lastUpdateTime = lastUpdateTime;
10361            }
10362        }
10363    }
10364
10365    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10366            PackageParser.Package changingLib) {
10367        if (file.path != null) {
10368            usesLibraryFiles.add(file.path);
10369            return;
10370        }
10371        PackageParser.Package p = mPackages.get(file.apk);
10372        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10373            // If we are doing this while in the middle of updating a library apk,
10374            // then we need to make sure to use that new apk for determining the
10375            // dependencies here.  (We haven't yet finished committing the new apk
10376            // to the package manager state.)
10377            if (p == null || p.packageName.equals(changingLib.packageName)) {
10378                p = changingLib;
10379            }
10380        }
10381        if (p != null) {
10382            usesLibraryFiles.addAll(p.getAllCodePaths());
10383            if (p.usesLibraryFiles != null) {
10384                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10385            }
10386        }
10387    }
10388
10389    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10390            PackageParser.Package changingLib) throws PackageManagerException {
10391        if (pkg == null) {
10392            return;
10393        }
10394        ArraySet<String> usesLibraryFiles = null;
10395        if (pkg.usesLibraries != null) {
10396            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10397                    null, null, pkg.packageName, changingLib, true,
10398                    pkg.applicationInfo.targetSdkVersion, null);
10399        }
10400        if (pkg.usesStaticLibraries != null) {
10401            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10402                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10403                    pkg.packageName, changingLib, true,
10404                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10405        }
10406        if (pkg.usesOptionalLibraries != null) {
10407            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10408                    null, null, pkg.packageName, changingLib, false,
10409                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
10410        }
10411        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10412            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10413        } else {
10414            pkg.usesLibraryFiles = null;
10415        }
10416    }
10417
10418    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10419            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
10420            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10421            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
10422            throws PackageManagerException {
10423        final int libCount = requestedLibraries.size();
10424        for (int i = 0; i < libCount; i++) {
10425            final String libName = requestedLibraries.get(i);
10426            final int libVersion = requiredVersions != null ? requiredVersions[i]
10427                    : SharedLibraryInfo.VERSION_UNDEFINED;
10428            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10429            if (libEntry == null) {
10430                if (required) {
10431                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10432                            "Package " + packageName + " requires unavailable shared library "
10433                                    + libName + "; failing!");
10434                } else if (DEBUG_SHARED_LIBRARIES) {
10435                    Slog.i(TAG, "Package " + packageName
10436                            + " desires unavailable shared library "
10437                            + libName + "; ignoring!");
10438                }
10439            } else {
10440                if (requiredVersions != null && requiredCertDigests != null) {
10441                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10442                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10443                            "Package " + packageName + " requires unavailable static shared"
10444                                    + " library " + libName + " version "
10445                                    + libEntry.info.getVersion() + "; failing!");
10446                    }
10447
10448                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10449                    if (libPkg == null) {
10450                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10451                                "Package " + packageName + " requires unavailable static shared"
10452                                        + " library; failing!");
10453                    }
10454
10455                    final String[] expectedCertDigests = requiredCertDigests[i];
10456                    // For apps targeting O MR1 we require explicit enumeration of all certs.
10457                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
10458                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
10459                            : PackageUtils.computeSignaturesSha256Digests(
10460                                    new Signature[]{libPkg.mSignatures[0]});
10461
10462                    // Take a shortcut if sizes don't match. Note that if an app doesn't
10463                    // target O we don't parse the "additional-certificate" tags similarly
10464                    // how we only consider all certs only for apps targeting O (see above).
10465                    // Therefore, the size check is safe to make.
10466                    if (expectedCertDigests.length != libCertDigests.length) {
10467                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10468                                "Package " + packageName + " requires differently signed" +
10469                                        " static sDexLoadReporter.java:45.19hared library; failing!");
10470                    }
10471
10472                    // Use a predictable order as signature order may vary
10473                    Arrays.sort(libCertDigests);
10474                    Arrays.sort(expectedCertDigests);
10475
10476                    final int certCount = libCertDigests.length;
10477                    for (int j = 0; j < certCount; j++) {
10478                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10479                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10480                                    "Package " + packageName + " requires differently signed" +
10481                                            " static shared library; failing!");
10482                        }
10483                    }
10484                }
10485
10486                if (outUsedLibraries == null) {
10487                    outUsedLibraries = new ArraySet<>();
10488                }
10489                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10490            }
10491        }
10492        return outUsedLibraries;
10493    }
10494
10495    private static boolean hasString(List<String> list, List<String> which) {
10496        if (list == null) {
10497            return false;
10498        }
10499        for (int i=list.size()-1; i>=0; i--) {
10500            for (int j=which.size()-1; j>=0; j--) {
10501                if (which.get(j).equals(list.get(i))) {
10502                    return true;
10503                }
10504            }
10505        }
10506        return false;
10507    }
10508
10509    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10510            PackageParser.Package changingPkg) {
10511        ArrayList<PackageParser.Package> res = null;
10512        for (PackageParser.Package pkg : mPackages.values()) {
10513            if (changingPkg != null
10514                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10515                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10516                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10517                            changingPkg.staticSharedLibName)) {
10518                return null;
10519            }
10520            if (res == null) {
10521                res = new ArrayList<>();
10522            }
10523            res.add(pkg);
10524            try {
10525                updateSharedLibrariesLPr(pkg, changingPkg);
10526            } catch (PackageManagerException e) {
10527                // If a system app update or an app and a required lib missing we
10528                // delete the package and for updated system apps keep the data as
10529                // it is better for the user to reinstall than to be in an limbo
10530                // state. Also libs disappearing under an app should never happen
10531                // - just in case.
10532                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10533                    final int flags = pkg.isUpdatedSystemApp()
10534                            ? PackageManager.DELETE_KEEP_DATA : 0;
10535                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10536                            flags , null, true, null);
10537                }
10538                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10539            }
10540        }
10541        return res;
10542    }
10543
10544    /**
10545     * Derive the value of the {@code cpuAbiOverride} based on the provided
10546     * value and an optional stored value from the package settings.
10547     */
10548    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10549        String cpuAbiOverride = null;
10550
10551        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10552            cpuAbiOverride = null;
10553        } else if (abiOverride != null) {
10554            cpuAbiOverride = abiOverride;
10555        } else if (settings != null) {
10556            cpuAbiOverride = settings.cpuAbiOverrideString;
10557        }
10558
10559        return cpuAbiOverride;
10560    }
10561
10562    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10563            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10564                    throws PackageManagerException {
10565        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10566        // If the package has children and this is the first dive in the function
10567        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10568        // whether all packages (parent and children) would be successfully scanned
10569        // before the actual scan since scanning mutates internal state and we want
10570        // to atomically install the package and its children.
10571        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10572            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10573                scanFlags |= SCAN_CHECK_ONLY;
10574            }
10575        } else {
10576            scanFlags &= ~SCAN_CHECK_ONLY;
10577        }
10578
10579        final PackageParser.Package scannedPkg;
10580        try {
10581            // Scan the parent
10582            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10583            // Scan the children
10584            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10585            for (int i = 0; i < childCount; i++) {
10586                PackageParser.Package childPkg = pkg.childPackages.get(i);
10587                scanPackageLI(childPkg, policyFlags,
10588                        scanFlags, currentTime, user);
10589            }
10590        } finally {
10591            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10592        }
10593
10594        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10595            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10596        }
10597
10598        return scannedPkg;
10599    }
10600
10601    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10602            int scanFlags, long currentTime, @Nullable UserHandle user)
10603                    throws PackageManagerException {
10604        boolean success = false;
10605        try {
10606            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10607                    currentTime, user);
10608            success = true;
10609            return res;
10610        } finally {
10611            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10612                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10613                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10614                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10615                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10616            }
10617        }
10618    }
10619
10620    /**
10621     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10622     */
10623    private static boolean apkHasCode(String fileName) {
10624        StrictJarFile jarFile = null;
10625        try {
10626            jarFile = new StrictJarFile(fileName,
10627                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10628            return jarFile.findEntry("classes.dex") != null;
10629        } catch (IOException ignore) {
10630        } finally {
10631            try {
10632                if (jarFile != null) {
10633                    jarFile.close();
10634                }
10635            } catch (IOException ignore) {}
10636        }
10637        return false;
10638    }
10639
10640    /**
10641     * Enforces code policy for the package. This ensures that if an APK has
10642     * declared hasCode="true" in its manifest that the APK actually contains
10643     * code.
10644     *
10645     * @throws PackageManagerException If bytecode could not be found when it should exist
10646     */
10647    private static void assertCodePolicy(PackageParser.Package pkg)
10648            throws PackageManagerException {
10649        final boolean shouldHaveCode =
10650                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10651        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10652            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10653                    "Package " + pkg.baseCodePath + " code is missing");
10654        }
10655
10656        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10657            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10658                final boolean splitShouldHaveCode =
10659                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10660                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10661                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10662                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10663                }
10664            }
10665        }
10666    }
10667
10668    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10669            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10670                    throws PackageManagerException {
10671        if (DEBUG_PACKAGE_SCANNING) {
10672            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10673                Log.d(TAG, "Scanning package " + pkg.packageName);
10674        }
10675
10676        applyPolicy(pkg, policyFlags);
10677
10678        assertPackageIsValid(pkg, policyFlags, scanFlags);
10679
10680        // Initialize package source and resource directories
10681        final File scanFile = new File(pkg.codePath);
10682        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10683        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10684
10685        SharedUserSetting suid = null;
10686        PackageSetting pkgSetting = null;
10687
10688        // Getting the package setting may have a side-effect, so if we
10689        // are only checking if scan would succeed, stash a copy of the
10690        // old setting to restore at the end.
10691        PackageSetting nonMutatedPs = null;
10692
10693        // We keep references to the derived CPU Abis from settings in oder to reuse
10694        // them in the case where we're not upgrading or booting for the first time.
10695        String primaryCpuAbiFromSettings = null;
10696        String secondaryCpuAbiFromSettings = null;
10697
10698        // writer
10699        synchronized (mPackages) {
10700            if (pkg.mSharedUserId != null) {
10701                // SIDE EFFECTS; may potentially allocate a new shared user
10702                suid = mSettings.getSharedUserLPw(
10703                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10704                if (DEBUG_PACKAGE_SCANNING) {
10705                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10706                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10707                                + "): packages=" + suid.packages);
10708                }
10709            }
10710
10711            // Check if we are renaming from an original package name.
10712            PackageSetting origPackage = null;
10713            String realName = null;
10714            if (pkg.mOriginalPackages != null) {
10715                // This package may need to be renamed to a previously
10716                // installed name.  Let's check on that...
10717                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10718                if (pkg.mOriginalPackages.contains(renamed)) {
10719                    // This package had originally been installed as the
10720                    // original name, and we have already taken care of
10721                    // transitioning to the new one.  Just update the new
10722                    // one to continue using the old name.
10723                    realName = pkg.mRealPackage;
10724                    if (!pkg.packageName.equals(renamed)) {
10725                        // Callers into this function may have already taken
10726                        // care of renaming the package; only do it here if
10727                        // it is not already done.
10728                        pkg.setPackageName(renamed);
10729                    }
10730                } else {
10731                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10732                        if ((origPackage = mSettings.getPackageLPr(
10733                                pkg.mOriginalPackages.get(i))) != null) {
10734                            // We do have the package already installed under its
10735                            // original name...  should we use it?
10736                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10737                                // New package is not compatible with original.
10738                                origPackage = null;
10739                                continue;
10740                            } else if (origPackage.sharedUser != null) {
10741                                // Make sure uid is compatible between packages.
10742                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10743                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10744                                            + " to " + pkg.packageName + ": old uid "
10745                                            + origPackage.sharedUser.name
10746                                            + " differs from " + pkg.mSharedUserId);
10747                                    origPackage = null;
10748                                    continue;
10749                                }
10750                                // TODO: Add case when shared user id is added [b/28144775]
10751                            } else {
10752                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10753                                        + pkg.packageName + " to old name " + origPackage.name);
10754                            }
10755                            break;
10756                        }
10757                    }
10758                }
10759            }
10760
10761            if (mTransferedPackages.contains(pkg.packageName)) {
10762                Slog.w(TAG, "Package " + pkg.packageName
10763                        + " was transferred to another, but its .apk remains");
10764            }
10765
10766            // See comments in nonMutatedPs declaration
10767            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10768                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10769                if (foundPs != null) {
10770                    nonMutatedPs = new PackageSetting(foundPs);
10771                }
10772            }
10773
10774            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10775                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10776                if (foundPs != null) {
10777                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10778                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10779                }
10780            }
10781
10782            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10783            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10784                PackageManagerService.reportSettingsProblem(Log.WARN,
10785                        "Package " + pkg.packageName + " shared user changed from "
10786                                + (pkgSetting.sharedUser != null
10787                                        ? pkgSetting.sharedUser.name : "<nothing>")
10788                                + " to "
10789                                + (suid != null ? suid.name : "<nothing>")
10790                                + "; replacing with new");
10791                pkgSetting = null;
10792            }
10793            final PackageSetting oldPkgSetting =
10794                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10795            final PackageSetting disabledPkgSetting =
10796                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10797
10798            String[] usesStaticLibraries = null;
10799            if (pkg.usesStaticLibraries != null) {
10800                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10801                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10802            }
10803
10804            if (pkgSetting == null) {
10805                final String parentPackageName = (pkg.parentPackage != null)
10806                        ? pkg.parentPackage.packageName : null;
10807                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10808                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10809                // REMOVE SharedUserSetting from method; update in a separate call
10810                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10811                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10812                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10813                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10814                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10815                        true /*allowInstall*/, instantApp, virtualPreload,
10816                        parentPackageName, pkg.getChildPackageNames(),
10817                        UserManagerService.getInstance(), usesStaticLibraries,
10818                        pkg.usesStaticLibrariesVersions);
10819                // SIDE EFFECTS; updates system state; move elsewhere
10820                if (origPackage != null) {
10821                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10822                }
10823                mSettings.addUserToSettingLPw(pkgSetting);
10824            } else {
10825                // REMOVE SharedUserSetting from method; update in a separate call.
10826                //
10827                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10828                // secondaryCpuAbi are not known at this point so we always update them
10829                // to null here, only to reset them at a later point.
10830                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10831                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10832                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10833                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10834                        UserManagerService.getInstance(), usesStaticLibraries,
10835                        pkg.usesStaticLibrariesVersions);
10836            }
10837            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10838            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10839
10840            // SIDE EFFECTS; modifies system state; move elsewhere
10841            if (pkgSetting.origPackage != null) {
10842                // If we are first transitioning from an original package,
10843                // fix up the new package's name now.  We need to do this after
10844                // looking up the package under its new name, so getPackageLP
10845                // can take care of fiddling things correctly.
10846                pkg.setPackageName(origPackage.name);
10847
10848                // File a report about this.
10849                String msg = "New package " + pkgSetting.realName
10850                        + " renamed to replace old package " + pkgSetting.name;
10851                reportSettingsProblem(Log.WARN, msg);
10852
10853                // Make a note of it.
10854                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10855                    mTransferedPackages.add(origPackage.name);
10856                }
10857
10858                // No longer need to retain this.
10859                pkgSetting.origPackage = null;
10860            }
10861
10862            // SIDE EFFECTS; modifies system state; move elsewhere
10863            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10864                // Make a note of it.
10865                mTransferedPackages.add(pkg.packageName);
10866            }
10867
10868            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10869                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10870            }
10871
10872            if ((scanFlags & SCAN_BOOTING) == 0
10873                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10874                // Check all shared libraries and map to their actual file path.
10875                // We only do this here for apps not on a system dir, because those
10876                // are the only ones that can fail an install due to this.  We
10877                // will take care of the system apps by updating all of their
10878                // library paths after the scan is done. Also during the initial
10879                // scan don't update any libs as we do this wholesale after all
10880                // apps are scanned to avoid dependency based scanning.
10881                updateSharedLibrariesLPr(pkg, null);
10882            }
10883
10884            if (mFoundPolicyFile) {
10885                SELinuxMMAC.assignSeInfoValue(pkg);
10886            }
10887            pkg.applicationInfo.uid = pkgSetting.appId;
10888            pkg.mExtras = pkgSetting;
10889
10890
10891            // Static shared libs have same package with different versions where
10892            // we internally use a synthetic package name to allow multiple versions
10893            // of the same package, therefore we need to compare signatures against
10894            // the package setting for the latest library version.
10895            PackageSetting signatureCheckPs = pkgSetting;
10896            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10897                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10898                if (libraryEntry != null) {
10899                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10900                }
10901            }
10902
10903            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10904                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10905                    // We just determined the app is signed correctly, so bring
10906                    // over the latest parsed certs.
10907                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10908                } else {
10909                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10910                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10911                                "Package " + pkg.packageName + " upgrade keys do not match the "
10912                                + "previously installed version");
10913                    } else {
10914                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10915                        String msg = "System package " + pkg.packageName
10916                                + " signature changed; retaining data.";
10917                        reportSettingsProblem(Log.WARN, msg);
10918                    }
10919                }
10920            } else {
10921                try {
10922                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10923                    verifySignaturesLP(signatureCheckPs, pkg);
10924                    // We just determined the app is signed correctly, so bring
10925                    // over the latest parsed certs.
10926                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10927                } catch (PackageManagerException e) {
10928                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10929                        throw e;
10930                    }
10931                    // The signature has changed, but this package is in the system
10932                    // image...  let's recover!
10933                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10934                    // However...  if this package is part of a shared user, but it
10935                    // doesn't match the signature of the shared user, let's fail.
10936                    // What this means is that you can't change the signatures
10937                    // associated with an overall shared user, which doesn't seem all
10938                    // that unreasonable.
10939                    if (signatureCheckPs.sharedUser != null) {
10940                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10941                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10942                            throw new PackageManagerException(
10943                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10944                                    "Signature mismatch for shared user: "
10945                                            + pkgSetting.sharedUser);
10946                        }
10947                    }
10948                    // File a report about this.
10949                    String msg = "System package " + pkg.packageName
10950                            + " signature changed; retaining data.";
10951                    reportSettingsProblem(Log.WARN, msg);
10952                }
10953            }
10954
10955            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10956                // This package wants to adopt ownership of permissions from
10957                // another package.
10958                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10959                    final String origName = pkg.mAdoptPermissions.get(i);
10960                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10961                    if (orig != null) {
10962                        if (verifyPackageUpdateLPr(orig, pkg)) {
10963                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10964                                    + pkg.packageName);
10965                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10966                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10967                        }
10968                    }
10969                }
10970            }
10971        }
10972
10973        pkg.applicationInfo.processName = fixProcessName(
10974                pkg.applicationInfo.packageName,
10975                pkg.applicationInfo.processName);
10976
10977        if (pkg != mPlatformPackage) {
10978            // Get all of our default paths setup
10979            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10980        }
10981
10982        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10983
10984        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10985            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10986                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10987                final boolean extractNativeLibs = !pkg.isLibrary();
10988                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10989                        mAppLib32InstallDir);
10990                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10991
10992                // Some system apps still use directory structure for native libraries
10993                // in which case we might end up not detecting abi solely based on apk
10994                // structure. Try to detect abi based on directory structure.
10995                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10996                        pkg.applicationInfo.primaryCpuAbi == null) {
10997                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10998                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10999                }
11000            } else {
11001                // This is not a first boot or an upgrade, don't bother deriving the
11002                // ABI during the scan. Instead, trust the value that was stored in the
11003                // package setting.
11004                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11005                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11006
11007                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11008
11009                if (DEBUG_ABI_SELECTION) {
11010                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11011                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11012                        pkg.applicationInfo.secondaryCpuAbi);
11013                }
11014            }
11015        } else {
11016            if ((scanFlags & SCAN_MOVE) != 0) {
11017                // We haven't run dex-opt for this move (since we've moved the compiled output too)
11018                // but we already have this packages package info in the PackageSetting. We just
11019                // use that and derive the native library path based on the new codepath.
11020                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11021                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11022            }
11023
11024            // Set native library paths again. For moves, the path will be updated based on the
11025            // ABIs we've determined above. For non-moves, the path will be updated based on the
11026            // ABIs we determined during compilation, but the path will depend on the final
11027            // package path (after the rename away from the stage path).
11028            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
11029        }
11030
11031        // This is a special case for the "system" package, where the ABI is
11032        // dictated by the zygote configuration (and init.rc). We should keep track
11033        // of this ABI so that we can deal with "normal" applications that run under
11034        // the same UID correctly.
11035        if (mPlatformPackage == pkg) {
11036            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11037                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11038        }
11039
11040        // If there's a mismatch between the abi-override in the package setting
11041        // and the abiOverride specified for the install. Warn about this because we
11042        // would've already compiled the app without taking the package setting into
11043        // account.
11044        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11045            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
11046                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11047                        " for package " + pkg.packageName);
11048            }
11049        }
11050
11051        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11052        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11053        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11054
11055        // Copy the derived override back to the parsed package, so that we can
11056        // update the package settings accordingly.
11057        pkg.cpuAbiOverride = cpuAbiOverride;
11058
11059        if (DEBUG_ABI_SELECTION) {
11060            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
11061                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11062                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11063        }
11064
11065        // Push the derived path down into PackageSettings so we know what to
11066        // clean up at uninstall time.
11067        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11068
11069        if (DEBUG_ABI_SELECTION) {
11070            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11071                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
11072                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11073        }
11074
11075        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
11076        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11077            // We don't do this here during boot because we can do it all
11078            // at once after scanning all existing packages.
11079            //
11080            // We also do this *before* we perform dexopt on this package, so that
11081            // we can avoid redundant dexopts, and also to make sure we've got the
11082            // code and package path correct.
11083            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11084        }
11085
11086        if (mFactoryTest && pkg.requestedPermissions.contains(
11087                android.Manifest.permission.FACTORY_TEST)) {
11088            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11089        }
11090
11091        if (isSystemApp(pkg)) {
11092            pkgSetting.isOrphaned = true;
11093        }
11094
11095        // Take care of first install / last update times.
11096        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
11097        if (currentTime != 0) {
11098            if (pkgSetting.firstInstallTime == 0) {
11099                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11100            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11101                pkgSetting.lastUpdateTime = currentTime;
11102            }
11103        } else if (pkgSetting.firstInstallTime == 0) {
11104            // We need *something*.  Take time time stamp of the file.
11105            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11106        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11107            if (scanFileTime != pkgSetting.timeStamp) {
11108                // A package on the system image has changed; consider this
11109                // to be an update.
11110                pkgSetting.lastUpdateTime = scanFileTime;
11111            }
11112        }
11113        pkgSetting.setTimeStamp(scanFileTime);
11114
11115        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11116            if (nonMutatedPs != null) {
11117                synchronized (mPackages) {
11118                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11119                }
11120            }
11121        } else {
11122            final int userId = user == null ? 0 : user.getIdentifier();
11123            // Modify state for the given package setting
11124            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11125                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11126            if (pkgSetting.getInstantApp(userId)) {
11127                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11128            }
11129        }
11130        return pkg;
11131    }
11132
11133    /**
11134     * Applies policy to the parsed package based upon the given policy flags.
11135     * Ensures the package is in a good state.
11136     * <p>
11137     * Implementation detail: This method must NOT have any side effect. It would
11138     * ideally be static, but, it requires locks to read system state.
11139     */
11140    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11141        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11142            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11143            if (pkg.applicationInfo.isDirectBootAware()) {
11144                // we're direct boot aware; set for all components
11145                for (PackageParser.Service s : pkg.services) {
11146                    s.info.encryptionAware = s.info.directBootAware = true;
11147                }
11148                for (PackageParser.Provider p : pkg.providers) {
11149                    p.info.encryptionAware = p.info.directBootAware = true;
11150                }
11151                for (PackageParser.Activity a : pkg.activities) {
11152                    a.info.encryptionAware = a.info.directBootAware = true;
11153                }
11154                for (PackageParser.Activity r : pkg.receivers) {
11155                    r.info.encryptionAware = r.info.directBootAware = true;
11156                }
11157            }
11158            if (compressedFileExists(pkg.codePath)) {
11159                pkg.isStub = true;
11160            }
11161        } else {
11162            // Only allow system apps to be flagged as core apps.
11163            pkg.coreApp = false;
11164            // clear flags not applicable to regular apps
11165            pkg.applicationInfo.privateFlags &=
11166                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11167            pkg.applicationInfo.privateFlags &=
11168                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11169        }
11170        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11171
11172        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11173            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11174        }
11175
11176        if (!isSystemApp(pkg)) {
11177            // Only system apps can use these features.
11178            pkg.mOriginalPackages = null;
11179            pkg.mRealPackage = null;
11180            pkg.mAdoptPermissions = null;
11181        }
11182    }
11183
11184    /**
11185     * Asserts the parsed package is valid according to the given policy. If the
11186     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11187     * <p>
11188     * Implementation detail: This method must NOT have any side effects. It would
11189     * ideally be static, but, it requires locks to read system state.
11190     *
11191     * @throws PackageManagerException If the package fails any of the validation checks
11192     */
11193    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11194            throws PackageManagerException {
11195        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11196            assertCodePolicy(pkg);
11197        }
11198
11199        if (pkg.applicationInfo.getCodePath() == null ||
11200                pkg.applicationInfo.getResourcePath() == null) {
11201            // Bail out. The resource and code paths haven't been set.
11202            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11203                    "Code and resource paths haven't been set correctly");
11204        }
11205
11206        // Make sure we're not adding any bogus keyset info
11207        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11208        ksms.assertScannedPackageValid(pkg);
11209
11210        synchronized (mPackages) {
11211            // The special "android" package can only be defined once
11212            if (pkg.packageName.equals("android")) {
11213                if (mAndroidApplication != null) {
11214                    Slog.w(TAG, "*************************************************");
11215                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11216                    Slog.w(TAG, " codePath=" + pkg.codePath);
11217                    Slog.w(TAG, "*************************************************");
11218                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11219                            "Core android package being redefined.  Skipping.");
11220                }
11221            }
11222
11223            // A package name must be unique; don't allow duplicates
11224            if (mPackages.containsKey(pkg.packageName)) {
11225                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11226                        "Application package " + pkg.packageName
11227                        + " already installed.  Skipping duplicate.");
11228            }
11229
11230            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11231                // Static libs have a synthetic package name containing the version
11232                // but we still want the base name to be unique.
11233                if (mPackages.containsKey(pkg.manifestPackageName)) {
11234                    throw new PackageManagerException(
11235                            "Duplicate static shared lib provider package");
11236                }
11237
11238                // Static shared libraries should have at least O target SDK
11239                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11240                    throw new PackageManagerException(
11241                            "Packages declaring static-shared libs must target O SDK or higher");
11242                }
11243
11244                // Package declaring static a shared lib cannot be instant apps
11245                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11246                    throw new PackageManagerException(
11247                            "Packages declaring static-shared libs cannot be instant apps");
11248                }
11249
11250                // Package declaring static a shared lib cannot be renamed since the package
11251                // name is synthetic and apps can't code around package manager internals.
11252                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11253                    throw new PackageManagerException(
11254                            "Packages declaring static-shared libs cannot be renamed");
11255                }
11256
11257                // Package declaring static a shared lib cannot declare child packages
11258                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11259                    throw new PackageManagerException(
11260                            "Packages declaring static-shared libs cannot have child packages");
11261                }
11262
11263                // Package declaring static a shared lib cannot declare dynamic libs
11264                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11265                    throw new PackageManagerException(
11266                            "Packages declaring static-shared libs cannot declare dynamic libs");
11267                }
11268
11269                // Package declaring static a shared lib cannot declare shared users
11270                if (pkg.mSharedUserId != null) {
11271                    throw new PackageManagerException(
11272                            "Packages declaring static-shared libs cannot declare shared users");
11273                }
11274
11275                // Static shared libs cannot declare activities
11276                if (!pkg.activities.isEmpty()) {
11277                    throw new PackageManagerException(
11278                            "Static shared libs cannot declare activities");
11279                }
11280
11281                // Static shared libs cannot declare services
11282                if (!pkg.services.isEmpty()) {
11283                    throw new PackageManagerException(
11284                            "Static shared libs cannot declare services");
11285                }
11286
11287                // Static shared libs cannot declare providers
11288                if (!pkg.providers.isEmpty()) {
11289                    throw new PackageManagerException(
11290                            "Static shared libs cannot declare content providers");
11291                }
11292
11293                // Static shared libs cannot declare receivers
11294                if (!pkg.receivers.isEmpty()) {
11295                    throw new PackageManagerException(
11296                            "Static shared libs cannot declare broadcast receivers");
11297                }
11298
11299                // Static shared libs cannot declare permission groups
11300                if (!pkg.permissionGroups.isEmpty()) {
11301                    throw new PackageManagerException(
11302                            "Static shared libs cannot declare permission groups");
11303                }
11304
11305                // Static shared libs cannot declare permissions
11306                if (!pkg.permissions.isEmpty()) {
11307                    throw new PackageManagerException(
11308                            "Static shared libs cannot declare permissions");
11309                }
11310
11311                // Static shared libs cannot declare protected broadcasts
11312                if (pkg.protectedBroadcasts != null) {
11313                    throw new PackageManagerException(
11314                            "Static shared libs cannot declare protected broadcasts");
11315                }
11316
11317                // Static shared libs cannot be overlay targets
11318                if (pkg.mOverlayTarget != null) {
11319                    throw new PackageManagerException(
11320                            "Static shared libs cannot be overlay targets");
11321                }
11322
11323                // The version codes must be ordered as lib versions
11324                int minVersionCode = Integer.MIN_VALUE;
11325                int maxVersionCode = Integer.MAX_VALUE;
11326
11327                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11328                        pkg.staticSharedLibName);
11329                if (versionedLib != null) {
11330                    final int versionCount = versionedLib.size();
11331                    for (int i = 0; i < versionCount; i++) {
11332                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11333                        final int libVersionCode = libInfo.getDeclaringPackage()
11334                                .getVersionCode();
11335                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11336                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11337                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11338                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11339                        } else {
11340                            minVersionCode = maxVersionCode = libVersionCode;
11341                            break;
11342                        }
11343                    }
11344                }
11345                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11346                    throw new PackageManagerException("Static shared"
11347                            + " lib version codes must be ordered as lib versions");
11348                }
11349            }
11350
11351            // Only privileged apps and updated privileged apps can add child packages.
11352            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11353                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11354                    throw new PackageManagerException("Only privileged apps can add child "
11355                            + "packages. Ignoring package " + pkg.packageName);
11356                }
11357                final int childCount = pkg.childPackages.size();
11358                for (int i = 0; i < childCount; i++) {
11359                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11360                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11361                            childPkg.packageName)) {
11362                        throw new PackageManagerException("Can't override child of "
11363                                + "another disabled app. Ignoring package " + pkg.packageName);
11364                    }
11365                }
11366            }
11367
11368            // If we're only installing presumed-existing packages, require that the
11369            // scanned APK is both already known and at the path previously established
11370            // for it.  Previously unknown packages we pick up normally, but if we have an
11371            // a priori expectation about this package's install presence, enforce it.
11372            // With a singular exception for new system packages. When an OTA contains
11373            // a new system package, we allow the codepath to change from a system location
11374            // to the user-installed location. If we don't allow this change, any newer,
11375            // user-installed version of the application will be ignored.
11376            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11377                if (mExpectingBetter.containsKey(pkg.packageName)) {
11378                    logCriticalInfo(Log.WARN,
11379                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11380                } else {
11381                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11382                    if (known != null) {
11383                        if (DEBUG_PACKAGE_SCANNING) {
11384                            Log.d(TAG, "Examining " + pkg.codePath
11385                                    + " and requiring known paths " + known.codePathString
11386                                    + " & " + known.resourcePathString);
11387                        }
11388                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11389                                || !pkg.applicationInfo.getResourcePath().equals(
11390                                        known.resourcePathString)) {
11391                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11392                                    "Application package " + pkg.packageName
11393                                    + " found at " + pkg.applicationInfo.getCodePath()
11394                                    + " but expected at " + known.codePathString
11395                                    + "; ignoring.");
11396                        }
11397                    }
11398                }
11399            }
11400
11401            // Verify that this new package doesn't have any content providers
11402            // that conflict with existing packages.  Only do this if the
11403            // package isn't already installed, since we don't want to break
11404            // things that are installed.
11405            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11406                final int N = pkg.providers.size();
11407                int i;
11408                for (i=0; i<N; i++) {
11409                    PackageParser.Provider p = pkg.providers.get(i);
11410                    if (p.info.authority != null) {
11411                        String names[] = p.info.authority.split(";");
11412                        for (int j = 0; j < names.length; j++) {
11413                            if (mProvidersByAuthority.containsKey(names[j])) {
11414                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11415                                final String otherPackageName =
11416                                        ((other != null && other.getComponentName() != null) ?
11417                                                other.getComponentName().getPackageName() : "?");
11418                                throw new PackageManagerException(
11419                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11420                                        "Can't install because provider name " + names[j]
11421                                                + " (in package " + pkg.applicationInfo.packageName
11422                                                + ") is already used by " + otherPackageName);
11423                            }
11424                        }
11425                    }
11426                }
11427            }
11428        }
11429    }
11430
11431    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11432            int type, String declaringPackageName, int declaringVersionCode) {
11433        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11434        if (versionedLib == null) {
11435            versionedLib = new SparseArray<>();
11436            mSharedLibraries.put(name, versionedLib);
11437            if (type == SharedLibraryInfo.TYPE_STATIC) {
11438                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11439            }
11440        } else if (versionedLib.indexOfKey(version) >= 0) {
11441            return false;
11442        }
11443        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11444                version, type, declaringPackageName, declaringVersionCode);
11445        versionedLib.put(version, libEntry);
11446        return true;
11447    }
11448
11449    private boolean removeSharedLibraryLPw(String name, int version) {
11450        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11451        if (versionedLib == null) {
11452            return false;
11453        }
11454        final int libIdx = versionedLib.indexOfKey(version);
11455        if (libIdx < 0) {
11456            return false;
11457        }
11458        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11459        versionedLib.remove(version);
11460        if (versionedLib.size() <= 0) {
11461            mSharedLibraries.remove(name);
11462            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11463                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11464                        .getPackageName());
11465            }
11466        }
11467        return true;
11468    }
11469
11470    /**
11471     * Adds a scanned package to the system. When this method is finished, the package will
11472     * be available for query, resolution, etc...
11473     */
11474    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11475            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11476        final String pkgName = pkg.packageName;
11477        if (mCustomResolverComponentName != null &&
11478                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11479            setUpCustomResolverActivity(pkg);
11480        }
11481
11482        if (pkg.packageName.equals("android")) {
11483            synchronized (mPackages) {
11484                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11485                    // Set up information for our fall-back user intent resolution activity.
11486                    mPlatformPackage = pkg;
11487                    pkg.mVersionCode = mSdkVersion;
11488                    mAndroidApplication = pkg.applicationInfo;
11489                    if (!mResolverReplaced) {
11490                        mResolveActivity.applicationInfo = mAndroidApplication;
11491                        mResolveActivity.name = ResolverActivity.class.getName();
11492                        mResolveActivity.packageName = mAndroidApplication.packageName;
11493                        mResolveActivity.processName = "system:ui";
11494                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11495                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11496                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11497                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11498                        mResolveActivity.exported = true;
11499                        mResolveActivity.enabled = true;
11500                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11501                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11502                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11503                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11504                                | ActivityInfo.CONFIG_ORIENTATION
11505                                | ActivityInfo.CONFIG_KEYBOARD
11506                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11507                        mResolveInfo.activityInfo = mResolveActivity;
11508                        mResolveInfo.priority = 0;
11509                        mResolveInfo.preferredOrder = 0;
11510                        mResolveInfo.match = 0;
11511                        mResolveComponentName = new ComponentName(
11512                                mAndroidApplication.packageName, mResolveActivity.name);
11513                    }
11514                }
11515            }
11516        }
11517
11518        ArrayList<PackageParser.Package> clientLibPkgs = null;
11519        // writer
11520        synchronized (mPackages) {
11521            boolean hasStaticSharedLibs = false;
11522
11523            // Any app can add new static shared libraries
11524            if (pkg.staticSharedLibName != null) {
11525                // Static shared libs don't allow renaming as they have synthetic package
11526                // names to allow install of multiple versions, so use name from manifest.
11527                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11528                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11529                        pkg.manifestPackageName, pkg.mVersionCode)) {
11530                    hasStaticSharedLibs = true;
11531                } else {
11532                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11533                                + pkg.staticSharedLibName + " already exists; skipping");
11534                }
11535                // Static shared libs cannot be updated once installed since they
11536                // use synthetic package name which includes the version code, so
11537                // not need to update other packages's shared lib dependencies.
11538            }
11539
11540            if (!hasStaticSharedLibs
11541                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11542                // Only system apps can add new dynamic shared libraries.
11543                if (pkg.libraryNames != null) {
11544                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11545                        String name = pkg.libraryNames.get(i);
11546                        boolean allowed = false;
11547                        if (pkg.isUpdatedSystemApp()) {
11548                            // New library entries can only be added through the
11549                            // system image.  This is important to get rid of a lot
11550                            // of nasty edge cases: for example if we allowed a non-
11551                            // system update of the app to add a library, then uninstalling
11552                            // the update would make the library go away, and assumptions
11553                            // we made such as through app install filtering would now
11554                            // have allowed apps on the device which aren't compatible
11555                            // with it.  Better to just have the restriction here, be
11556                            // conservative, and create many fewer cases that can negatively
11557                            // impact the user experience.
11558                            final PackageSetting sysPs = mSettings
11559                                    .getDisabledSystemPkgLPr(pkg.packageName);
11560                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11561                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11562                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11563                                        allowed = true;
11564                                        break;
11565                                    }
11566                                }
11567                            }
11568                        } else {
11569                            allowed = true;
11570                        }
11571                        if (allowed) {
11572                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11573                                    SharedLibraryInfo.VERSION_UNDEFINED,
11574                                    SharedLibraryInfo.TYPE_DYNAMIC,
11575                                    pkg.packageName, pkg.mVersionCode)) {
11576                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11577                                        + name + " already exists; skipping");
11578                            }
11579                        } else {
11580                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11581                                    + name + " that is not declared on system image; skipping");
11582                        }
11583                    }
11584
11585                    if ((scanFlags & SCAN_BOOTING) == 0) {
11586                        // If we are not booting, we need to update any applications
11587                        // that are clients of our shared library.  If we are booting,
11588                        // this will all be done once the scan is complete.
11589                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11590                    }
11591                }
11592            }
11593        }
11594
11595        if ((scanFlags & SCAN_BOOTING) != 0) {
11596            // No apps can run during boot scan, so they don't need to be frozen
11597        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11598            // Caller asked to not kill app, so it's probably not frozen
11599        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11600            // Caller asked us to ignore frozen check for some reason; they
11601            // probably didn't know the package name
11602        } else {
11603            // We're doing major surgery on this package, so it better be frozen
11604            // right now to keep it from launching
11605            checkPackageFrozen(pkgName);
11606        }
11607
11608        // Also need to kill any apps that are dependent on the library.
11609        if (clientLibPkgs != null) {
11610            for (int i=0; i<clientLibPkgs.size(); i++) {
11611                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11612                killApplication(clientPkg.applicationInfo.packageName,
11613                        clientPkg.applicationInfo.uid, "update lib");
11614            }
11615        }
11616
11617        // writer
11618        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11619
11620        synchronized (mPackages) {
11621            // We don't expect installation to fail beyond this point
11622
11623            // Add the new setting to mSettings
11624            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11625            // Add the new setting to mPackages
11626            mPackages.put(pkg.applicationInfo.packageName, pkg);
11627            // Make sure we don't accidentally delete its data.
11628            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11629            while (iter.hasNext()) {
11630                PackageCleanItem item = iter.next();
11631                if (pkgName.equals(item.packageName)) {
11632                    iter.remove();
11633                }
11634            }
11635
11636            // Add the package's KeySets to the global KeySetManagerService
11637            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11638            ksms.addScannedPackageLPw(pkg);
11639
11640            int N = pkg.providers.size();
11641            StringBuilder r = null;
11642            int i;
11643            for (i=0; i<N; i++) {
11644                PackageParser.Provider p = pkg.providers.get(i);
11645                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11646                        p.info.processName);
11647                mProviders.addProvider(p);
11648                p.syncable = p.info.isSyncable;
11649                if (p.info.authority != null) {
11650                    String names[] = p.info.authority.split(";");
11651                    p.info.authority = null;
11652                    for (int j = 0; j < names.length; j++) {
11653                        if (j == 1 && p.syncable) {
11654                            // We only want the first authority for a provider to possibly be
11655                            // syncable, so if we already added this provider using a different
11656                            // authority clear the syncable flag. We copy the provider before
11657                            // changing it because the mProviders object contains a reference
11658                            // to a provider that we don't want to change.
11659                            // Only do this for the second authority since the resulting provider
11660                            // object can be the same for all future authorities for this provider.
11661                            p = new PackageParser.Provider(p);
11662                            p.syncable = false;
11663                        }
11664                        if (!mProvidersByAuthority.containsKey(names[j])) {
11665                            mProvidersByAuthority.put(names[j], p);
11666                            if (p.info.authority == null) {
11667                                p.info.authority = names[j];
11668                            } else {
11669                                p.info.authority = p.info.authority + ";" + names[j];
11670                            }
11671                            if (DEBUG_PACKAGE_SCANNING) {
11672                                if (chatty)
11673                                    Log.d(TAG, "Registered content provider: " + names[j]
11674                                            + ", className = " + p.info.name + ", isSyncable = "
11675                                            + p.info.isSyncable);
11676                            }
11677                        } else {
11678                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11679                            Slog.w(TAG, "Skipping provider name " + names[j] +
11680                                    " (in package " + pkg.applicationInfo.packageName +
11681                                    "): name already used by "
11682                                    + ((other != null && other.getComponentName() != null)
11683                                            ? other.getComponentName().getPackageName() : "?"));
11684                        }
11685                    }
11686                }
11687                if (chatty) {
11688                    if (r == null) {
11689                        r = new StringBuilder(256);
11690                    } else {
11691                        r.append(' ');
11692                    }
11693                    r.append(p.info.name);
11694                }
11695            }
11696            if (r != null) {
11697                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11698            }
11699
11700            N = pkg.services.size();
11701            r = null;
11702            for (i=0; i<N; i++) {
11703                PackageParser.Service s = pkg.services.get(i);
11704                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11705                        s.info.processName);
11706                mServices.addService(s);
11707                if (chatty) {
11708                    if (r == null) {
11709                        r = new StringBuilder(256);
11710                    } else {
11711                        r.append(' ');
11712                    }
11713                    r.append(s.info.name);
11714                }
11715            }
11716            if (r != null) {
11717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11718            }
11719
11720            N = pkg.receivers.size();
11721            r = null;
11722            for (i=0; i<N; i++) {
11723                PackageParser.Activity a = pkg.receivers.get(i);
11724                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11725                        a.info.processName);
11726                mReceivers.addActivity(a, "receiver");
11727                if (chatty) {
11728                    if (r == null) {
11729                        r = new StringBuilder(256);
11730                    } else {
11731                        r.append(' ');
11732                    }
11733                    r.append(a.info.name);
11734                }
11735            }
11736            if (r != null) {
11737                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11738            }
11739
11740            N = pkg.activities.size();
11741            r = null;
11742            for (i=0; i<N; i++) {
11743                PackageParser.Activity a = pkg.activities.get(i);
11744                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11745                        a.info.processName);
11746                mActivities.addActivity(a, "activity");
11747                if (chatty) {
11748                    if (r == null) {
11749                        r = new StringBuilder(256);
11750                    } else {
11751                        r.append(' ');
11752                    }
11753                    r.append(a.info.name);
11754                }
11755            }
11756            if (r != null) {
11757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11758            }
11759
11760            N = pkg.permissionGroups.size();
11761            r = null;
11762            for (i=0; i<N; i++) {
11763                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11764                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11765                final String curPackageName = cur == null ? null : cur.info.packageName;
11766                // Dont allow ephemeral apps to define new permission groups.
11767                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11768                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11769                            + pg.info.packageName
11770                            + " ignored: instant apps cannot define new permission groups.");
11771                    continue;
11772                }
11773                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11774                if (cur == null || isPackageUpdate) {
11775                    mPermissionGroups.put(pg.info.name, pg);
11776                    if (chatty) {
11777                        if (r == null) {
11778                            r = new StringBuilder(256);
11779                        } else {
11780                            r.append(' ');
11781                        }
11782                        if (isPackageUpdate) {
11783                            r.append("UPD:");
11784                        }
11785                        r.append(pg.info.name);
11786                    }
11787                } else {
11788                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11789                            + pg.info.packageName + " ignored: original from "
11790                            + cur.info.packageName);
11791                    if (chatty) {
11792                        if (r == null) {
11793                            r = new StringBuilder(256);
11794                        } else {
11795                            r.append(' ');
11796                        }
11797                        r.append("DUP:");
11798                        r.append(pg.info.name);
11799                    }
11800                }
11801            }
11802            if (r != null) {
11803                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11804            }
11805
11806            N = pkg.permissions.size();
11807            r = null;
11808            for (i=0; i<N; i++) {
11809                PackageParser.Permission p = pkg.permissions.get(i);
11810
11811                // Dont allow ephemeral apps to define new permissions.
11812                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11813                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11814                            + p.info.packageName
11815                            + " ignored: instant apps cannot define new permissions.");
11816                    continue;
11817                }
11818
11819                // Assume by default that we did not install this permission into the system.
11820                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11821
11822                // Now that permission groups have a special meaning, we ignore permission
11823                // groups for legacy apps to prevent unexpected behavior. In particular,
11824                // permissions for one app being granted to someone just because they happen
11825                // to be in a group defined by another app (before this had no implications).
11826                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11827                    p.group = mPermissionGroups.get(p.info.group);
11828                    // Warn for a permission in an unknown group.
11829                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11830                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11831                                + p.info.packageName + " in an unknown group " + p.info.group);
11832                    }
11833                }
11834
11835                ArrayMap<String, BasePermission> permissionMap =
11836                        p.tree ? mSettings.mPermissionTrees
11837                                : mSettings.mPermissions;
11838                BasePermission bp = permissionMap.get(p.info.name);
11839
11840                // Allow system apps to redefine non-system permissions
11841                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11842                    final boolean currentOwnerIsSystem = (bp.perm != null
11843                            && isSystemApp(bp.perm.owner));
11844                    if (isSystemApp(p.owner)) {
11845                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11846                            // It's a built-in permission and no owner, take ownership now
11847                            bp.packageSetting = pkgSetting;
11848                            bp.perm = p;
11849                            bp.uid = pkg.applicationInfo.uid;
11850                            bp.sourcePackage = p.info.packageName;
11851                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11852                        } else if (!currentOwnerIsSystem) {
11853                            String msg = "New decl " + p.owner + " of permission  "
11854                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11855                            reportSettingsProblem(Log.WARN, msg);
11856                            bp = null;
11857                        }
11858                    }
11859                }
11860
11861                if (bp == null) {
11862                    bp = new BasePermission(p.info.name, p.info.packageName,
11863                            BasePermission.TYPE_NORMAL);
11864                    permissionMap.put(p.info.name, bp);
11865                }
11866
11867                if (bp.perm == null) {
11868                    if (bp.sourcePackage == null
11869                            || bp.sourcePackage.equals(p.info.packageName)) {
11870                        BasePermission tree = findPermissionTreeLP(p.info.name);
11871                        if (tree == null
11872                                || tree.sourcePackage.equals(p.info.packageName)) {
11873                            bp.packageSetting = pkgSetting;
11874                            bp.perm = p;
11875                            bp.uid = pkg.applicationInfo.uid;
11876                            bp.sourcePackage = p.info.packageName;
11877                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11878                            if (chatty) {
11879                                if (r == null) {
11880                                    r = new StringBuilder(256);
11881                                } else {
11882                                    r.append(' ');
11883                                }
11884                                r.append(p.info.name);
11885                            }
11886                        } else {
11887                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11888                                    + p.info.packageName + " ignored: base tree "
11889                                    + tree.name + " is from package "
11890                                    + tree.sourcePackage);
11891                        }
11892                    } else {
11893                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11894                                + p.info.packageName + " ignored: original from "
11895                                + bp.sourcePackage);
11896                    }
11897                } else if (chatty) {
11898                    if (r == null) {
11899                        r = new StringBuilder(256);
11900                    } else {
11901                        r.append(' ');
11902                    }
11903                    r.append("DUP:");
11904                    r.append(p.info.name);
11905                }
11906                if (bp.perm == p) {
11907                    bp.protectionLevel = p.info.protectionLevel;
11908                }
11909            }
11910
11911            if (r != null) {
11912                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11913            }
11914
11915            N = pkg.instrumentation.size();
11916            r = null;
11917            for (i=0; i<N; i++) {
11918                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11919                a.info.packageName = pkg.applicationInfo.packageName;
11920                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11921                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11922                a.info.splitNames = pkg.splitNames;
11923                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11924                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11925                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11926                a.info.dataDir = pkg.applicationInfo.dataDir;
11927                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11928                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11929                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11930                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11931                mInstrumentation.put(a.getComponentName(), a);
11932                if (chatty) {
11933                    if (r == null) {
11934                        r = new StringBuilder(256);
11935                    } else {
11936                        r.append(' ');
11937                    }
11938                    r.append(a.info.name);
11939                }
11940            }
11941            if (r != null) {
11942                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11943            }
11944
11945            if (pkg.protectedBroadcasts != null) {
11946                N = pkg.protectedBroadcasts.size();
11947                synchronized (mProtectedBroadcasts) {
11948                    for (i = 0; i < N; i++) {
11949                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11950                    }
11951                }
11952            }
11953        }
11954
11955        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11956    }
11957
11958    /**
11959     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11960     * is derived purely on the basis of the contents of {@code scanFile} and
11961     * {@code cpuAbiOverride}.
11962     *
11963     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11964     */
11965    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11966                                 String cpuAbiOverride, boolean extractLibs,
11967                                 File appLib32InstallDir)
11968            throws PackageManagerException {
11969        // Give ourselves some initial paths; we'll come back for another
11970        // pass once we've determined ABI below.
11971        setNativeLibraryPaths(pkg, appLib32InstallDir);
11972
11973        // We would never need to extract libs for forward-locked and external packages,
11974        // since the container service will do it for us. We shouldn't attempt to
11975        // extract libs from system app when it was not updated.
11976        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11977                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11978            extractLibs = false;
11979        }
11980
11981        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11982        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11983
11984        NativeLibraryHelper.Handle handle = null;
11985        try {
11986            handle = NativeLibraryHelper.Handle.create(pkg);
11987            // TODO(multiArch): This can be null for apps that didn't go through the
11988            // usual installation process. We can calculate it again, like we
11989            // do during install time.
11990            //
11991            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11992            // unnecessary.
11993            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11994
11995            // Null out the abis so that they can be recalculated.
11996            pkg.applicationInfo.primaryCpuAbi = null;
11997            pkg.applicationInfo.secondaryCpuAbi = null;
11998            if (isMultiArch(pkg.applicationInfo)) {
11999                // Warn if we've set an abiOverride for multi-lib packages..
12000                // By definition, we need to copy both 32 and 64 bit libraries for
12001                // such packages.
12002                if (pkg.cpuAbiOverride != null
12003                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12004                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12005                }
12006
12007                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12008                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12009                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12010                    if (extractLibs) {
12011                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12012                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12013                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12014                                useIsaSpecificSubdirs);
12015                    } else {
12016                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12017                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12018                    }
12019                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12020                }
12021
12022                // Shared library native code should be in the APK zip aligned
12023                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12024                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12025                            "Shared library native lib extraction not supported");
12026                }
12027
12028                maybeThrowExceptionForMultiArchCopy(
12029                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12030
12031                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12032                    if (extractLibs) {
12033                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12034                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12035                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12036                                useIsaSpecificSubdirs);
12037                    } else {
12038                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12039                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12040                    }
12041                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12042                }
12043
12044                maybeThrowExceptionForMultiArchCopy(
12045                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12046
12047                if (abi64 >= 0) {
12048                    // Shared library native libs should be in the APK zip aligned
12049                    if (extractLibs && pkg.isLibrary()) {
12050                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12051                                "Shared library native lib extraction not supported");
12052                    }
12053                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12054                }
12055
12056                if (abi32 >= 0) {
12057                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12058                    if (abi64 >= 0) {
12059                        if (pkg.use32bitAbi) {
12060                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12061                            pkg.applicationInfo.primaryCpuAbi = abi;
12062                        } else {
12063                            pkg.applicationInfo.secondaryCpuAbi = abi;
12064                        }
12065                    } else {
12066                        pkg.applicationInfo.primaryCpuAbi = abi;
12067                    }
12068                }
12069            } else {
12070                String[] abiList = (cpuAbiOverride != null) ?
12071                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12072
12073                // Enable gross and lame hacks for apps that are built with old
12074                // SDK tools. We must scan their APKs for renderscript bitcode and
12075                // not launch them if it's present. Don't bother checking on devices
12076                // that don't have 64 bit support.
12077                boolean needsRenderScriptOverride = false;
12078                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12079                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12080                    abiList = Build.SUPPORTED_32_BIT_ABIS;
12081                    needsRenderScriptOverride = true;
12082                }
12083
12084                final int copyRet;
12085                if (extractLibs) {
12086                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12087                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12088                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12089                } else {
12090                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12091                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12092                }
12093                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12094
12095                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12096                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12097                            "Error unpackaging native libs for app, errorCode=" + copyRet);
12098                }
12099
12100                if (copyRet >= 0) {
12101                    // Shared libraries that have native libs must be multi-architecture
12102                    if (pkg.isLibrary()) {
12103                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12104                                "Shared library with native libs must be multiarch");
12105                    }
12106                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12107                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12108                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12109                } else if (needsRenderScriptOverride) {
12110                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12111                }
12112            }
12113        } catch (IOException ioe) {
12114            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12115        } finally {
12116            IoUtils.closeQuietly(handle);
12117        }
12118
12119        // Now that we've calculated the ABIs and determined if it's an internal app,
12120        // we will go ahead and populate the nativeLibraryPath.
12121        setNativeLibraryPaths(pkg, appLib32InstallDir);
12122    }
12123
12124    /**
12125     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12126     * i.e, so that all packages can be run inside a single process if required.
12127     *
12128     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12129     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12130     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12131     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12132     * updating a package that belongs to a shared user.
12133     *
12134     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12135     * adds unnecessary complexity.
12136     */
12137    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12138            PackageParser.Package scannedPackage) {
12139        String requiredInstructionSet = null;
12140        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12141            requiredInstructionSet = VMRuntime.getInstructionSet(
12142                     scannedPackage.applicationInfo.primaryCpuAbi);
12143        }
12144
12145        PackageSetting requirer = null;
12146        for (PackageSetting ps : packagesForUser) {
12147            // If packagesForUser contains scannedPackage, we skip it. This will happen
12148            // when scannedPackage is an update of an existing package. Without this check,
12149            // we will never be able to change the ABI of any package belonging to a shared
12150            // user, even if it's compatible with other packages.
12151            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12152                if (ps.primaryCpuAbiString == null) {
12153                    continue;
12154                }
12155
12156                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12157                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12158                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12159                    // this but there's not much we can do.
12160                    String errorMessage = "Instruction set mismatch, "
12161                            + ((requirer == null) ? "[caller]" : requirer)
12162                            + " requires " + requiredInstructionSet + " whereas " + ps
12163                            + " requires " + instructionSet;
12164                    Slog.w(TAG, errorMessage);
12165                }
12166
12167                if (requiredInstructionSet == null) {
12168                    requiredInstructionSet = instructionSet;
12169                    requirer = ps;
12170                }
12171            }
12172        }
12173
12174        if (requiredInstructionSet != null) {
12175            String adjustedAbi;
12176            if (requirer != null) {
12177                // requirer != null implies that either scannedPackage was null or that scannedPackage
12178                // did not require an ABI, in which case we have to adjust scannedPackage to match
12179                // the ABI of the set (which is the same as requirer's ABI)
12180                adjustedAbi = requirer.primaryCpuAbiString;
12181                if (scannedPackage != null) {
12182                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12183                }
12184            } else {
12185                // requirer == null implies that we're updating all ABIs in the set to
12186                // match scannedPackage.
12187                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12188            }
12189
12190            for (PackageSetting ps : packagesForUser) {
12191                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12192                    if (ps.primaryCpuAbiString != null) {
12193                        continue;
12194                    }
12195
12196                    ps.primaryCpuAbiString = adjustedAbi;
12197                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12198                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12199                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12200                        if (DEBUG_ABI_SELECTION) {
12201                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12202                                    + " (requirer="
12203                                    + (requirer != null ? requirer.pkg : "null")
12204                                    + ", scannedPackage="
12205                                    + (scannedPackage != null ? scannedPackage : "null")
12206                                    + ")");
12207                        }
12208                        try {
12209                            mInstaller.rmdex(ps.codePathString,
12210                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12211                        } catch (InstallerException ignored) {
12212                        }
12213                    }
12214                }
12215            }
12216        }
12217    }
12218
12219    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12220        synchronized (mPackages) {
12221            mResolverReplaced = true;
12222            // Set up information for custom user intent resolution activity.
12223            mResolveActivity.applicationInfo = pkg.applicationInfo;
12224            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12225            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12226            mResolveActivity.processName = pkg.applicationInfo.packageName;
12227            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12228            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12229                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12230            mResolveActivity.theme = 0;
12231            mResolveActivity.exported = true;
12232            mResolveActivity.enabled = true;
12233            mResolveInfo.activityInfo = mResolveActivity;
12234            mResolveInfo.priority = 0;
12235            mResolveInfo.preferredOrder = 0;
12236            mResolveInfo.match = 0;
12237            mResolveComponentName = mCustomResolverComponentName;
12238            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12239                    mResolveComponentName);
12240        }
12241    }
12242
12243    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12244        if (installerActivity == null) {
12245            if (DEBUG_EPHEMERAL) {
12246                Slog.d(TAG, "Clear ephemeral installer activity");
12247            }
12248            mInstantAppInstallerActivity = null;
12249            return;
12250        }
12251
12252        if (DEBUG_EPHEMERAL) {
12253            Slog.d(TAG, "Set ephemeral installer activity: "
12254                    + installerActivity.getComponentName());
12255        }
12256        // Set up information for ephemeral installer activity
12257        mInstantAppInstallerActivity = installerActivity;
12258        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12259                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12260        mInstantAppInstallerActivity.exported = true;
12261        mInstantAppInstallerActivity.enabled = true;
12262        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12263        mInstantAppInstallerInfo.priority = 0;
12264        mInstantAppInstallerInfo.preferredOrder = 1;
12265        mInstantAppInstallerInfo.isDefault = true;
12266        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12267                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12268    }
12269
12270    private static String calculateBundledApkRoot(final String codePathString) {
12271        final File codePath = new File(codePathString);
12272        final File codeRoot;
12273        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12274            codeRoot = Environment.getRootDirectory();
12275        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12276            codeRoot = Environment.getOemDirectory();
12277        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12278            codeRoot = Environment.getVendorDirectory();
12279        } else {
12280            // Unrecognized code path; take its top real segment as the apk root:
12281            // e.g. /something/app/blah.apk => /something
12282            try {
12283                File f = codePath.getCanonicalFile();
12284                File parent = f.getParentFile();    // non-null because codePath is a file
12285                File tmp;
12286                while ((tmp = parent.getParentFile()) != null) {
12287                    f = parent;
12288                    parent = tmp;
12289                }
12290                codeRoot = f;
12291                Slog.w(TAG, "Unrecognized code path "
12292                        + codePath + " - using " + codeRoot);
12293            } catch (IOException e) {
12294                // Can't canonicalize the code path -- shenanigans?
12295                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12296                return Environment.getRootDirectory().getPath();
12297            }
12298        }
12299        return codeRoot.getPath();
12300    }
12301
12302    /**
12303     * Derive and set the location of native libraries for the given package,
12304     * which varies depending on where and how the package was installed.
12305     */
12306    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12307        final ApplicationInfo info = pkg.applicationInfo;
12308        final String codePath = pkg.codePath;
12309        final File codeFile = new File(codePath);
12310        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12311        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12312
12313        info.nativeLibraryRootDir = null;
12314        info.nativeLibraryRootRequiresIsa = false;
12315        info.nativeLibraryDir = null;
12316        info.secondaryNativeLibraryDir = null;
12317
12318        if (isApkFile(codeFile)) {
12319            // Monolithic install
12320            if (bundledApp) {
12321                // If "/system/lib64/apkname" exists, assume that is the per-package
12322                // native library directory to use; otherwise use "/system/lib/apkname".
12323                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12324                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12325                        getPrimaryInstructionSet(info));
12326
12327                // This is a bundled system app so choose the path based on the ABI.
12328                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12329                // is just the default path.
12330                final String apkName = deriveCodePathName(codePath);
12331                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12332                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12333                        apkName).getAbsolutePath();
12334
12335                if (info.secondaryCpuAbi != null) {
12336                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12337                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12338                            secondaryLibDir, apkName).getAbsolutePath();
12339                }
12340            } else if (asecApp) {
12341                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12342                        .getAbsolutePath();
12343            } else {
12344                final String apkName = deriveCodePathName(codePath);
12345                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12346                        .getAbsolutePath();
12347            }
12348
12349            info.nativeLibraryRootRequiresIsa = false;
12350            info.nativeLibraryDir = info.nativeLibraryRootDir;
12351        } else {
12352            // Cluster install
12353            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12354            info.nativeLibraryRootRequiresIsa = true;
12355
12356            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12357                    getPrimaryInstructionSet(info)).getAbsolutePath();
12358
12359            if (info.secondaryCpuAbi != null) {
12360                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12361                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12362            }
12363        }
12364    }
12365
12366    /**
12367     * Calculate the abis and roots for a bundled app. These can uniquely
12368     * be determined from the contents of the system partition, i.e whether
12369     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12370     * of this information, and instead assume that the system was built
12371     * sensibly.
12372     */
12373    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12374                                           PackageSetting pkgSetting) {
12375        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12376
12377        // If "/system/lib64/apkname" exists, assume that is the per-package
12378        // native library directory to use; otherwise use "/system/lib/apkname".
12379        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12380        setBundledAppAbi(pkg, apkRoot, apkName);
12381        // pkgSetting might be null during rescan following uninstall of updates
12382        // to a bundled app, so accommodate that possibility.  The settings in
12383        // that case will be established later from the parsed package.
12384        //
12385        // If the settings aren't null, sync them up with what we've just derived.
12386        // note that apkRoot isn't stored in the package settings.
12387        if (pkgSetting != null) {
12388            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12389            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12390        }
12391    }
12392
12393    /**
12394     * Deduces the ABI of a bundled app and sets the relevant fields on the
12395     * parsed pkg object.
12396     *
12397     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12398     *        under which system libraries are installed.
12399     * @param apkName the name of the installed package.
12400     */
12401    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12402        final File codeFile = new File(pkg.codePath);
12403
12404        final boolean has64BitLibs;
12405        final boolean has32BitLibs;
12406        if (isApkFile(codeFile)) {
12407            // Monolithic install
12408            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12409            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12410        } else {
12411            // Cluster install
12412            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12413            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12414                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12415                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12416                has64BitLibs = (new File(rootDir, isa)).exists();
12417            } else {
12418                has64BitLibs = false;
12419            }
12420            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12421                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12422                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12423                has32BitLibs = (new File(rootDir, isa)).exists();
12424            } else {
12425                has32BitLibs = false;
12426            }
12427        }
12428
12429        if (has64BitLibs && !has32BitLibs) {
12430            // The package has 64 bit libs, but not 32 bit libs. Its primary
12431            // ABI should be 64 bit. We can safely assume here that the bundled
12432            // native libraries correspond to the most preferred ABI in the list.
12433
12434            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12435            pkg.applicationInfo.secondaryCpuAbi = null;
12436        } else if (has32BitLibs && !has64BitLibs) {
12437            // The package has 32 bit libs but not 64 bit libs. Its primary
12438            // ABI should be 32 bit.
12439
12440            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12441            pkg.applicationInfo.secondaryCpuAbi = null;
12442        } else if (has32BitLibs && has64BitLibs) {
12443            // The application has both 64 and 32 bit bundled libraries. We check
12444            // here that the app declares multiArch support, and warn if it doesn't.
12445            //
12446            // We will be lenient here and record both ABIs. The primary will be the
12447            // ABI that's higher on the list, i.e, a device that's configured to prefer
12448            // 64 bit apps will see a 64 bit primary ABI,
12449
12450            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12451                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12452            }
12453
12454            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12455                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12456                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12457            } else {
12458                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12459                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12460            }
12461        } else {
12462            pkg.applicationInfo.primaryCpuAbi = null;
12463            pkg.applicationInfo.secondaryCpuAbi = null;
12464        }
12465    }
12466
12467    private void killApplication(String pkgName, int appId, String reason) {
12468        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12469    }
12470
12471    private void killApplication(String pkgName, int appId, int userId, String reason) {
12472        // Request the ActivityManager to kill the process(only for existing packages)
12473        // so that we do not end up in a confused state while the user is still using the older
12474        // version of the application while the new one gets installed.
12475        final long token = Binder.clearCallingIdentity();
12476        try {
12477            IActivityManager am = ActivityManager.getService();
12478            if (am != null) {
12479                try {
12480                    am.killApplication(pkgName, appId, userId, reason);
12481                } catch (RemoteException e) {
12482                }
12483            }
12484        } finally {
12485            Binder.restoreCallingIdentity(token);
12486        }
12487    }
12488
12489    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12490        // Remove the parent package setting
12491        PackageSetting ps = (PackageSetting) pkg.mExtras;
12492        if (ps != null) {
12493            removePackageLI(ps, chatty);
12494        }
12495        // Remove the child package setting
12496        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12497        for (int i = 0; i < childCount; i++) {
12498            PackageParser.Package childPkg = pkg.childPackages.get(i);
12499            ps = (PackageSetting) childPkg.mExtras;
12500            if (ps != null) {
12501                removePackageLI(ps, chatty);
12502            }
12503        }
12504    }
12505
12506    void removePackageLI(PackageSetting ps, boolean chatty) {
12507        if (DEBUG_INSTALL) {
12508            if (chatty)
12509                Log.d(TAG, "Removing package " + ps.name);
12510        }
12511
12512        // writer
12513        synchronized (mPackages) {
12514            mPackages.remove(ps.name);
12515            final PackageParser.Package pkg = ps.pkg;
12516            if (pkg != null) {
12517                cleanPackageDataStructuresLILPw(pkg, chatty);
12518            }
12519        }
12520    }
12521
12522    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12523        if (DEBUG_INSTALL) {
12524            if (chatty)
12525                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12526        }
12527
12528        // writer
12529        synchronized (mPackages) {
12530            // Remove the parent package
12531            mPackages.remove(pkg.applicationInfo.packageName);
12532            cleanPackageDataStructuresLILPw(pkg, chatty);
12533
12534            // Remove the child packages
12535            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12536            for (int i = 0; i < childCount; i++) {
12537                PackageParser.Package childPkg = pkg.childPackages.get(i);
12538                mPackages.remove(childPkg.applicationInfo.packageName);
12539                cleanPackageDataStructuresLILPw(childPkg, chatty);
12540            }
12541        }
12542    }
12543
12544    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12545        int N = pkg.providers.size();
12546        StringBuilder r = null;
12547        int i;
12548        for (i=0; i<N; i++) {
12549            PackageParser.Provider p = pkg.providers.get(i);
12550            mProviders.removeProvider(p);
12551            if (p.info.authority == null) {
12552
12553                /* There was another ContentProvider with this authority when
12554                 * this app was installed so this authority is null,
12555                 * Ignore it as we don't have to unregister the provider.
12556                 */
12557                continue;
12558            }
12559            String names[] = p.info.authority.split(";");
12560            for (int j = 0; j < names.length; j++) {
12561                if (mProvidersByAuthority.get(names[j]) == p) {
12562                    mProvidersByAuthority.remove(names[j]);
12563                    if (DEBUG_REMOVE) {
12564                        if (chatty)
12565                            Log.d(TAG, "Unregistered content provider: " + names[j]
12566                                    + ", className = " + p.info.name + ", isSyncable = "
12567                                    + p.info.isSyncable);
12568                    }
12569                }
12570            }
12571            if (DEBUG_REMOVE && chatty) {
12572                if (r == null) {
12573                    r = new StringBuilder(256);
12574                } else {
12575                    r.append(' ');
12576                }
12577                r.append(p.info.name);
12578            }
12579        }
12580        if (r != null) {
12581            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12582        }
12583
12584        N = pkg.services.size();
12585        r = null;
12586        for (i=0; i<N; i++) {
12587            PackageParser.Service s = pkg.services.get(i);
12588            mServices.removeService(s);
12589            if (chatty) {
12590                if (r == null) {
12591                    r = new StringBuilder(256);
12592                } else {
12593                    r.append(' ');
12594                }
12595                r.append(s.info.name);
12596            }
12597        }
12598        if (r != null) {
12599            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12600        }
12601
12602        N = pkg.receivers.size();
12603        r = null;
12604        for (i=0; i<N; i++) {
12605            PackageParser.Activity a = pkg.receivers.get(i);
12606            mReceivers.removeActivity(a, "receiver");
12607            if (DEBUG_REMOVE && chatty) {
12608                if (r == null) {
12609                    r = new StringBuilder(256);
12610                } else {
12611                    r.append(' ');
12612                }
12613                r.append(a.info.name);
12614            }
12615        }
12616        if (r != null) {
12617            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12618        }
12619
12620        N = pkg.activities.size();
12621        r = null;
12622        for (i=0; i<N; i++) {
12623            PackageParser.Activity a = pkg.activities.get(i);
12624            mActivities.removeActivity(a, "activity");
12625            if (DEBUG_REMOVE && chatty) {
12626                if (r == null) {
12627                    r = new StringBuilder(256);
12628                } else {
12629                    r.append(' ');
12630                }
12631                r.append(a.info.name);
12632            }
12633        }
12634        if (r != null) {
12635            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12636        }
12637
12638        N = pkg.permissions.size();
12639        r = null;
12640        for (i=0; i<N; i++) {
12641            PackageParser.Permission p = pkg.permissions.get(i);
12642            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12643            if (bp == null) {
12644                bp = mSettings.mPermissionTrees.get(p.info.name);
12645            }
12646            if (bp != null && bp.perm == p) {
12647                bp.perm = null;
12648                if (DEBUG_REMOVE && chatty) {
12649                    if (r == null) {
12650                        r = new StringBuilder(256);
12651                    } else {
12652                        r.append(' ');
12653                    }
12654                    r.append(p.info.name);
12655                }
12656            }
12657            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12658                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12659                if (appOpPkgs != null) {
12660                    appOpPkgs.remove(pkg.packageName);
12661                }
12662            }
12663        }
12664        if (r != null) {
12665            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12666        }
12667
12668        N = pkg.requestedPermissions.size();
12669        r = null;
12670        for (i=0; i<N; i++) {
12671            String perm = pkg.requestedPermissions.get(i);
12672            BasePermission bp = mSettings.mPermissions.get(perm);
12673            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12674                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12675                if (appOpPkgs != null) {
12676                    appOpPkgs.remove(pkg.packageName);
12677                    if (appOpPkgs.isEmpty()) {
12678                        mAppOpPermissionPackages.remove(perm);
12679                    }
12680                }
12681            }
12682        }
12683        if (r != null) {
12684            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12685        }
12686
12687        N = pkg.instrumentation.size();
12688        r = null;
12689        for (i=0; i<N; i++) {
12690            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12691            mInstrumentation.remove(a.getComponentName());
12692            if (DEBUG_REMOVE && chatty) {
12693                if (r == null) {
12694                    r = new StringBuilder(256);
12695                } else {
12696                    r.append(' ');
12697                }
12698                r.append(a.info.name);
12699            }
12700        }
12701        if (r != null) {
12702            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12703        }
12704
12705        r = null;
12706        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12707            // Only system apps can hold shared libraries.
12708            if (pkg.libraryNames != null) {
12709                for (i = 0; i < pkg.libraryNames.size(); i++) {
12710                    String name = pkg.libraryNames.get(i);
12711                    if (removeSharedLibraryLPw(name, 0)) {
12712                        if (DEBUG_REMOVE && chatty) {
12713                            if (r == null) {
12714                                r = new StringBuilder(256);
12715                            } else {
12716                                r.append(' ');
12717                            }
12718                            r.append(name);
12719                        }
12720                    }
12721                }
12722            }
12723        }
12724
12725        r = null;
12726
12727        // Any package can hold static shared libraries.
12728        if (pkg.staticSharedLibName != null) {
12729            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12730                if (DEBUG_REMOVE && chatty) {
12731                    if (r == null) {
12732                        r = new StringBuilder(256);
12733                    } else {
12734                        r.append(' ');
12735                    }
12736                    r.append(pkg.staticSharedLibName);
12737                }
12738            }
12739        }
12740
12741        if (r != null) {
12742            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12743        }
12744    }
12745
12746    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12747        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12748            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12749                return true;
12750            }
12751        }
12752        return false;
12753    }
12754
12755    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12756    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12757    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12758
12759    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12760        // Update the parent permissions
12761        updatePermissionsLPw(pkg.packageName, pkg, flags);
12762        // Update the child permissions
12763        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12764        for (int i = 0; i < childCount; i++) {
12765            PackageParser.Package childPkg = pkg.childPackages.get(i);
12766            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12767        }
12768    }
12769
12770    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12771            int flags) {
12772        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12773        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12774    }
12775
12776    private void updatePermissionsLPw(String changingPkg,
12777            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12778        // Make sure there are no dangling permission trees.
12779        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12780        while (it.hasNext()) {
12781            final BasePermission bp = it.next();
12782            if (bp.packageSetting == null) {
12783                // We may not yet have parsed the package, so just see if
12784                // we still know about its settings.
12785                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12786            }
12787            if (bp.packageSetting == null) {
12788                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12789                        + " from package " + bp.sourcePackage);
12790                it.remove();
12791            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12792                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12793                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12794                            + " from package " + bp.sourcePackage);
12795                    flags |= UPDATE_PERMISSIONS_ALL;
12796                    it.remove();
12797                }
12798            }
12799        }
12800
12801        // Make sure all dynamic permissions have been assigned to a package,
12802        // and make sure there are no dangling permissions.
12803        it = mSettings.mPermissions.values().iterator();
12804        while (it.hasNext()) {
12805            final BasePermission bp = it.next();
12806            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12807                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12808                        + bp.name + " pkg=" + bp.sourcePackage
12809                        + " info=" + bp.pendingInfo);
12810                if (bp.packageSetting == null && bp.pendingInfo != null) {
12811                    final BasePermission tree = findPermissionTreeLP(bp.name);
12812                    if (tree != null && tree.perm != null) {
12813                        bp.packageSetting = tree.packageSetting;
12814                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12815                                new PermissionInfo(bp.pendingInfo));
12816                        bp.perm.info.packageName = tree.perm.info.packageName;
12817                        bp.perm.info.name = bp.name;
12818                        bp.uid = tree.uid;
12819                    }
12820                }
12821            }
12822            if (bp.packageSetting == null) {
12823                // We may not yet have parsed the package, so just see if
12824                // we still know about its settings.
12825                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12826            }
12827            if (bp.packageSetting == null) {
12828                Slog.w(TAG, "Removing dangling permission: " + bp.name
12829                        + " from package " + bp.sourcePackage);
12830                it.remove();
12831            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12832                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12833                    Slog.i(TAG, "Removing old permission: " + bp.name
12834                            + " from package " + bp.sourcePackage);
12835                    flags |= UPDATE_PERMISSIONS_ALL;
12836                    it.remove();
12837                }
12838            }
12839        }
12840
12841        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12842        // Now update the permissions for all packages, in particular
12843        // replace the granted permissions of the system packages.
12844        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12845            for (PackageParser.Package pkg : mPackages.values()) {
12846                if (pkg != pkgInfo) {
12847                    // Only replace for packages on requested volume
12848                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12849                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12850                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12851                    grantPermissionsLPw(pkg, replace, changingPkg);
12852                }
12853            }
12854        }
12855
12856        if (pkgInfo != null) {
12857            // Only replace for packages on requested volume
12858            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12859            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12860                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12861            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12862        }
12863        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12864    }
12865
12866    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12867            String packageOfInterest) {
12868        // IMPORTANT: There are two types of permissions: install and runtime.
12869        // Install time permissions are granted when the app is installed to
12870        // all device users and users added in the future. Runtime permissions
12871        // are granted at runtime explicitly to specific users. Normal and signature
12872        // protected permissions are install time permissions. Dangerous permissions
12873        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12874        // otherwise they are runtime permissions. This function does not manage
12875        // runtime permissions except for the case an app targeting Lollipop MR1
12876        // being upgraded to target a newer SDK, in which case dangerous permissions
12877        // are transformed from install time to runtime ones.
12878
12879        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12880        if (ps == null) {
12881            return;
12882        }
12883
12884        PermissionsState permissionsState = ps.getPermissionsState();
12885        PermissionsState origPermissions = permissionsState;
12886
12887        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12888
12889        boolean runtimePermissionsRevoked = false;
12890        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12891
12892        boolean changedInstallPermission = false;
12893
12894        if (replace) {
12895            ps.installPermissionsFixed = false;
12896            if (!ps.isSharedUser()) {
12897                origPermissions = new PermissionsState(permissionsState);
12898                permissionsState.reset();
12899            } else {
12900                // We need to know only about runtime permission changes since the
12901                // calling code always writes the install permissions state but
12902                // the runtime ones are written only if changed. The only cases of
12903                // changed runtime permissions here are promotion of an install to
12904                // runtime and revocation of a runtime from a shared user.
12905                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12906                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12907                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12908                    runtimePermissionsRevoked = true;
12909                }
12910            }
12911        }
12912
12913        permissionsState.setGlobalGids(mGlobalGids);
12914
12915        final int N = pkg.requestedPermissions.size();
12916        for (int i=0; i<N; i++) {
12917            final String name = pkg.requestedPermissions.get(i);
12918            final BasePermission bp = mSettings.mPermissions.get(name);
12919            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12920                    >= Build.VERSION_CODES.M;
12921
12922            if (DEBUG_INSTALL) {
12923                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12924            }
12925
12926            if (bp == null || bp.packageSetting == null) {
12927                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12928                    if (DEBUG_PERMISSIONS) {
12929                        Slog.i(TAG, "Unknown permission " + name
12930                                + " in package " + pkg.packageName);
12931                    }
12932                }
12933                continue;
12934            }
12935
12936
12937            // Limit ephemeral apps to ephemeral allowed permissions.
12938            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12939                if (DEBUG_PERMISSIONS) {
12940                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12941                            + pkg.packageName);
12942                }
12943                continue;
12944            }
12945
12946            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12947                if (DEBUG_PERMISSIONS) {
12948                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12949                            + pkg.packageName);
12950                }
12951                continue;
12952            }
12953
12954            final String perm = bp.name;
12955            boolean allowedSig = false;
12956            int grant = GRANT_DENIED;
12957
12958            // Keep track of app op permissions.
12959            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12960                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12961                if (pkgs == null) {
12962                    pkgs = new ArraySet<>();
12963                    mAppOpPermissionPackages.put(bp.name, pkgs);
12964                }
12965                pkgs.add(pkg.packageName);
12966            }
12967
12968            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12969            switch (level) {
12970                case PermissionInfo.PROTECTION_NORMAL: {
12971                    // For all apps normal permissions are install time ones.
12972                    grant = GRANT_INSTALL;
12973                } break;
12974
12975                case PermissionInfo.PROTECTION_DANGEROUS: {
12976                    // If a permission review is required for legacy apps we represent
12977                    // their permissions as always granted runtime ones since we need
12978                    // to keep the review required permission flag per user while an
12979                    // install permission's state is shared across all users.
12980                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12981                        // For legacy apps dangerous permissions are install time ones.
12982                        grant = GRANT_INSTALL;
12983                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12984                        // For legacy apps that became modern, install becomes runtime.
12985                        grant = GRANT_UPGRADE;
12986                    } else if (mPromoteSystemApps
12987                            && isSystemApp(ps)
12988                            && mExistingSystemPackages.contains(ps.name)) {
12989                        // For legacy system apps, install becomes runtime.
12990                        // We cannot check hasInstallPermission() for system apps since those
12991                        // permissions were granted implicitly and not persisted pre-M.
12992                        grant = GRANT_UPGRADE;
12993                    } else {
12994                        // For modern apps keep runtime permissions unchanged.
12995                        grant = GRANT_RUNTIME;
12996                    }
12997                } break;
12998
12999                case PermissionInfo.PROTECTION_SIGNATURE: {
13000                    // For all apps signature permissions are install time ones.
13001                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
13002                    if (allowedSig) {
13003                        grant = GRANT_INSTALL;
13004                    }
13005                } break;
13006            }
13007
13008            if (DEBUG_PERMISSIONS) {
13009                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
13010            }
13011
13012            if (grant != GRANT_DENIED) {
13013                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
13014                    // If this is an existing, non-system package, then
13015                    // we can't add any new permissions to it.
13016                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
13017                        // Except...  if this is a permission that was added
13018                        // to the platform (note: need to only do this when
13019                        // updating the platform).
13020                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
13021                            grant = GRANT_DENIED;
13022                        }
13023                    }
13024                }
13025
13026                switch (grant) {
13027                    case GRANT_INSTALL: {
13028                        // Revoke this as runtime permission to handle the case of
13029                        // a runtime permission being downgraded to an install one.
13030                        // Also in permission review mode we keep dangerous permissions
13031                        // for legacy apps
13032                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13033                            if (origPermissions.getRuntimePermissionState(
13034                                    bp.name, userId) != null) {
13035                                // Revoke the runtime permission and clear the flags.
13036                                origPermissions.revokeRuntimePermission(bp, userId);
13037                                origPermissions.updatePermissionFlags(bp, userId,
13038                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
13039                                // If we revoked a permission permission, we have to write.
13040                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13041                                        changedRuntimePermissionUserIds, userId);
13042                            }
13043                        }
13044                        // Grant an install permission.
13045                        if (permissionsState.grantInstallPermission(bp) !=
13046                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
13047                            changedInstallPermission = true;
13048                        }
13049                    } break;
13050
13051                    case GRANT_RUNTIME: {
13052                        // Grant previously granted runtime permissions.
13053                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13054                            PermissionState permissionState = origPermissions
13055                                    .getRuntimePermissionState(bp.name, userId);
13056                            int flags = permissionState != null
13057                                    ? permissionState.getFlags() : 0;
13058                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
13059                                // Don't propagate the permission in a permission review mode if
13060                                // the former was revoked, i.e. marked to not propagate on upgrade.
13061                                // Note that in a permission review mode install permissions are
13062                                // represented as constantly granted runtime ones since we need to
13063                                // keep a per user state associated with the permission. Also the
13064                                // revoke on upgrade flag is no longer applicable and is reset.
13065                                final boolean revokeOnUpgrade = (flags & PackageManager
13066                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
13067                                if (revokeOnUpgrade) {
13068                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13069                                    // Since we changed the flags, we have to write.
13070                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13071                                            changedRuntimePermissionUserIds, userId);
13072                                }
13073                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
13074                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
13075                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
13076                                        // If we cannot put the permission as it was,
13077                                        // we have to write.
13078                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13079                                                changedRuntimePermissionUserIds, userId);
13080                                    }
13081                                }
13082
13083                                // If the app supports runtime permissions no need for a review.
13084                                if (mPermissionReviewRequired
13085                                        && appSupportsRuntimePermissions
13086                                        && (flags & PackageManager
13087                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
13088                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
13089                                    // Since we changed the flags, we have to write.
13090                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13091                                            changedRuntimePermissionUserIds, userId);
13092                                }
13093                            } else if (mPermissionReviewRequired
13094                                    && !appSupportsRuntimePermissions) {
13095                                // For legacy apps that need a permission review, every new
13096                                // runtime permission is granted but it is pending a review.
13097                                // We also need to review only platform defined runtime
13098                                // permissions as these are the only ones the platform knows
13099                                // how to disable the API to simulate revocation as legacy
13100                                // apps don't expect to run with revoked permissions.
13101                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13102                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13103                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13104                                        // We changed the flags, hence have to write.
13105                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13106                                                changedRuntimePermissionUserIds, userId);
13107                                    }
13108                                }
13109                                if (permissionsState.grantRuntimePermission(bp, userId)
13110                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13111                                    // We changed the permission, hence have to write.
13112                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13113                                            changedRuntimePermissionUserIds, userId);
13114                                }
13115                            }
13116                            // Propagate the permission flags.
13117                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13118                        }
13119                    } break;
13120
13121                    case GRANT_UPGRADE: {
13122                        // Grant runtime permissions for a previously held install permission.
13123                        PermissionState permissionState = origPermissions
13124                                .getInstallPermissionState(bp.name);
13125                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13126
13127                        if (origPermissions.revokeInstallPermission(bp)
13128                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13129                            // We will be transferring the permission flags, so clear them.
13130                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13131                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13132                            changedInstallPermission = true;
13133                        }
13134
13135                        // If the permission is not to be promoted to runtime we ignore it and
13136                        // also its other flags as they are not applicable to install permissions.
13137                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13138                            for (int userId : currentUserIds) {
13139                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13140                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13141                                    // Transfer the permission flags.
13142                                    permissionsState.updatePermissionFlags(bp, userId,
13143                                            flags, flags);
13144                                    // If we granted the permission, we have to write.
13145                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13146                                            changedRuntimePermissionUserIds, userId);
13147                                }
13148                            }
13149                        }
13150                    } break;
13151
13152                    default: {
13153                        if (packageOfInterest == null
13154                                || packageOfInterest.equals(pkg.packageName)) {
13155                            if (DEBUG_PERMISSIONS) {
13156                                Slog.i(TAG, "Not granting permission " + perm
13157                                        + " to package " + pkg.packageName
13158                                        + " because it was previously installed without");
13159                            }
13160                        }
13161                    } break;
13162                }
13163            } else {
13164                if (permissionsState.revokeInstallPermission(bp) !=
13165                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13166                    // Also drop the permission flags.
13167                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13168                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13169                    changedInstallPermission = true;
13170                    Slog.i(TAG, "Un-granting permission " + perm
13171                            + " from package " + pkg.packageName
13172                            + " (protectionLevel=" + bp.protectionLevel
13173                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13174                            + ")");
13175                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13176                    // Don't print warning for app op permissions, since it is fine for them
13177                    // not to be granted, there is a UI for the user to decide.
13178                    if (DEBUG_PERMISSIONS
13179                            && (packageOfInterest == null
13180                                    || packageOfInterest.equals(pkg.packageName))) {
13181                        Slog.i(TAG, "Not granting permission " + perm
13182                                + " to package " + pkg.packageName
13183                                + " (protectionLevel=" + bp.protectionLevel
13184                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13185                                + ")");
13186                    }
13187                }
13188            }
13189        }
13190
13191        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13192                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13193            // This is the first that we have heard about this package, so the
13194            // permissions we have now selected are fixed until explicitly
13195            // changed.
13196            ps.installPermissionsFixed = true;
13197        }
13198
13199        // Persist the runtime permissions state for users with changes. If permissions
13200        // were revoked because no app in the shared user declares them we have to
13201        // write synchronously to avoid losing runtime permissions state.
13202        for (int userId : changedRuntimePermissionUserIds) {
13203            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13204        }
13205    }
13206
13207    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13208        boolean allowed = false;
13209        final int NP = PackageParser.NEW_PERMISSIONS.length;
13210        for (int ip=0; ip<NP; ip++) {
13211            final PackageParser.NewPermissionInfo npi
13212                    = PackageParser.NEW_PERMISSIONS[ip];
13213            if (npi.name.equals(perm)
13214                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13215                allowed = true;
13216                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13217                        + pkg.packageName);
13218                break;
13219            }
13220        }
13221        return allowed;
13222    }
13223
13224    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13225            BasePermission bp, PermissionsState origPermissions) {
13226        boolean privilegedPermission = (bp.protectionLevel
13227                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13228        boolean privappPermissionsDisable =
13229                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13230        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13231        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13232        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13233                && !platformPackage && platformPermission) {
13234            final ArraySet<String> allowedPermissions = SystemConfig.getInstance()
13235                    .getPrivAppPermissions(pkg.packageName);
13236            final boolean whitelisted =
13237                    allowedPermissions != null && allowedPermissions.contains(perm);
13238            if (!whitelisted) {
13239                Slog.w(TAG, "Privileged permission " + perm + " for package "
13240                        + pkg.packageName + " - not in privapp-permissions whitelist");
13241                // Only report violations for apps on system image
13242                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13243                    // it's only a reportable violation if the permission isn't explicitly denied
13244                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
13245                            .getPrivAppDenyPermissions(pkg.packageName);
13246                    final boolean permissionViolation =
13247                            deniedPermissions == null || !deniedPermissions.contains(perm);
13248                    if (permissionViolation) {
13249                        if (mPrivappPermissionsViolations == null) {
13250                            mPrivappPermissionsViolations = new ArraySet<>();
13251                        }
13252                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13253                    } else {
13254                        return false;
13255                    }
13256                }
13257                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13258                    return false;
13259                }
13260            }
13261        }
13262        boolean allowed = (compareSignatures(
13263                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13264                        == PackageManager.SIGNATURE_MATCH)
13265                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13266                        == PackageManager.SIGNATURE_MATCH);
13267        if (!allowed && privilegedPermission) {
13268            if (isSystemApp(pkg)) {
13269                // For updated system applications, a system permission
13270                // is granted only if it had been defined by the original application.
13271                if (pkg.isUpdatedSystemApp()) {
13272                    final PackageSetting sysPs = mSettings
13273                            .getDisabledSystemPkgLPr(pkg.packageName);
13274                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13275                        // If the original was granted this permission, we take
13276                        // that grant decision as read and propagate it to the
13277                        // update.
13278                        if (sysPs.isPrivileged()) {
13279                            allowed = true;
13280                        }
13281                    } else {
13282                        // The system apk may have been updated with an older
13283                        // version of the one on the data partition, but which
13284                        // granted a new system permission that it didn't have
13285                        // before.  In this case we do want to allow the app to
13286                        // now get the new permission if the ancestral apk is
13287                        // privileged to get it.
13288                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13289                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13290                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13291                                    allowed = true;
13292                                    break;
13293                                }
13294                            }
13295                        }
13296                        // Also if a privileged parent package on the system image or any of
13297                        // its children requested a privileged permission, the updated child
13298                        // packages can also get the permission.
13299                        if (pkg.parentPackage != null) {
13300                            final PackageSetting disabledSysParentPs = mSettings
13301                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13302                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13303                                    && disabledSysParentPs.isPrivileged()) {
13304                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13305                                    allowed = true;
13306                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13307                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13308                                    for (int i = 0; i < count; i++) {
13309                                        PackageParser.Package disabledSysChildPkg =
13310                                                disabledSysParentPs.pkg.childPackages.get(i);
13311                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13312                                                perm)) {
13313                                            allowed = true;
13314                                            break;
13315                                        }
13316                                    }
13317                                }
13318                            }
13319                        }
13320                    }
13321                } else {
13322                    allowed = isPrivilegedApp(pkg);
13323                }
13324            }
13325        }
13326        if (!allowed) {
13327            if (!allowed && (bp.protectionLevel
13328                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13329                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13330                // If this was a previously normal/dangerous permission that got moved
13331                // to a system permission as part of the runtime permission redesign, then
13332                // we still want to blindly grant it to old apps.
13333                allowed = true;
13334            }
13335            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13336                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13337                // If this permission is to be granted to the system installer and
13338                // this app is an installer, then it gets the permission.
13339                allowed = true;
13340            }
13341            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13342                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13343                // If this permission is to be granted to the system verifier and
13344                // this app is a verifier, then it gets the permission.
13345                allowed = true;
13346            }
13347            if (!allowed && (bp.protectionLevel
13348                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13349                    && isSystemApp(pkg)) {
13350                // Any pre-installed system app is allowed to get this permission.
13351                allowed = true;
13352            }
13353            if (!allowed && (bp.protectionLevel
13354                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13355                // For development permissions, a development permission
13356                // is granted only if it was already granted.
13357                allowed = origPermissions.hasInstallPermission(perm);
13358            }
13359            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13360                    && pkg.packageName.equals(mSetupWizardPackage)) {
13361                // If this permission is to be granted to the system setup wizard and
13362                // this app is a setup wizard, then it gets the permission.
13363                allowed = true;
13364            }
13365        }
13366        return allowed;
13367    }
13368
13369    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13370        final int permCount = pkg.requestedPermissions.size();
13371        for (int j = 0; j < permCount; j++) {
13372            String requestedPermission = pkg.requestedPermissions.get(j);
13373            if (permission.equals(requestedPermission)) {
13374                return true;
13375            }
13376        }
13377        return false;
13378    }
13379
13380    final class ActivityIntentResolver
13381            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13382        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13383                boolean defaultOnly, int userId) {
13384            if (!sUserManager.exists(userId)) return null;
13385            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13386            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13387        }
13388
13389        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13390                int userId) {
13391            if (!sUserManager.exists(userId)) return null;
13392            mFlags = flags;
13393            return super.queryIntent(intent, resolvedType,
13394                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13395                    userId);
13396        }
13397
13398        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13399                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13400            if (!sUserManager.exists(userId)) return null;
13401            if (packageActivities == null) {
13402                return null;
13403            }
13404            mFlags = flags;
13405            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13406            final int N = packageActivities.size();
13407            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13408                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13409
13410            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13411            for (int i = 0; i < N; ++i) {
13412                intentFilters = packageActivities.get(i).intents;
13413                if (intentFilters != null && intentFilters.size() > 0) {
13414                    PackageParser.ActivityIntentInfo[] array =
13415                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13416                    intentFilters.toArray(array);
13417                    listCut.add(array);
13418                }
13419            }
13420            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13421        }
13422
13423        /**
13424         * Finds a privileged activity that matches the specified activity names.
13425         */
13426        private PackageParser.Activity findMatchingActivity(
13427                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13428            for (PackageParser.Activity sysActivity : activityList) {
13429                if (sysActivity.info.name.equals(activityInfo.name)) {
13430                    return sysActivity;
13431                }
13432                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13433                    return sysActivity;
13434                }
13435                if (sysActivity.info.targetActivity != null) {
13436                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13437                        return sysActivity;
13438                    }
13439                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13440                        return sysActivity;
13441                    }
13442                }
13443            }
13444            return null;
13445        }
13446
13447        public class IterGenerator<E> {
13448            public Iterator<E> generate(ActivityIntentInfo info) {
13449                return null;
13450            }
13451        }
13452
13453        public class ActionIterGenerator extends IterGenerator<String> {
13454            @Override
13455            public Iterator<String> generate(ActivityIntentInfo info) {
13456                return info.actionsIterator();
13457            }
13458        }
13459
13460        public class CategoriesIterGenerator extends IterGenerator<String> {
13461            @Override
13462            public Iterator<String> generate(ActivityIntentInfo info) {
13463                return info.categoriesIterator();
13464            }
13465        }
13466
13467        public class SchemesIterGenerator extends IterGenerator<String> {
13468            @Override
13469            public Iterator<String> generate(ActivityIntentInfo info) {
13470                return info.schemesIterator();
13471            }
13472        }
13473
13474        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13475            @Override
13476            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13477                return info.authoritiesIterator();
13478            }
13479        }
13480
13481        /**
13482         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13483         * MODIFIED. Do not pass in a list that should not be changed.
13484         */
13485        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13486                IterGenerator<T> generator, Iterator<T> searchIterator) {
13487            // loop through the set of actions; every one must be found in the intent filter
13488            while (searchIterator.hasNext()) {
13489                // we must have at least one filter in the list to consider a match
13490                if (intentList.size() == 0) {
13491                    break;
13492                }
13493
13494                final T searchAction = searchIterator.next();
13495
13496                // loop through the set of intent filters
13497                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13498                while (intentIter.hasNext()) {
13499                    final ActivityIntentInfo intentInfo = intentIter.next();
13500                    boolean selectionFound = false;
13501
13502                    // loop through the intent filter's selection criteria; at least one
13503                    // of them must match the searched criteria
13504                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13505                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13506                        final T intentSelection = intentSelectionIter.next();
13507                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13508                            selectionFound = true;
13509                            break;
13510                        }
13511                    }
13512
13513                    // the selection criteria wasn't found in this filter's set; this filter
13514                    // is not a potential match
13515                    if (!selectionFound) {
13516                        intentIter.remove();
13517                    }
13518                }
13519            }
13520        }
13521
13522        private boolean isProtectedAction(ActivityIntentInfo filter) {
13523            final Iterator<String> actionsIter = filter.actionsIterator();
13524            while (actionsIter != null && actionsIter.hasNext()) {
13525                final String filterAction = actionsIter.next();
13526                if (PROTECTED_ACTIONS.contains(filterAction)) {
13527                    return true;
13528                }
13529            }
13530            return false;
13531        }
13532
13533        /**
13534         * Adjusts the priority of the given intent filter according to policy.
13535         * <p>
13536         * <ul>
13537         * <li>The priority for non privileged applications is capped to '0'</li>
13538         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13539         * <li>The priority for unbundled updates to privileged applications is capped to the
13540         *      priority defined on the system partition</li>
13541         * </ul>
13542         * <p>
13543         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13544         * allowed to obtain any priority on any action.
13545         */
13546        private void adjustPriority(
13547                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13548            // nothing to do; priority is fine as-is
13549            if (intent.getPriority() <= 0) {
13550                return;
13551            }
13552
13553            final ActivityInfo activityInfo = intent.activity.info;
13554            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13555
13556            final boolean privilegedApp =
13557                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13558            if (!privilegedApp) {
13559                // non-privileged applications can never define a priority >0
13560                if (DEBUG_FILTERS) {
13561                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13562                            + " package: " + applicationInfo.packageName
13563                            + " activity: " + intent.activity.className
13564                            + " origPrio: " + intent.getPriority());
13565                }
13566                intent.setPriority(0);
13567                return;
13568            }
13569
13570            if (systemActivities == null) {
13571                // the system package is not disabled; we're parsing the system partition
13572                if (isProtectedAction(intent)) {
13573                    if (mDeferProtectedFilters) {
13574                        // We can't deal with these just yet. No component should ever obtain a
13575                        // >0 priority for a protected actions, with ONE exception -- the setup
13576                        // wizard. The setup wizard, however, cannot be known until we're able to
13577                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13578                        // until all intent filters have been processed. Chicken, meet egg.
13579                        // Let the filter temporarily have a high priority and rectify the
13580                        // priorities after all system packages have been scanned.
13581                        mProtectedFilters.add(intent);
13582                        if (DEBUG_FILTERS) {
13583                            Slog.i(TAG, "Protected action; save for later;"
13584                                    + " package: " + applicationInfo.packageName
13585                                    + " activity: " + intent.activity.className
13586                                    + " origPrio: " + intent.getPriority());
13587                        }
13588                        return;
13589                    } else {
13590                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13591                            Slog.i(TAG, "No setup wizard;"
13592                                + " All protected intents capped to priority 0");
13593                        }
13594                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13595                            if (DEBUG_FILTERS) {
13596                                Slog.i(TAG, "Found setup wizard;"
13597                                    + " allow priority " + intent.getPriority() + ";"
13598                                    + " package: " + intent.activity.info.packageName
13599                                    + " activity: " + intent.activity.className
13600                                    + " priority: " + intent.getPriority());
13601                            }
13602                            // setup wizard gets whatever it wants
13603                            return;
13604                        }
13605                        if (DEBUG_FILTERS) {
13606                            Slog.i(TAG, "Protected action; cap priority to 0;"
13607                                    + " package: " + intent.activity.info.packageName
13608                                    + " activity: " + intent.activity.className
13609                                    + " origPrio: " + intent.getPriority());
13610                        }
13611                        intent.setPriority(0);
13612                        return;
13613                    }
13614                }
13615                // privileged apps on the system image get whatever priority they request
13616                return;
13617            }
13618
13619            // privileged app unbundled update ... try to find the same activity
13620            final PackageParser.Activity foundActivity =
13621                    findMatchingActivity(systemActivities, activityInfo);
13622            if (foundActivity == null) {
13623                // this is a new activity; it cannot obtain >0 priority
13624                if (DEBUG_FILTERS) {
13625                    Slog.i(TAG, "New activity; cap priority to 0;"
13626                            + " package: " + applicationInfo.packageName
13627                            + " activity: " + intent.activity.className
13628                            + " origPrio: " + intent.getPriority());
13629                }
13630                intent.setPriority(0);
13631                return;
13632            }
13633
13634            // found activity, now check for filter equivalence
13635
13636            // a shallow copy is enough; we modify the list, not its contents
13637            final List<ActivityIntentInfo> intentListCopy =
13638                    new ArrayList<>(foundActivity.intents);
13639            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13640
13641            // find matching action subsets
13642            final Iterator<String> actionsIterator = intent.actionsIterator();
13643            if (actionsIterator != null) {
13644                getIntentListSubset(
13645                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13646                if (intentListCopy.size() == 0) {
13647                    // no more intents to match; we're not equivalent
13648                    if (DEBUG_FILTERS) {
13649                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13650                                + " package: " + applicationInfo.packageName
13651                                + " activity: " + intent.activity.className
13652                                + " origPrio: " + intent.getPriority());
13653                    }
13654                    intent.setPriority(0);
13655                    return;
13656                }
13657            }
13658
13659            // find matching category subsets
13660            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13661            if (categoriesIterator != null) {
13662                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13663                        categoriesIterator);
13664                if (intentListCopy.size() == 0) {
13665                    // no more intents to match; we're not equivalent
13666                    if (DEBUG_FILTERS) {
13667                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13668                                + " package: " + applicationInfo.packageName
13669                                + " activity: " + intent.activity.className
13670                                + " origPrio: " + intent.getPriority());
13671                    }
13672                    intent.setPriority(0);
13673                    return;
13674                }
13675            }
13676
13677            // find matching schemes subsets
13678            final Iterator<String> schemesIterator = intent.schemesIterator();
13679            if (schemesIterator != null) {
13680                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13681                        schemesIterator);
13682                if (intentListCopy.size() == 0) {
13683                    // no more intents to match; we're not equivalent
13684                    if (DEBUG_FILTERS) {
13685                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13686                                + " package: " + applicationInfo.packageName
13687                                + " activity: " + intent.activity.className
13688                                + " origPrio: " + intent.getPriority());
13689                    }
13690                    intent.setPriority(0);
13691                    return;
13692                }
13693            }
13694
13695            // find matching authorities subsets
13696            final Iterator<IntentFilter.AuthorityEntry>
13697                    authoritiesIterator = intent.authoritiesIterator();
13698            if (authoritiesIterator != null) {
13699                getIntentListSubset(intentListCopy,
13700                        new AuthoritiesIterGenerator(),
13701                        authoritiesIterator);
13702                if (intentListCopy.size() == 0) {
13703                    // no more intents to match; we're not equivalent
13704                    if (DEBUG_FILTERS) {
13705                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13706                                + " package: " + applicationInfo.packageName
13707                                + " activity: " + intent.activity.className
13708                                + " origPrio: " + intent.getPriority());
13709                    }
13710                    intent.setPriority(0);
13711                    return;
13712                }
13713            }
13714
13715            // we found matching filter(s); app gets the max priority of all intents
13716            int cappedPriority = 0;
13717            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13718                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13719            }
13720            if (intent.getPriority() > cappedPriority) {
13721                if (DEBUG_FILTERS) {
13722                    Slog.i(TAG, "Found matching filter(s);"
13723                            + " cap priority to " + cappedPriority + ";"
13724                            + " package: " + applicationInfo.packageName
13725                            + " activity: " + intent.activity.className
13726                            + " origPrio: " + intent.getPriority());
13727                }
13728                intent.setPriority(cappedPriority);
13729                return;
13730            }
13731            // all this for nothing; the requested priority was <= what was on the system
13732        }
13733
13734        public final void addActivity(PackageParser.Activity a, String type) {
13735            mActivities.put(a.getComponentName(), a);
13736            if (DEBUG_SHOW_INFO)
13737                Log.v(
13738                TAG, "  " + type + " " +
13739                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13740            if (DEBUG_SHOW_INFO)
13741                Log.v(TAG, "    Class=" + a.info.name);
13742            final int NI = a.intents.size();
13743            for (int j=0; j<NI; j++) {
13744                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13745                if ("activity".equals(type)) {
13746                    final PackageSetting ps =
13747                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13748                    final List<PackageParser.Activity> systemActivities =
13749                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13750                    adjustPriority(systemActivities, intent);
13751                }
13752                if (DEBUG_SHOW_INFO) {
13753                    Log.v(TAG, "    IntentFilter:");
13754                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13755                }
13756                if (!intent.debugCheck()) {
13757                    Log.w(TAG, "==> For Activity " + a.info.name);
13758                }
13759                addFilter(intent);
13760            }
13761        }
13762
13763        public final void removeActivity(PackageParser.Activity a, String type) {
13764            mActivities.remove(a.getComponentName());
13765            if (DEBUG_SHOW_INFO) {
13766                Log.v(TAG, "  " + type + " "
13767                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13768                                : a.info.name) + ":");
13769                Log.v(TAG, "    Class=" + a.info.name);
13770            }
13771            final int NI = a.intents.size();
13772            for (int j=0; j<NI; j++) {
13773                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13774                if (DEBUG_SHOW_INFO) {
13775                    Log.v(TAG, "    IntentFilter:");
13776                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13777                }
13778                removeFilter(intent);
13779            }
13780        }
13781
13782        @Override
13783        protected boolean allowFilterResult(
13784                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13785            ActivityInfo filterAi = filter.activity.info;
13786            for (int i=dest.size()-1; i>=0; i--) {
13787                ActivityInfo destAi = dest.get(i).activityInfo;
13788                if (destAi.name == filterAi.name
13789                        && destAi.packageName == filterAi.packageName) {
13790                    return false;
13791                }
13792            }
13793            return true;
13794        }
13795
13796        @Override
13797        protected ActivityIntentInfo[] newArray(int size) {
13798            return new ActivityIntentInfo[size];
13799        }
13800
13801        @Override
13802        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13803            if (!sUserManager.exists(userId)) return true;
13804            PackageParser.Package p = filter.activity.owner;
13805            if (p != null) {
13806                PackageSetting ps = (PackageSetting)p.mExtras;
13807                if (ps != null) {
13808                    // System apps are never considered stopped for purposes of
13809                    // filtering, because there may be no way for the user to
13810                    // actually re-launch them.
13811                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13812                            && ps.getStopped(userId);
13813                }
13814            }
13815            return false;
13816        }
13817
13818        @Override
13819        protected boolean isPackageForFilter(String packageName,
13820                PackageParser.ActivityIntentInfo info) {
13821            return packageName.equals(info.activity.owner.packageName);
13822        }
13823
13824        @Override
13825        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13826                int match, int userId) {
13827            if (!sUserManager.exists(userId)) return null;
13828            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13829                return null;
13830            }
13831            final PackageParser.Activity activity = info.activity;
13832            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13833            if (ps == null) {
13834                return null;
13835            }
13836            final PackageUserState userState = ps.readUserState(userId);
13837            ActivityInfo ai =
13838                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13839            if (ai == null) {
13840                return null;
13841            }
13842            final boolean matchExplicitlyVisibleOnly =
13843                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13844            final boolean matchVisibleToInstantApp =
13845                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13846            final boolean componentVisible =
13847                    matchVisibleToInstantApp
13848                    && info.isVisibleToInstantApp()
13849                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13850            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13851            // throw out filters that aren't visible to ephemeral apps
13852            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13853                return null;
13854            }
13855            // throw out instant app filters if we're not explicitly requesting them
13856            if (!matchInstantApp && userState.instantApp) {
13857                return null;
13858            }
13859            // throw out instant app filters if updates are available; will trigger
13860            // instant app resolution
13861            if (userState.instantApp && ps.isUpdateAvailable()) {
13862                return null;
13863            }
13864            final ResolveInfo res = new ResolveInfo();
13865            res.activityInfo = ai;
13866            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13867                res.filter = info;
13868            }
13869            if (info != null) {
13870                res.handleAllWebDataURI = info.handleAllWebDataURI();
13871            }
13872            res.priority = info.getPriority();
13873            res.preferredOrder = activity.owner.mPreferredOrder;
13874            //System.out.println("Result: " + res.activityInfo.className +
13875            //                   " = " + res.priority);
13876            res.match = match;
13877            res.isDefault = info.hasDefault;
13878            res.labelRes = info.labelRes;
13879            res.nonLocalizedLabel = info.nonLocalizedLabel;
13880            if (userNeedsBadging(userId)) {
13881                res.noResourceId = true;
13882            } else {
13883                res.icon = info.icon;
13884            }
13885            res.iconResourceId = info.icon;
13886            res.system = res.activityInfo.applicationInfo.isSystemApp();
13887            res.isInstantAppAvailable = userState.instantApp;
13888            return res;
13889        }
13890
13891        @Override
13892        protected void sortResults(List<ResolveInfo> results) {
13893            Collections.sort(results, mResolvePrioritySorter);
13894        }
13895
13896        @Override
13897        protected void dumpFilter(PrintWriter out, String prefix,
13898                PackageParser.ActivityIntentInfo filter) {
13899            out.print(prefix); out.print(
13900                    Integer.toHexString(System.identityHashCode(filter.activity)));
13901                    out.print(' ');
13902                    filter.activity.printComponentShortName(out);
13903                    out.print(" filter ");
13904                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13905        }
13906
13907        @Override
13908        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13909            return filter.activity;
13910        }
13911
13912        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13913            PackageParser.Activity activity = (PackageParser.Activity)label;
13914            out.print(prefix); out.print(
13915                    Integer.toHexString(System.identityHashCode(activity)));
13916                    out.print(' ');
13917                    activity.printComponentShortName(out);
13918            if (count > 1) {
13919                out.print(" ("); out.print(count); out.print(" filters)");
13920            }
13921            out.println();
13922        }
13923
13924        // Keys are String (activity class name), values are Activity.
13925        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13926                = new ArrayMap<ComponentName, PackageParser.Activity>();
13927        private int mFlags;
13928    }
13929
13930    private final class ServiceIntentResolver
13931            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13932        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13933                boolean defaultOnly, int userId) {
13934            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13935            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13936        }
13937
13938        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13939                int userId) {
13940            if (!sUserManager.exists(userId)) return null;
13941            mFlags = flags;
13942            return super.queryIntent(intent, resolvedType,
13943                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13944                    userId);
13945        }
13946
13947        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13948                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13949            if (!sUserManager.exists(userId)) return null;
13950            if (packageServices == null) {
13951                return null;
13952            }
13953            mFlags = flags;
13954            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13955            final int N = packageServices.size();
13956            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13957                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13958
13959            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13960            for (int i = 0; i < N; ++i) {
13961                intentFilters = packageServices.get(i).intents;
13962                if (intentFilters != null && intentFilters.size() > 0) {
13963                    PackageParser.ServiceIntentInfo[] array =
13964                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13965                    intentFilters.toArray(array);
13966                    listCut.add(array);
13967                }
13968            }
13969            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13970        }
13971
13972        public final void addService(PackageParser.Service s) {
13973            mServices.put(s.getComponentName(), s);
13974            if (DEBUG_SHOW_INFO) {
13975                Log.v(TAG, "  "
13976                        + (s.info.nonLocalizedLabel != null
13977                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13978                Log.v(TAG, "    Class=" + s.info.name);
13979            }
13980            final int NI = s.intents.size();
13981            int j;
13982            for (j=0; j<NI; j++) {
13983                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13984                if (DEBUG_SHOW_INFO) {
13985                    Log.v(TAG, "    IntentFilter:");
13986                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13987                }
13988                if (!intent.debugCheck()) {
13989                    Log.w(TAG, "==> For Service " + s.info.name);
13990                }
13991                addFilter(intent);
13992            }
13993        }
13994
13995        public final void removeService(PackageParser.Service s) {
13996            mServices.remove(s.getComponentName());
13997            if (DEBUG_SHOW_INFO) {
13998                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13999                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
14000                Log.v(TAG, "    Class=" + s.info.name);
14001            }
14002            final int NI = s.intents.size();
14003            int j;
14004            for (j=0; j<NI; j++) {
14005                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
14006                if (DEBUG_SHOW_INFO) {
14007                    Log.v(TAG, "    IntentFilter:");
14008                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14009                }
14010                removeFilter(intent);
14011            }
14012        }
14013
14014        @Override
14015        protected boolean allowFilterResult(
14016                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
14017            ServiceInfo filterSi = filter.service.info;
14018            for (int i=dest.size()-1; i>=0; i--) {
14019                ServiceInfo destAi = dest.get(i).serviceInfo;
14020                if (destAi.name == filterSi.name
14021                        && destAi.packageName == filterSi.packageName) {
14022                    return false;
14023                }
14024            }
14025            return true;
14026        }
14027
14028        @Override
14029        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
14030            return new PackageParser.ServiceIntentInfo[size];
14031        }
14032
14033        @Override
14034        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
14035            if (!sUserManager.exists(userId)) return true;
14036            PackageParser.Package p = filter.service.owner;
14037            if (p != null) {
14038                PackageSetting ps = (PackageSetting)p.mExtras;
14039                if (ps != null) {
14040                    // System apps are never considered stopped for purposes of
14041                    // filtering, because there may be no way for the user to
14042                    // actually re-launch them.
14043                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14044                            && ps.getStopped(userId);
14045                }
14046            }
14047            return false;
14048        }
14049
14050        @Override
14051        protected boolean isPackageForFilter(String packageName,
14052                PackageParser.ServiceIntentInfo info) {
14053            return packageName.equals(info.service.owner.packageName);
14054        }
14055
14056        @Override
14057        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
14058                int match, int userId) {
14059            if (!sUserManager.exists(userId)) return null;
14060            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
14061            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
14062                return null;
14063            }
14064            final PackageParser.Service service = info.service;
14065            PackageSetting ps = (PackageSetting) service.owner.mExtras;
14066            if (ps == null) {
14067                return null;
14068            }
14069            final PackageUserState userState = ps.readUserState(userId);
14070            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
14071                    userState, userId);
14072            if (si == null) {
14073                return null;
14074            }
14075            final boolean matchVisibleToInstantApp =
14076                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14077            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14078            // throw out filters that aren't visible to ephemeral apps
14079            if (matchVisibleToInstantApp
14080                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14081                return null;
14082            }
14083            // throw out ephemeral filters if we're not explicitly requesting them
14084            if (!isInstantApp && userState.instantApp) {
14085                return null;
14086            }
14087            // throw out instant app filters if updates are available; will trigger
14088            // instant app resolution
14089            if (userState.instantApp && ps.isUpdateAvailable()) {
14090                return null;
14091            }
14092            final ResolveInfo res = new ResolveInfo();
14093            res.serviceInfo = si;
14094            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
14095                res.filter = filter;
14096            }
14097            res.priority = info.getPriority();
14098            res.preferredOrder = service.owner.mPreferredOrder;
14099            res.match = match;
14100            res.isDefault = info.hasDefault;
14101            res.labelRes = info.labelRes;
14102            res.nonLocalizedLabel = info.nonLocalizedLabel;
14103            res.icon = info.icon;
14104            res.system = res.serviceInfo.applicationInfo.isSystemApp();
14105            return res;
14106        }
14107
14108        @Override
14109        protected void sortResults(List<ResolveInfo> results) {
14110            Collections.sort(results, mResolvePrioritySorter);
14111        }
14112
14113        @Override
14114        protected void dumpFilter(PrintWriter out, String prefix,
14115                PackageParser.ServiceIntentInfo filter) {
14116            out.print(prefix); out.print(
14117                    Integer.toHexString(System.identityHashCode(filter.service)));
14118                    out.print(' ');
14119                    filter.service.printComponentShortName(out);
14120                    out.print(" filter ");
14121                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14122        }
14123
14124        @Override
14125        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14126            return filter.service;
14127        }
14128
14129        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14130            PackageParser.Service service = (PackageParser.Service)label;
14131            out.print(prefix); out.print(
14132                    Integer.toHexString(System.identityHashCode(service)));
14133                    out.print(' ');
14134                    service.printComponentShortName(out);
14135            if (count > 1) {
14136                out.print(" ("); out.print(count); out.print(" filters)");
14137            }
14138            out.println();
14139        }
14140
14141//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14142//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14143//            final List<ResolveInfo> retList = Lists.newArrayList();
14144//            while (i.hasNext()) {
14145//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14146//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14147//                    retList.add(resolveInfo);
14148//                }
14149//            }
14150//            return retList;
14151//        }
14152
14153        // Keys are String (activity class name), values are Activity.
14154        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14155                = new ArrayMap<ComponentName, PackageParser.Service>();
14156        private int mFlags;
14157    }
14158
14159    private final class ProviderIntentResolver
14160            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14161        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14162                boolean defaultOnly, int userId) {
14163            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14164            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14165        }
14166
14167        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14168                int userId) {
14169            if (!sUserManager.exists(userId))
14170                return null;
14171            mFlags = flags;
14172            return super.queryIntent(intent, resolvedType,
14173                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14174                    userId);
14175        }
14176
14177        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14178                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14179            if (!sUserManager.exists(userId))
14180                return null;
14181            if (packageProviders == null) {
14182                return null;
14183            }
14184            mFlags = flags;
14185            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14186            final int N = packageProviders.size();
14187            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14188                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14189
14190            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14191            for (int i = 0; i < N; ++i) {
14192                intentFilters = packageProviders.get(i).intents;
14193                if (intentFilters != null && intentFilters.size() > 0) {
14194                    PackageParser.ProviderIntentInfo[] array =
14195                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14196                    intentFilters.toArray(array);
14197                    listCut.add(array);
14198                }
14199            }
14200            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14201        }
14202
14203        public final void addProvider(PackageParser.Provider p) {
14204            if (mProviders.containsKey(p.getComponentName())) {
14205                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14206                return;
14207            }
14208
14209            mProviders.put(p.getComponentName(), p);
14210            if (DEBUG_SHOW_INFO) {
14211                Log.v(TAG, "  "
14212                        + (p.info.nonLocalizedLabel != null
14213                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14214                Log.v(TAG, "    Class=" + p.info.name);
14215            }
14216            final int NI = p.intents.size();
14217            int j;
14218            for (j = 0; j < NI; j++) {
14219                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14220                if (DEBUG_SHOW_INFO) {
14221                    Log.v(TAG, "    IntentFilter:");
14222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14223                }
14224                if (!intent.debugCheck()) {
14225                    Log.w(TAG, "==> For Provider " + p.info.name);
14226                }
14227                addFilter(intent);
14228            }
14229        }
14230
14231        public final void removeProvider(PackageParser.Provider p) {
14232            mProviders.remove(p.getComponentName());
14233            if (DEBUG_SHOW_INFO) {
14234                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14235                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14236                Log.v(TAG, "    Class=" + p.info.name);
14237            }
14238            final int NI = p.intents.size();
14239            int j;
14240            for (j = 0; j < NI; j++) {
14241                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14242                if (DEBUG_SHOW_INFO) {
14243                    Log.v(TAG, "    IntentFilter:");
14244                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14245                }
14246                removeFilter(intent);
14247            }
14248        }
14249
14250        @Override
14251        protected boolean allowFilterResult(
14252                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14253            ProviderInfo filterPi = filter.provider.info;
14254            for (int i = dest.size() - 1; i >= 0; i--) {
14255                ProviderInfo destPi = dest.get(i).providerInfo;
14256                if (destPi.name == filterPi.name
14257                        && destPi.packageName == filterPi.packageName) {
14258                    return false;
14259                }
14260            }
14261            return true;
14262        }
14263
14264        @Override
14265        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14266            return new PackageParser.ProviderIntentInfo[size];
14267        }
14268
14269        @Override
14270        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14271            if (!sUserManager.exists(userId))
14272                return true;
14273            PackageParser.Package p = filter.provider.owner;
14274            if (p != null) {
14275                PackageSetting ps = (PackageSetting) p.mExtras;
14276                if (ps != null) {
14277                    // System apps are never considered stopped for purposes of
14278                    // filtering, because there may be no way for the user to
14279                    // actually re-launch them.
14280                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14281                            && ps.getStopped(userId);
14282                }
14283            }
14284            return false;
14285        }
14286
14287        @Override
14288        protected boolean isPackageForFilter(String packageName,
14289                PackageParser.ProviderIntentInfo info) {
14290            return packageName.equals(info.provider.owner.packageName);
14291        }
14292
14293        @Override
14294        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14295                int match, int userId) {
14296            if (!sUserManager.exists(userId))
14297                return null;
14298            final PackageParser.ProviderIntentInfo info = filter;
14299            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14300                return null;
14301            }
14302            final PackageParser.Provider provider = info.provider;
14303            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14304            if (ps == null) {
14305                return null;
14306            }
14307            final PackageUserState userState = ps.readUserState(userId);
14308            final boolean matchVisibleToInstantApp =
14309                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14310            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14311            // throw out filters that aren't visible to instant applications
14312            if (matchVisibleToInstantApp
14313                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14314                return null;
14315            }
14316            // throw out instant application filters if we're not explicitly requesting them
14317            if (!isInstantApp && userState.instantApp) {
14318                return null;
14319            }
14320            // throw out instant application filters if updates are available; will trigger
14321            // instant application resolution
14322            if (userState.instantApp && ps.isUpdateAvailable()) {
14323                return null;
14324            }
14325            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14326                    userState, userId);
14327            if (pi == null) {
14328                return null;
14329            }
14330            final ResolveInfo res = new ResolveInfo();
14331            res.providerInfo = pi;
14332            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14333                res.filter = filter;
14334            }
14335            res.priority = info.getPriority();
14336            res.preferredOrder = provider.owner.mPreferredOrder;
14337            res.match = match;
14338            res.isDefault = info.hasDefault;
14339            res.labelRes = info.labelRes;
14340            res.nonLocalizedLabel = info.nonLocalizedLabel;
14341            res.icon = info.icon;
14342            res.system = res.providerInfo.applicationInfo.isSystemApp();
14343            return res;
14344        }
14345
14346        @Override
14347        protected void sortResults(List<ResolveInfo> results) {
14348            Collections.sort(results, mResolvePrioritySorter);
14349        }
14350
14351        @Override
14352        protected void dumpFilter(PrintWriter out, String prefix,
14353                PackageParser.ProviderIntentInfo filter) {
14354            out.print(prefix);
14355            out.print(
14356                    Integer.toHexString(System.identityHashCode(filter.provider)));
14357            out.print(' ');
14358            filter.provider.printComponentShortName(out);
14359            out.print(" filter ");
14360            out.println(Integer.toHexString(System.identityHashCode(filter)));
14361        }
14362
14363        @Override
14364        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14365            return filter.provider;
14366        }
14367
14368        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14369            PackageParser.Provider provider = (PackageParser.Provider)label;
14370            out.print(prefix); out.print(
14371                    Integer.toHexString(System.identityHashCode(provider)));
14372                    out.print(' ');
14373                    provider.printComponentShortName(out);
14374            if (count > 1) {
14375                out.print(" ("); out.print(count); out.print(" filters)");
14376            }
14377            out.println();
14378        }
14379
14380        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14381                = new ArrayMap<ComponentName, PackageParser.Provider>();
14382        private int mFlags;
14383    }
14384
14385    static final class EphemeralIntentResolver
14386            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14387        /**
14388         * The result that has the highest defined order. Ordering applies on a
14389         * per-package basis. Mapping is from package name to Pair of order and
14390         * EphemeralResolveInfo.
14391         * <p>
14392         * NOTE: This is implemented as a field variable for convenience and efficiency.
14393         * By having a field variable, we're able to track filter ordering as soon as
14394         * a non-zero order is defined. Otherwise, multiple loops across the result set
14395         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14396         * this needs to be contained entirely within {@link #filterResults}.
14397         */
14398        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14399
14400        @Override
14401        protected AuxiliaryResolveInfo[] newArray(int size) {
14402            return new AuxiliaryResolveInfo[size];
14403        }
14404
14405        @Override
14406        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14407            return true;
14408        }
14409
14410        @Override
14411        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14412                int userId) {
14413            if (!sUserManager.exists(userId)) {
14414                return null;
14415            }
14416            final String packageName = responseObj.resolveInfo.getPackageName();
14417            final Integer order = responseObj.getOrder();
14418            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14419                    mOrderResult.get(packageName);
14420            // ordering is enabled and this item's order isn't high enough
14421            if (lastOrderResult != null && lastOrderResult.first >= order) {
14422                return null;
14423            }
14424            final InstantAppResolveInfo res = responseObj.resolveInfo;
14425            if (order > 0) {
14426                // non-zero order, enable ordering
14427                mOrderResult.put(packageName, new Pair<>(order, res));
14428            }
14429            return responseObj;
14430        }
14431
14432        @Override
14433        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14434            // only do work if ordering is enabled [most of the time it won't be]
14435            if (mOrderResult.size() == 0) {
14436                return;
14437            }
14438            int resultSize = results.size();
14439            for (int i = 0; i < resultSize; i++) {
14440                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14441                final String packageName = info.getPackageName();
14442                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14443                if (savedInfo == null) {
14444                    // package doesn't having ordering
14445                    continue;
14446                }
14447                if (savedInfo.second == info) {
14448                    // circled back to the highest ordered item; remove from order list
14449                    mOrderResult.remove(packageName);
14450                    if (mOrderResult.size() == 0) {
14451                        // no more ordered items
14452                        break;
14453                    }
14454                    continue;
14455                }
14456                // item has a worse order, remove it from the result list
14457                results.remove(i);
14458                resultSize--;
14459                i--;
14460            }
14461        }
14462    }
14463
14464    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14465            new Comparator<ResolveInfo>() {
14466        public int compare(ResolveInfo r1, ResolveInfo r2) {
14467            int v1 = r1.priority;
14468            int v2 = r2.priority;
14469            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14470            if (v1 != v2) {
14471                return (v1 > v2) ? -1 : 1;
14472            }
14473            v1 = r1.preferredOrder;
14474            v2 = r2.preferredOrder;
14475            if (v1 != v2) {
14476                return (v1 > v2) ? -1 : 1;
14477            }
14478            if (r1.isDefault != r2.isDefault) {
14479                return r1.isDefault ? -1 : 1;
14480            }
14481            v1 = r1.match;
14482            v2 = r2.match;
14483            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14484            if (v1 != v2) {
14485                return (v1 > v2) ? -1 : 1;
14486            }
14487            if (r1.system != r2.system) {
14488                return r1.system ? -1 : 1;
14489            }
14490            if (r1.activityInfo != null) {
14491                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14492            }
14493            if (r1.serviceInfo != null) {
14494                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14495            }
14496            if (r1.providerInfo != null) {
14497                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14498            }
14499            return 0;
14500        }
14501    };
14502
14503    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14504            new Comparator<ProviderInfo>() {
14505        public int compare(ProviderInfo p1, ProviderInfo p2) {
14506            final int v1 = p1.initOrder;
14507            final int v2 = p2.initOrder;
14508            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14509        }
14510    };
14511
14512    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14513            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14514            final int[] userIds) {
14515        mHandler.post(new Runnable() {
14516            @Override
14517            public void run() {
14518                try {
14519                    final IActivityManager am = ActivityManager.getService();
14520                    if (am == null) return;
14521                    final int[] resolvedUserIds;
14522                    if (userIds == null) {
14523                        resolvedUserIds = am.getRunningUserIds();
14524                    } else {
14525                        resolvedUserIds = userIds;
14526                    }
14527                    for (int id : resolvedUserIds) {
14528                        final Intent intent = new Intent(action,
14529                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14530                        if (extras != null) {
14531                            intent.putExtras(extras);
14532                        }
14533                        if (targetPkg != null) {
14534                            intent.setPackage(targetPkg);
14535                        }
14536                        // Modify the UID when posting to other users
14537                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14538                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14539                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14540                            intent.putExtra(Intent.EXTRA_UID, uid);
14541                        }
14542                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14543                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14544                        if (DEBUG_BROADCASTS) {
14545                            RuntimeException here = new RuntimeException("here");
14546                            here.fillInStackTrace();
14547                            Slog.d(TAG, "Sending to user " + id + ": "
14548                                    + intent.toShortString(false, true, false, false)
14549                                    + " " + intent.getExtras(), here);
14550                        }
14551                        am.broadcastIntent(null, intent, null, finishedReceiver,
14552                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14553                                null, finishedReceiver != null, false, id);
14554                    }
14555                } catch (RemoteException ex) {
14556                }
14557            }
14558        });
14559    }
14560
14561    /**
14562     * Check if the external storage media is available. This is true if there
14563     * is a mounted external storage medium or if the external storage is
14564     * emulated.
14565     */
14566    private boolean isExternalMediaAvailable() {
14567        return mMediaMounted || Environment.isExternalStorageEmulated();
14568    }
14569
14570    @Override
14571    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14572        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14573            return null;
14574        }
14575        // writer
14576        synchronized (mPackages) {
14577            if (!isExternalMediaAvailable()) {
14578                // If the external storage is no longer mounted at this point,
14579                // the caller may not have been able to delete all of this
14580                // packages files and can not delete any more.  Bail.
14581                return null;
14582            }
14583            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14584            if (lastPackage != null) {
14585                pkgs.remove(lastPackage);
14586            }
14587            if (pkgs.size() > 0) {
14588                return pkgs.get(0);
14589            }
14590        }
14591        return null;
14592    }
14593
14594    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14595        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14596                userId, andCode ? 1 : 0, packageName);
14597        if (mSystemReady) {
14598            msg.sendToTarget();
14599        } else {
14600            if (mPostSystemReadyMessages == null) {
14601                mPostSystemReadyMessages = new ArrayList<>();
14602            }
14603            mPostSystemReadyMessages.add(msg);
14604        }
14605    }
14606
14607    void startCleaningPackages() {
14608        // reader
14609        if (!isExternalMediaAvailable()) {
14610            return;
14611        }
14612        synchronized (mPackages) {
14613            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14614                return;
14615            }
14616        }
14617        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14618        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14619        IActivityManager am = ActivityManager.getService();
14620        if (am != null) {
14621            int dcsUid = -1;
14622            synchronized (mPackages) {
14623                if (!mDefaultContainerWhitelisted) {
14624                    mDefaultContainerWhitelisted = true;
14625                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14626                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14627                }
14628            }
14629            try {
14630                if (dcsUid > 0) {
14631                    am.backgroundWhitelistUid(dcsUid);
14632                }
14633                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14634                        UserHandle.USER_SYSTEM);
14635            } catch (RemoteException e) {
14636            }
14637        }
14638    }
14639
14640    @Override
14641    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14642            int installFlags, String installerPackageName, int userId) {
14643        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14644
14645        final int callingUid = Binder.getCallingUid();
14646        enforceCrossUserPermission(callingUid, userId,
14647                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14648
14649        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14650            try {
14651                if (observer != null) {
14652                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14653                }
14654            } catch (RemoteException re) {
14655            }
14656            return;
14657        }
14658
14659        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14660            installFlags |= PackageManager.INSTALL_FROM_ADB;
14661
14662        } else {
14663            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14664            // about installerPackageName.
14665
14666            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14667            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14668        }
14669
14670        UserHandle user;
14671        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14672            user = UserHandle.ALL;
14673        } else {
14674            user = new UserHandle(userId);
14675        }
14676
14677        // Only system components can circumvent runtime permissions when installing.
14678        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14679                && mContext.checkCallingOrSelfPermission(Manifest.permission
14680                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14681            throw new SecurityException("You need the "
14682                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14683                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14684        }
14685
14686        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14687                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14688            throw new IllegalArgumentException(
14689                    "New installs into ASEC containers no longer supported");
14690        }
14691
14692        final File originFile = new File(originPath);
14693        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14694
14695        final Message msg = mHandler.obtainMessage(INIT_COPY);
14696        final VerificationInfo verificationInfo = new VerificationInfo(
14697                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14698        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14699                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14700                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14701                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14702        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14703        msg.obj = params;
14704
14705        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14706                System.identityHashCode(msg.obj));
14707        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14708                System.identityHashCode(msg.obj));
14709
14710        mHandler.sendMessage(msg);
14711    }
14712
14713
14714    /**
14715     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14716     * it is acting on behalf on an enterprise or the user).
14717     *
14718     * Note that the ordering of the conditionals in this method is important. The checks we perform
14719     * are as follows, in this order:
14720     *
14721     * 1) If the install is being performed by a system app, we can trust the app to have set the
14722     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14723     *    what it is.
14724     * 2) If the install is being performed by a device or profile owner app, the install reason
14725     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14726     *    set the install reason correctly. If the app targets an older SDK version where install
14727     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14728     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14729     * 3) In all other cases, the install is being performed by a regular app that is neither part
14730     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14731     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14732     *    set to enterprise policy and if so, change it to unknown instead.
14733     */
14734    private int fixUpInstallReason(String installerPackageName, int installerUid,
14735            int installReason) {
14736        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14737                == PERMISSION_GRANTED) {
14738            // If the install is being performed by a system app, we trust that app to have set the
14739            // install reason correctly.
14740            return installReason;
14741        }
14742
14743        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14744            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14745        if (dpm != null) {
14746            ComponentName owner = null;
14747            try {
14748                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14749                if (owner == null) {
14750                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14751                }
14752            } catch (RemoteException e) {
14753            }
14754            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14755                // If the install is being performed by a device or profile owner, the install
14756                // reason should be enterprise policy.
14757                return PackageManager.INSTALL_REASON_POLICY;
14758            }
14759        }
14760
14761        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14762            // If the install is being performed by a regular app (i.e. neither system app nor
14763            // device or profile owner), we have no reason to believe that the app is acting on
14764            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14765            // change it to unknown instead.
14766            return PackageManager.INSTALL_REASON_UNKNOWN;
14767        }
14768
14769        // If the install is being performed by a regular app and the install reason was set to any
14770        // value but enterprise policy, leave the install reason unchanged.
14771        return installReason;
14772    }
14773
14774    void installStage(String packageName, File stagedDir, String stagedCid,
14775            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14776            String installerPackageName, int installerUid, UserHandle user,
14777            Certificate[][] certificates) {
14778        if (DEBUG_EPHEMERAL) {
14779            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14780                Slog.d(TAG, "Ephemeral install of " + packageName);
14781            }
14782        }
14783        final VerificationInfo verificationInfo = new VerificationInfo(
14784                sessionParams.originatingUri, sessionParams.referrerUri,
14785                sessionParams.originatingUid, installerUid);
14786
14787        final OriginInfo origin;
14788        if (stagedDir != null) {
14789            origin = OriginInfo.fromStagedFile(stagedDir);
14790        } else {
14791            origin = OriginInfo.fromStagedContainer(stagedCid);
14792        }
14793
14794        final Message msg = mHandler.obtainMessage(INIT_COPY);
14795        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14796                sessionParams.installReason);
14797        final InstallParams params = new InstallParams(origin, null, observer,
14798                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14799                verificationInfo, user, sessionParams.abiOverride,
14800                sessionParams.grantedRuntimePermissions, certificates, installReason);
14801        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14802        msg.obj = params;
14803
14804        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14805                System.identityHashCode(msg.obj));
14806        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14807                System.identityHashCode(msg.obj));
14808
14809        mHandler.sendMessage(msg);
14810    }
14811
14812    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14813            int userId) {
14814        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14815        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14816                false /*startReceiver*/, pkgSetting.appId, userId);
14817
14818        // Send a session commit broadcast
14819        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14820        info.installReason = pkgSetting.getInstallReason(userId);
14821        info.appPackageName = packageName;
14822        sendSessionCommitBroadcast(info, userId);
14823    }
14824
14825    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14826            boolean includeStopped, int appId, int... userIds) {
14827        if (ArrayUtils.isEmpty(userIds)) {
14828            return;
14829        }
14830        Bundle extras = new Bundle(1);
14831        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14832        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14833
14834        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14835                packageName, extras, 0, null, null, userIds);
14836        if (sendBootCompleted) {
14837            mHandler.post(() -> {
14838                        for (int userId : userIds) {
14839                            sendBootCompletedBroadcastToSystemApp(
14840                                    packageName, includeStopped, userId);
14841                        }
14842                    }
14843            );
14844        }
14845    }
14846
14847    /**
14848     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14849     * automatically without needing an explicit launch.
14850     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14851     */
14852    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14853            int userId) {
14854        // If user is not running, the app didn't miss any broadcast
14855        if (!mUserManagerInternal.isUserRunning(userId)) {
14856            return;
14857        }
14858        final IActivityManager am = ActivityManager.getService();
14859        try {
14860            // Deliver LOCKED_BOOT_COMPLETED first
14861            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14862                    .setPackage(packageName);
14863            if (includeStopped) {
14864                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14865            }
14866            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14867            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14868                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14869
14870            // Deliver BOOT_COMPLETED only if user is unlocked
14871            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14872                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14873                if (includeStopped) {
14874                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14875                }
14876                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14877                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14878            }
14879        } catch (RemoteException e) {
14880            throw e.rethrowFromSystemServer();
14881        }
14882    }
14883
14884    @Override
14885    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14886            int userId) {
14887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14888        PackageSetting pkgSetting;
14889        final int callingUid = Binder.getCallingUid();
14890        enforceCrossUserPermission(callingUid, userId,
14891                true /* requireFullPermission */, true /* checkShell */,
14892                "setApplicationHiddenSetting for user " + userId);
14893
14894        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14895            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14896            return false;
14897        }
14898
14899        long callingId = Binder.clearCallingIdentity();
14900        try {
14901            boolean sendAdded = false;
14902            boolean sendRemoved = false;
14903            // writer
14904            synchronized (mPackages) {
14905                pkgSetting = mSettings.mPackages.get(packageName);
14906                if (pkgSetting == null) {
14907                    return false;
14908                }
14909                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14910                    return false;
14911                }
14912                // Do not allow "android" is being disabled
14913                if ("android".equals(packageName)) {
14914                    Slog.w(TAG, "Cannot hide package: android");
14915                    return false;
14916                }
14917                // Cannot hide static shared libs as they are considered
14918                // a part of the using app (emulating static linking). Also
14919                // static libs are installed always on internal storage.
14920                PackageParser.Package pkg = mPackages.get(packageName);
14921                if (pkg != null && pkg.staticSharedLibName != null) {
14922                    Slog.w(TAG, "Cannot hide package: " + packageName
14923                            + " providing static shared library: "
14924                            + pkg.staticSharedLibName);
14925                    return false;
14926                }
14927                // Only allow protected packages to hide themselves.
14928                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14929                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14930                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14931                    return false;
14932                }
14933
14934                if (pkgSetting.getHidden(userId) != hidden) {
14935                    pkgSetting.setHidden(hidden, userId);
14936                    mSettings.writePackageRestrictionsLPr(userId);
14937                    if (hidden) {
14938                        sendRemoved = true;
14939                    } else {
14940                        sendAdded = true;
14941                    }
14942                }
14943            }
14944            if (sendAdded) {
14945                sendPackageAddedForUser(packageName, pkgSetting, userId);
14946                return true;
14947            }
14948            if (sendRemoved) {
14949                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14950                        "hiding pkg");
14951                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14952                return true;
14953            }
14954        } finally {
14955            Binder.restoreCallingIdentity(callingId);
14956        }
14957        return false;
14958    }
14959
14960    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14961            int userId) {
14962        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14963        info.removedPackage = packageName;
14964        info.installerPackageName = pkgSetting.installerPackageName;
14965        info.removedUsers = new int[] {userId};
14966        info.broadcastUsers = new int[] {userId};
14967        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14968        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14969    }
14970
14971    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14972        if (pkgList.length > 0) {
14973            Bundle extras = new Bundle(1);
14974            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14975
14976            sendPackageBroadcast(
14977                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14978                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14979                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14980                    new int[] {userId});
14981        }
14982    }
14983
14984    /**
14985     * Returns true if application is not found or there was an error. Otherwise it returns
14986     * the hidden state of the package for the given user.
14987     */
14988    @Override
14989    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14990        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14991        final int callingUid = Binder.getCallingUid();
14992        enforceCrossUserPermission(callingUid, userId,
14993                true /* requireFullPermission */, false /* checkShell */,
14994                "getApplicationHidden for user " + userId);
14995        PackageSetting ps;
14996        long callingId = Binder.clearCallingIdentity();
14997        try {
14998            // writer
14999            synchronized (mPackages) {
15000                ps = mSettings.mPackages.get(packageName);
15001                if (ps == null) {
15002                    return true;
15003                }
15004                if (filterAppAccessLPr(ps, callingUid, userId)) {
15005                    return true;
15006                }
15007                return ps.getHidden(userId);
15008            }
15009        } finally {
15010            Binder.restoreCallingIdentity(callingId);
15011        }
15012    }
15013
15014    /**
15015     * @hide
15016     */
15017    @Override
15018    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
15019            int installReason) {
15020        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
15021                null);
15022        PackageSetting pkgSetting;
15023        final int callingUid = Binder.getCallingUid();
15024        enforceCrossUserPermission(callingUid, userId,
15025                true /* requireFullPermission */, true /* checkShell */,
15026                "installExistingPackage for user " + userId);
15027        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
15028            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
15029        }
15030
15031        long callingId = Binder.clearCallingIdentity();
15032        try {
15033            boolean installed = false;
15034            final boolean instantApp =
15035                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15036            final boolean fullApp =
15037                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
15038
15039            // writer
15040            synchronized (mPackages) {
15041                pkgSetting = mSettings.mPackages.get(packageName);
15042                if (pkgSetting == null) {
15043                    return PackageManager.INSTALL_FAILED_INVALID_URI;
15044                }
15045                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
15046                    // only allow the existing package to be used if it's installed as a full
15047                    // application for at least one user
15048                    boolean installAllowed = false;
15049                    for (int checkUserId : sUserManager.getUserIds()) {
15050                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
15051                        if (installAllowed) {
15052                            break;
15053                        }
15054                    }
15055                    if (!installAllowed) {
15056                        return PackageManager.INSTALL_FAILED_INVALID_URI;
15057                    }
15058                }
15059                if (!pkgSetting.getInstalled(userId)) {
15060                    pkgSetting.setInstalled(true, userId);
15061                    pkgSetting.setHidden(false, userId);
15062                    pkgSetting.setInstallReason(installReason, userId);
15063                    mSettings.writePackageRestrictionsLPr(userId);
15064                    mSettings.writeKernelMappingLPr(pkgSetting);
15065                    installed = true;
15066                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15067                    // upgrade app from instant to full; we don't allow app downgrade
15068                    installed = true;
15069                }
15070                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
15071            }
15072
15073            if (installed) {
15074                if (pkgSetting.pkg != null) {
15075                    synchronized (mInstallLock) {
15076                        // We don't need to freeze for a brand new install
15077                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
15078                    }
15079                }
15080                sendPackageAddedForUser(packageName, pkgSetting, userId);
15081                synchronized (mPackages) {
15082                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
15083                }
15084            }
15085        } finally {
15086            Binder.restoreCallingIdentity(callingId);
15087        }
15088
15089        return PackageManager.INSTALL_SUCCEEDED;
15090    }
15091
15092    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
15093            boolean instantApp, boolean fullApp) {
15094        // no state specified; do nothing
15095        if (!instantApp && !fullApp) {
15096            return;
15097        }
15098        if (userId != UserHandle.USER_ALL) {
15099            if (instantApp && !pkgSetting.getInstantApp(userId)) {
15100                pkgSetting.setInstantApp(true /*instantApp*/, userId);
15101            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
15102                pkgSetting.setInstantApp(false /*instantApp*/, userId);
15103            }
15104        } else {
15105            for (int currentUserId : sUserManager.getUserIds()) {
15106                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
15107                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
15108                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
15109                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
15110                }
15111            }
15112        }
15113    }
15114
15115    boolean isUserRestricted(int userId, String restrictionKey) {
15116        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15117        if (restrictions.getBoolean(restrictionKey, false)) {
15118            Log.w(TAG, "User is restricted: " + restrictionKey);
15119            return true;
15120        }
15121        return false;
15122    }
15123
15124    @Override
15125    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15126            int userId) {
15127        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15128        final int callingUid = Binder.getCallingUid();
15129        enforceCrossUserPermission(callingUid, userId,
15130                true /* requireFullPermission */, true /* checkShell */,
15131                "setPackagesSuspended for user " + userId);
15132
15133        if (ArrayUtils.isEmpty(packageNames)) {
15134            return packageNames;
15135        }
15136
15137        // List of package names for whom the suspended state has changed.
15138        List<String> changedPackages = new ArrayList<>(packageNames.length);
15139        // List of package names for whom the suspended state is not set as requested in this
15140        // method.
15141        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15142        long callingId = Binder.clearCallingIdentity();
15143        try {
15144            for (int i = 0; i < packageNames.length; i++) {
15145                String packageName = packageNames[i];
15146                boolean changed = false;
15147                final int appId;
15148                synchronized (mPackages) {
15149                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15150                    if (pkgSetting == null
15151                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15152                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15153                                + "\". Skipping suspending/un-suspending.");
15154                        unactionedPackages.add(packageName);
15155                        continue;
15156                    }
15157                    appId = pkgSetting.appId;
15158                    if (pkgSetting.getSuspended(userId) != suspended) {
15159                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15160                            unactionedPackages.add(packageName);
15161                            continue;
15162                        }
15163                        pkgSetting.setSuspended(suspended, userId);
15164                        mSettings.writePackageRestrictionsLPr(userId);
15165                        changed = true;
15166                        changedPackages.add(packageName);
15167                    }
15168                }
15169
15170                if (changed && suspended) {
15171                    killApplication(packageName, UserHandle.getUid(userId, appId),
15172                            "suspending package");
15173                }
15174            }
15175        } finally {
15176            Binder.restoreCallingIdentity(callingId);
15177        }
15178
15179        if (!changedPackages.isEmpty()) {
15180            sendPackagesSuspendedForUser(changedPackages.toArray(
15181                    new String[changedPackages.size()]), userId, suspended);
15182        }
15183
15184        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15185    }
15186
15187    @Override
15188    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15189        final int callingUid = Binder.getCallingUid();
15190        enforceCrossUserPermission(callingUid, userId,
15191                true /* requireFullPermission */, false /* checkShell */,
15192                "isPackageSuspendedForUser for user " + userId);
15193        synchronized (mPackages) {
15194            final PackageSetting ps = mSettings.mPackages.get(packageName);
15195            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15196                throw new IllegalArgumentException("Unknown target package: " + packageName);
15197            }
15198            return ps.getSuspended(userId);
15199        }
15200    }
15201
15202    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15203        if (isPackageDeviceAdmin(packageName, userId)) {
15204            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15205                    + "\": has an active device admin");
15206            return false;
15207        }
15208
15209        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15210        if (packageName.equals(activeLauncherPackageName)) {
15211            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15212                    + "\": contains the active launcher");
15213            return false;
15214        }
15215
15216        if (packageName.equals(mRequiredInstallerPackage)) {
15217            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15218                    + "\": required for package installation");
15219            return false;
15220        }
15221
15222        if (packageName.equals(mRequiredUninstallerPackage)) {
15223            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15224                    + "\": required for package uninstallation");
15225            return false;
15226        }
15227
15228        if (packageName.equals(mRequiredVerifierPackage)) {
15229            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15230                    + "\": required for package verification");
15231            return false;
15232        }
15233
15234        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15235            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15236                    + "\": is the default dialer");
15237            return false;
15238        }
15239
15240        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15241            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15242                    + "\": protected package");
15243            return false;
15244        }
15245
15246        // Cannot suspend static shared libs as they are considered
15247        // a part of the using app (emulating static linking). Also
15248        // static libs are installed always on internal storage.
15249        PackageParser.Package pkg = mPackages.get(packageName);
15250        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15251            Slog.w(TAG, "Cannot suspend package: " + packageName
15252                    + " providing static shared library: "
15253                    + pkg.staticSharedLibName);
15254            return false;
15255        }
15256
15257        return true;
15258    }
15259
15260    private String getActiveLauncherPackageName(int userId) {
15261        Intent intent = new Intent(Intent.ACTION_MAIN);
15262        intent.addCategory(Intent.CATEGORY_HOME);
15263        ResolveInfo resolveInfo = resolveIntent(
15264                intent,
15265                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15266                PackageManager.MATCH_DEFAULT_ONLY,
15267                userId);
15268
15269        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15270    }
15271
15272    private String getDefaultDialerPackageName(int userId) {
15273        synchronized (mPackages) {
15274            return mSettings.getDefaultDialerPackageNameLPw(userId);
15275        }
15276    }
15277
15278    @Override
15279    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15280        mContext.enforceCallingOrSelfPermission(
15281                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15282                "Only package verification agents can verify applications");
15283
15284        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15285        final PackageVerificationResponse response = new PackageVerificationResponse(
15286                verificationCode, Binder.getCallingUid());
15287        msg.arg1 = id;
15288        msg.obj = response;
15289        mHandler.sendMessage(msg);
15290    }
15291
15292    @Override
15293    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15294            long millisecondsToDelay) {
15295        mContext.enforceCallingOrSelfPermission(
15296                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15297                "Only package verification agents can extend verification timeouts");
15298
15299        final PackageVerificationState state = mPendingVerification.get(id);
15300        final PackageVerificationResponse response = new PackageVerificationResponse(
15301                verificationCodeAtTimeout, Binder.getCallingUid());
15302
15303        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15304            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15305        }
15306        if (millisecondsToDelay < 0) {
15307            millisecondsToDelay = 0;
15308        }
15309        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15310                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15311            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15312        }
15313
15314        if ((state != null) && !state.timeoutExtended()) {
15315            state.extendTimeout();
15316
15317            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15318            msg.arg1 = id;
15319            msg.obj = response;
15320            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15321        }
15322    }
15323
15324    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15325            int verificationCode, UserHandle user) {
15326        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15327        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15328        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15329        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15330        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15331
15332        mContext.sendBroadcastAsUser(intent, user,
15333                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15334    }
15335
15336    private ComponentName matchComponentForVerifier(String packageName,
15337            List<ResolveInfo> receivers) {
15338        ActivityInfo targetReceiver = null;
15339
15340        final int NR = receivers.size();
15341        for (int i = 0; i < NR; i++) {
15342            final ResolveInfo info = receivers.get(i);
15343            if (info.activityInfo == null) {
15344                continue;
15345            }
15346
15347            if (packageName.equals(info.activityInfo.packageName)) {
15348                targetReceiver = info.activityInfo;
15349                break;
15350            }
15351        }
15352
15353        if (targetReceiver == null) {
15354            return null;
15355        }
15356
15357        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15358    }
15359
15360    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15361            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15362        if (pkgInfo.verifiers.length == 0) {
15363            return null;
15364        }
15365
15366        final int N = pkgInfo.verifiers.length;
15367        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15368        for (int i = 0; i < N; i++) {
15369            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15370
15371            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15372                    receivers);
15373            if (comp == null) {
15374                continue;
15375            }
15376
15377            final int verifierUid = getUidForVerifier(verifierInfo);
15378            if (verifierUid == -1) {
15379                continue;
15380            }
15381
15382            if (DEBUG_VERIFY) {
15383                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15384                        + " with the correct signature");
15385            }
15386            sufficientVerifiers.add(comp);
15387            verificationState.addSufficientVerifier(verifierUid);
15388        }
15389
15390        return sufficientVerifiers;
15391    }
15392
15393    private int getUidForVerifier(VerifierInfo verifierInfo) {
15394        synchronized (mPackages) {
15395            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15396            if (pkg == null) {
15397                return -1;
15398            } else if (pkg.mSignatures.length != 1) {
15399                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15400                        + " has more than one signature; ignoring");
15401                return -1;
15402            }
15403
15404            /*
15405             * If the public key of the package's signature does not match
15406             * our expected public key, then this is a different package and
15407             * we should skip.
15408             */
15409
15410            final byte[] expectedPublicKey;
15411            try {
15412                final Signature verifierSig = pkg.mSignatures[0];
15413                final PublicKey publicKey = verifierSig.getPublicKey();
15414                expectedPublicKey = publicKey.getEncoded();
15415            } catch (CertificateException e) {
15416                return -1;
15417            }
15418
15419            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15420
15421            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15422                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15423                        + " does not have the expected public key; ignoring");
15424                return -1;
15425            }
15426
15427            return pkg.applicationInfo.uid;
15428        }
15429    }
15430
15431    @Override
15432    public void finishPackageInstall(int token, boolean didLaunch) {
15433        enforceSystemOrRoot("Only the system is allowed to finish installs");
15434
15435        if (DEBUG_INSTALL) {
15436            Slog.v(TAG, "BM finishing package install for " + token);
15437        }
15438        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15439
15440        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15441        mHandler.sendMessage(msg);
15442    }
15443
15444    /**
15445     * Get the verification agent timeout.  Used for both the APK verifier and the
15446     * intent filter verifier.
15447     *
15448     * @return verification timeout in milliseconds
15449     */
15450    private long getVerificationTimeout() {
15451        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15452                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15453                DEFAULT_VERIFICATION_TIMEOUT);
15454    }
15455
15456    /**
15457     * Get the default verification agent response code.
15458     *
15459     * @return default verification response code
15460     */
15461    private int getDefaultVerificationResponse(UserHandle user) {
15462        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15463            return PackageManager.VERIFICATION_REJECT;
15464        }
15465        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15466                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15467                DEFAULT_VERIFICATION_RESPONSE);
15468    }
15469
15470    /**
15471     * Check whether or not package verification has been enabled.
15472     *
15473     * @return true if verification should be performed
15474     */
15475    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15476        if (!DEFAULT_VERIFY_ENABLE) {
15477            return false;
15478        }
15479
15480        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15481
15482        // Check if installing from ADB
15483        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15484            // Do not run verification in a test harness environment
15485            if (ActivityManager.isRunningInTestHarness()) {
15486                return false;
15487            }
15488            if (ensureVerifyAppsEnabled) {
15489                return true;
15490            }
15491            // Check if the developer does not want package verification for ADB installs
15492            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15493                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15494                return false;
15495            }
15496        } else {
15497            // only when not installed from ADB, skip verification for instant apps when
15498            // the installer and verifier are the same.
15499            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15500                if (mInstantAppInstallerActivity != null
15501                        && mInstantAppInstallerActivity.packageName.equals(
15502                                mRequiredVerifierPackage)) {
15503                    try {
15504                        mContext.getSystemService(AppOpsManager.class)
15505                                .checkPackage(installerUid, mRequiredVerifierPackage);
15506                        if (DEBUG_VERIFY) {
15507                            Slog.i(TAG, "disable verification for instant app");
15508                        }
15509                        return false;
15510                    } catch (SecurityException ignore) { }
15511                }
15512            }
15513        }
15514
15515        if (ensureVerifyAppsEnabled) {
15516            return true;
15517        }
15518
15519        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15520                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15521    }
15522
15523    @Override
15524    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15525            throws RemoteException {
15526        mContext.enforceCallingOrSelfPermission(
15527                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15528                "Only intentfilter verification agents can verify applications");
15529
15530        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15531        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15532                Binder.getCallingUid(), verificationCode, failedDomains);
15533        msg.arg1 = id;
15534        msg.obj = response;
15535        mHandler.sendMessage(msg);
15536    }
15537
15538    @Override
15539    public int getIntentVerificationStatus(String packageName, int userId) {
15540        final int callingUid = Binder.getCallingUid();
15541        if (UserHandle.getUserId(callingUid) != userId) {
15542            mContext.enforceCallingOrSelfPermission(
15543                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15544                    "getIntentVerificationStatus" + userId);
15545        }
15546        if (getInstantAppPackageName(callingUid) != null) {
15547            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15548        }
15549        synchronized (mPackages) {
15550            final PackageSetting ps = mSettings.mPackages.get(packageName);
15551            if (ps == null
15552                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15553                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15554            }
15555            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15556        }
15557    }
15558
15559    @Override
15560    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15561        mContext.enforceCallingOrSelfPermission(
15562                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15563
15564        boolean result = false;
15565        synchronized (mPackages) {
15566            final PackageSetting ps = mSettings.mPackages.get(packageName);
15567            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15568                return false;
15569            }
15570            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15571        }
15572        if (result) {
15573            scheduleWritePackageRestrictionsLocked(userId);
15574        }
15575        return result;
15576    }
15577
15578    @Override
15579    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15580            String packageName) {
15581        final int callingUid = Binder.getCallingUid();
15582        if (getInstantAppPackageName(callingUid) != null) {
15583            return ParceledListSlice.emptyList();
15584        }
15585        synchronized (mPackages) {
15586            final PackageSetting ps = mSettings.mPackages.get(packageName);
15587            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15588                return ParceledListSlice.emptyList();
15589            }
15590            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15591        }
15592    }
15593
15594    @Override
15595    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15596        if (TextUtils.isEmpty(packageName)) {
15597            return ParceledListSlice.emptyList();
15598        }
15599        final int callingUid = Binder.getCallingUid();
15600        final int callingUserId = UserHandle.getUserId(callingUid);
15601        synchronized (mPackages) {
15602            PackageParser.Package pkg = mPackages.get(packageName);
15603            if (pkg == null || pkg.activities == null) {
15604                return ParceledListSlice.emptyList();
15605            }
15606            if (pkg.mExtras == null) {
15607                return ParceledListSlice.emptyList();
15608            }
15609            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15610            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15611                return ParceledListSlice.emptyList();
15612            }
15613            final int count = pkg.activities.size();
15614            ArrayList<IntentFilter> result = new ArrayList<>();
15615            for (int n=0; n<count; n++) {
15616                PackageParser.Activity activity = pkg.activities.get(n);
15617                if (activity.intents != null && activity.intents.size() > 0) {
15618                    result.addAll(activity.intents);
15619                }
15620            }
15621            return new ParceledListSlice<>(result);
15622        }
15623    }
15624
15625    @Override
15626    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15627        mContext.enforceCallingOrSelfPermission(
15628                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15629        if (UserHandle.getCallingUserId() != userId) {
15630            mContext.enforceCallingOrSelfPermission(
15631                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15632        }
15633
15634        synchronized (mPackages) {
15635            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15636            if (packageName != null) {
15637                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15638                        packageName, userId);
15639            }
15640            return result;
15641        }
15642    }
15643
15644    @Override
15645    public String getDefaultBrowserPackageName(int userId) {
15646        if (UserHandle.getCallingUserId() != userId) {
15647            mContext.enforceCallingOrSelfPermission(
15648                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15649        }
15650        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15651            return null;
15652        }
15653        synchronized (mPackages) {
15654            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15655        }
15656    }
15657
15658    /**
15659     * Get the "allow unknown sources" setting.
15660     *
15661     * @return the current "allow unknown sources" setting
15662     */
15663    private int getUnknownSourcesSettings() {
15664        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15665                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15666                -1);
15667    }
15668
15669    @Override
15670    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15671        final int callingUid = Binder.getCallingUid();
15672        if (getInstantAppPackageName(callingUid) != null) {
15673            return;
15674        }
15675        // writer
15676        synchronized (mPackages) {
15677            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15678            if (targetPackageSetting == null
15679                    || filterAppAccessLPr(
15680                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15681                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15682            }
15683
15684            PackageSetting installerPackageSetting;
15685            if (installerPackageName != null) {
15686                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15687                if (installerPackageSetting == null) {
15688                    throw new IllegalArgumentException("Unknown installer package: "
15689                            + installerPackageName);
15690                }
15691            } else {
15692                installerPackageSetting = null;
15693            }
15694
15695            Signature[] callerSignature;
15696            Object obj = mSettings.getUserIdLPr(callingUid);
15697            if (obj != null) {
15698                if (obj instanceof SharedUserSetting) {
15699                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15700                } else if (obj instanceof PackageSetting) {
15701                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15702                } else {
15703                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15704                }
15705            } else {
15706                throw new SecurityException("Unknown calling UID: " + callingUid);
15707            }
15708
15709            // Verify: can't set installerPackageName to a package that is
15710            // not signed with the same cert as the caller.
15711            if (installerPackageSetting != null) {
15712                if (compareSignatures(callerSignature,
15713                        installerPackageSetting.signatures.mSignatures)
15714                        != PackageManager.SIGNATURE_MATCH) {
15715                    throw new SecurityException(
15716                            "Caller does not have same cert as new installer package "
15717                            + installerPackageName);
15718                }
15719            }
15720
15721            // Verify: if target already has an installer package, it must
15722            // be signed with the same cert as the caller.
15723            if (targetPackageSetting.installerPackageName != null) {
15724                PackageSetting setting = mSettings.mPackages.get(
15725                        targetPackageSetting.installerPackageName);
15726                // If the currently set package isn't valid, then it's always
15727                // okay to change it.
15728                if (setting != null) {
15729                    if (compareSignatures(callerSignature,
15730                            setting.signatures.mSignatures)
15731                            != PackageManager.SIGNATURE_MATCH) {
15732                        throw new SecurityException(
15733                                "Caller does not have same cert as old installer package "
15734                                + targetPackageSetting.installerPackageName);
15735                    }
15736                }
15737            }
15738
15739            // Okay!
15740            targetPackageSetting.installerPackageName = installerPackageName;
15741            if (installerPackageName != null) {
15742                mSettings.mInstallerPackages.add(installerPackageName);
15743            }
15744            scheduleWriteSettingsLocked();
15745        }
15746    }
15747
15748    @Override
15749    public void setApplicationCategoryHint(String packageName, int categoryHint,
15750            String callerPackageName) {
15751        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15752            throw new SecurityException("Instant applications don't have access to this method");
15753        }
15754        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15755                callerPackageName);
15756        synchronized (mPackages) {
15757            PackageSetting ps = mSettings.mPackages.get(packageName);
15758            if (ps == null) {
15759                throw new IllegalArgumentException("Unknown target package " + packageName);
15760            }
15761            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15762                throw new IllegalArgumentException("Unknown target package " + packageName);
15763            }
15764            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15765                throw new IllegalArgumentException("Calling package " + callerPackageName
15766                        + " is not installer for " + packageName);
15767            }
15768
15769            if (ps.categoryHint != categoryHint) {
15770                ps.categoryHint = categoryHint;
15771                scheduleWriteSettingsLocked();
15772            }
15773        }
15774    }
15775
15776    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15777        // Queue up an async operation since the package installation may take a little while.
15778        mHandler.post(new Runnable() {
15779            public void run() {
15780                mHandler.removeCallbacks(this);
15781                 // Result object to be returned
15782                PackageInstalledInfo res = new PackageInstalledInfo();
15783                res.setReturnCode(currentStatus);
15784                res.uid = -1;
15785                res.pkg = null;
15786                res.removedInfo = null;
15787                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15788                    args.doPreInstall(res.returnCode);
15789                    synchronized (mInstallLock) {
15790                        installPackageTracedLI(args, res);
15791                    }
15792                    args.doPostInstall(res.returnCode, res.uid);
15793                }
15794
15795                // A restore should be performed at this point if (a) the install
15796                // succeeded, (b) the operation is not an update, and (c) the new
15797                // package has not opted out of backup participation.
15798                final boolean update = res.removedInfo != null
15799                        && res.removedInfo.removedPackage != null;
15800                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15801                boolean doRestore = !update
15802                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15803
15804                // Set up the post-install work request bookkeeping.  This will be used
15805                // and cleaned up by the post-install event handling regardless of whether
15806                // there's a restore pass performed.  Token values are >= 1.
15807                int token;
15808                if (mNextInstallToken < 0) mNextInstallToken = 1;
15809                token = mNextInstallToken++;
15810
15811                PostInstallData data = new PostInstallData(args, res);
15812                mRunningInstalls.put(token, data);
15813                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15814
15815                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15816                    // Pass responsibility to the Backup Manager.  It will perform a
15817                    // restore if appropriate, then pass responsibility back to the
15818                    // Package Manager to run the post-install observer callbacks
15819                    // and broadcasts.
15820                    IBackupManager bm = IBackupManager.Stub.asInterface(
15821                            ServiceManager.getService(Context.BACKUP_SERVICE));
15822                    if (bm != null) {
15823                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15824                                + " to BM for possible restore");
15825                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15826                        try {
15827                            // TODO: http://b/22388012
15828                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15829                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15830                            } else {
15831                                doRestore = false;
15832                            }
15833                        } catch (RemoteException e) {
15834                            // can't happen; the backup manager is local
15835                        } catch (Exception e) {
15836                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15837                            doRestore = false;
15838                        }
15839                    } else {
15840                        Slog.e(TAG, "Backup Manager not found!");
15841                        doRestore = false;
15842                    }
15843                }
15844
15845                if (!doRestore) {
15846                    // No restore possible, or the Backup Manager was mysteriously not
15847                    // available -- just fire the post-install work request directly.
15848                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15849
15850                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15851
15852                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15853                    mHandler.sendMessage(msg);
15854                }
15855            }
15856        });
15857    }
15858
15859    /**
15860     * Callback from PackageSettings whenever an app is first transitioned out of the
15861     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15862     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15863     * here whether the app is the target of an ongoing install, and only send the
15864     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15865     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15866     * handling.
15867     */
15868    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15869        // Serialize this with the rest of the install-process message chain.  In the
15870        // restore-at-install case, this Runnable will necessarily run before the
15871        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15872        // are coherent.  In the non-restore case, the app has already completed install
15873        // and been launched through some other means, so it is not in a problematic
15874        // state for observers to see the FIRST_LAUNCH signal.
15875        mHandler.post(new Runnable() {
15876            @Override
15877            public void run() {
15878                for (int i = 0; i < mRunningInstalls.size(); i++) {
15879                    final PostInstallData data = mRunningInstalls.valueAt(i);
15880                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15881                        continue;
15882                    }
15883                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15884                        // right package; but is it for the right user?
15885                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15886                            if (userId == data.res.newUsers[uIndex]) {
15887                                if (DEBUG_BACKUP) {
15888                                    Slog.i(TAG, "Package " + pkgName
15889                                            + " being restored so deferring FIRST_LAUNCH");
15890                                }
15891                                return;
15892                            }
15893                        }
15894                    }
15895                }
15896                // didn't find it, so not being restored
15897                if (DEBUG_BACKUP) {
15898                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15899                }
15900                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15901            }
15902        });
15903    }
15904
15905    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15906        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15907                installerPkg, null, userIds);
15908    }
15909
15910    private abstract class HandlerParams {
15911        private static final int MAX_RETRIES = 4;
15912
15913        /**
15914         * Number of times startCopy() has been attempted and had a non-fatal
15915         * error.
15916         */
15917        private int mRetries = 0;
15918
15919        /** User handle for the user requesting the information or installation. */
15920        private final UserHandle mUser;
15921        String traceMethod;
15922        int traceCookie;
15923
15924        HandlerParams(UserHandle user) {
15925            mUser = user;
15926        }
15927
15928        UserHandle getUser() {
15929            return mUser;
15930        }
15931
15932        HandlerParams setTraceMethod(String traceMethod) {
15933            this.traceMethod = traceMethod;
15934            return this;
15935        }
15936
15937        HandlerParams setTraceCookie(int traceCookie) {
15938            this.traceCookie = traceCookie;
15939            return this;
15940        }
15941
15942        final boolean startCopy() {
15943            boolean res;
15944            try {
15945                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15946
15947                if (++mRetries > MAX_RETRIES) {
15948                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15949                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15950                    handleServiceError();
15951                    return false;
15952                } else {
15953                    handleStartCopy();
15954                    res = true;
15955                }
15956            } catch (RemoteException e) {
15957                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15958                mHandler.sendEmptyMessage(MCS_RECONNECT);
15959                res = false;
15960            }
15961            handleReturnCode();
15962            return res;
15963        }
15964
15965        final void serviceError() {
15966            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15967            handleServiceError();
15968            handleReturnCode();
15969        }
15970
15971        abstract void handleStartCopy() throws RemoteException;
15972        abstract void handleServiceError();
15973        abstract void handleReturnCode();
15974    }
15975
15976    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15977        for (File path : paths) {
15978            try {
15979                mcs.clearDirectory(path.getAbsolutePath());
15980            } catch (RemoteException e) {
15981            }
15982        }
15983    }
15984
15985    static class OriginInfo {
15986        /**
15987         * Location where install is coming from, before it has been
15988         * copied/renamed into place. This could be a single monolithic APK
15989         * file, or a cluster directory. This location may be untrusted.
15990         */
15991        final File file;
15992        final String cid;
15993
15994        /**
15995         * Flag indicating that {@link #file} or {@link #cid} has already been
15996         * staged, meaning downstream users don't need to defensively copy the
15997         * contents.
15998         */
15999        final boolean staged;
16000
16001        /**
16002         * Flag indicating that {@link #file} or {@link #cid} is an already
16003         * installed app that is being moved.
16004         */
16005        final boolean existing;
16006
16007        final String resolvedPath;
16008        final File resolvedFile;
16009
16010        static OriginInfo fromNothing() {
16011            return new OriginInfo(null, null, false, false);
16012        }
16013
16014        static OriginInfo fromUntrustedFile(File file) {
16015            return new OriginInfo(file, null, false, false);
16016        }
16017
16018        static OriginInfo fromExistingFile(File file) {
16019            return new OriginInfo(file, null, false, true);
16020        }
16021
16022        static OriginInfo fromStagedFile(File file) {
16023            return new OriginInfo(file, null, true, false);
16024        }
16025
16026        static OriginInfo fromStagedContainer(String cid) {
16027            return new OriginInfo(null, cid, true, false);
16028        }
16029
16030        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
16031            this.file = file;
16032            this.cid = cid;
16033            this.staged = staged;
16034            this.existing = existing;
16035
16036            if (cid != null) {
16037                resolvedPath = PackageHelper.getSdDir(cid);
16038                resolvedFile = new File(resolvedPath);
16039            } else if (file != null) {
16040                resolvedPath = file.getAbsolutePath();
16041                resolvedFile = file;
16042            } else {
16043                resolvedPath = null;
16044                resolvedFile = null;
16045            }
16046        }
16047    }
16048
16049    static class MoveInfo {
16050        final int moveId;
16051        final String fromUuid;
16052        final String toUuid;
16053        final String packageName;
16054        final String dataAppName;
16055        final int appId;
16056        final String seinfo;
16057        final int targetSdkVersion;
16058
16059        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
16060                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
16061            this.moveId = moveId;
16062            this.fromUuid = fromUuid;
16063            this.toUuid = toUuid;
16064            this.packageName = packageName;
16065            this.dataAppName = dataAppName;
16066            this.appId = appId;
16067            this.seinfo = seinfo;
16068            this.targetSdkVersion = targetSdkVersion;
16069        }
16070    }
16071
16072    static class VerificationInfo {
16073        /** A constant used to indicate that a uid value is not present. */
16074        public static final int NO_UID = -1;
16075
16076        /** URI referencing where the package was downloaded from. */
16077        final Uri originatingUri;
16078
16079        /** HTTP referrer URI associated with the originatingURI. */
16080        final Uri referrer;
16081
16082        /** UID of the application that the install request originated from. */
16083        final int originatingUid;
16084
16085        /** UID of application requesting the install */
16086        final int installerUid;
16087
16088        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
16089            this.originatingUri = originatingUri;
16090            this.referrer = referrer;
16091            this.originatingUid = originatingUid;
16092            this.installerUid = installerUid;
16093        }
16094    }
16095
16096    class InstallParams extends HandlerParams {
16097        final OriginInfo origin;
16098        final MoveInfo move;
16099        final IPackageInstallObserver2 observer;
16100        int installFlags;
16101        final String installerPackageName;
16102        final String volumeUuid;
16103        private InstallArgs mArgs;
16104        private int mRet;
16105        final String packageAbiOverride;
16106        final String[] grantedRuntimePermissions;
16107        final VerificationInfo verificationInfo;
16108        final Certificate[][] certificates;
16109        final int installReason;
16110
16111        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16112                int installFlags, String installerPackageName, String volumeUuid,
16113                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16114                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16115            super(user);
16116            this.origin = origin;
16117            this.move = move;
16118            this.observer = observer;
16119            this.installFlags = installFlags;
16120            this.installerPackageName = installerPackageName;
16121            this.volumeUuid = volumeUuid;
16122            this.verificationInfo = verificationInfo;
16123            this.packageAbiOverride = packageAbiOverride;
16124            this.grantedRuntimePermissions = grantedPermissions;
16125            this.certificates = certificates;
16126            this.installReason = installReason;
16127        }
16128
16129        @Override
16130        public String toString() {
16131            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16132                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16133        }
16134
16135        private int installLocationPolicy(PackageInfoLite pkgLite) {
16136            String packageName = pkgLite.packageName;
16137            int installLocation = pkgLite.installLocation;
16138            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16139            // reader
16140            synchronized (mPackages) {
16141                // Currently installed package which the new package is attempting to replace or
16142                // null if no such package is installed.
16143                PackageParser.Package installedPkg = mPackages.get(packageName);
16144                // Package which currently owns the data which the new package will own if installed.
16145                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16146                // will be null whereas dataOwnerPkg will contain information about the package
16147                // which was uninstalled while keeping its data.
16148                PackageParser.Package dataOwnerPkg = installedPkg;
16149                if (dataOwnerPkg  == null) {
16150                    PackageSetting ps = mSettings.mPackages.get(packageName);
16151                    if (ps != null) {
16152                        dataOwnerPkg = ps.pkg;
16153                    }
16154                }
16155
16156                if (dataOwnerPkg != null) {
16157                    // If installed, the package will get access to data left on the device by its
16158                    // predecessor. As a security measure, this is permited only if this is not a
16159                    // version downgrade or if the predecessor package is marked as debuggable and
16160                    // a downgrade is explicitly requested.
16161                    //
16162                    // On debuggable platform builds, downgrades are permitted even for
16163                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16164                    // not offer security guarantees and thus it's OK to disable some security
16165                    // mechanisms to make debugging/testing easier on those builds. However, even on
16166                    // debuggable builds downgrades of packages are permitted only if requested via
16167                    // installFlags. This is because we aim to keep the behavior of debuggable
16168                    // platform builds as close as possible to the behavior of non-debuggable
16169                    // platform builds.
16170                    final boolean downgradeRequested =
16171                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16172                    final boolean packageDebuggable =
16173                                (dataOwnerPkg.applicationInfo.flags
16174                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16175                    final boolean downgradePermitted =
16176                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16177                    if (!downgradePermitted) {
16178                        try {
16179                            checkDowngrade(dataOwnerPkg, pkgLite);
16180                        } catch (PackageManagerException e) {
16181                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16182                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16183                        }
16184                    }
16185                }
16186
16187                if (installedPkg != null) {
16188                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16189                        // Check for updated system application.
16190                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16191                            if (onSd) {
16192                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16193                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16194                            }
16195                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16196                        } else {
16197                            if (onSd) {
16198                                // Install flag overrides everything.
16199                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16200                            }
16201                            // If current upgrade specifies particular preference
16202                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16203                                // Application explicitly specified internal.
16204                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16205                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16206                                // App explictly prefers external. Let policy decide
16207                            } else {
16208                                // Prefer previous location
16209                                if (isExternal(installedPkg)) {
16210                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16211                                }
16212                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16213                            }
16214                        }
16215                    } else {
16216                        // Invalid install. Return error code
16217                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16218                    }
16219                }
16220            }
16221            // All the special cases have been taken care of.
16222            // Return result based on recommended install location.
16223            if (onSd) {
16224                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16225            }
16226            return pkgLite.recommendedInstallLocation;
16227        }
16228
16229        /*
16230         * Invoke remote method to get package information and install
16231         * location values. Override install location based on default
16232         * policy if needed and then create install arguments based
16233         * on the install location.
16234         */
16235        public void handleStartCopy() throws RemoteException {
16236            int ret = PackageManager.INSTALL_SUCCEEDED;
16237
16238            // If we're already staged, we've firmly committed to an install location
16239            if (origin.staged) {
16240                if (origin.file != null) {
16241                    installFlags |= PackageManager.INSTALL_INTERNAL;
16242                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16243                } else if (origin.cid != null) {
16244                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16245                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16246                } else {
16247                    throw new IllegalStateException("Invalid stage location");
16248                }
16249            }
16250
16251            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16252            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16253            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16254            PackageInfoLite pkgLite = null;
16255
16256            if (onInt && onSd) {
16257                // Check if both bits are set.
16258                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16259                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16260            } else if (onSd && ephemeral) {
16261                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16262                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16263            } else {
16264                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16265                        packageAbiOverride);
16266
16267                if (DEBUG_EPHEMERAL && ephemeral) {
16268                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16269                }
16270
16271                /*
16272                 * If we have too little free space, try to free cache
16273                 * before giving up.
16274                 */
16275                if (!origin.staged && pkgLite.recommendedInstallLocation
16276                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16277                    // TODO: focus freeing disk space on the target device
16278                    final StorageManager storage = StorageManager.from(mContext);
16279                    final long lowThreshold = storage.getStorageLowBytes(
16280                            Environment.getDataDirectory());
16281
16282                    final long sizeBytes = mContainerService.calculateInstalledSize(
16283                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16284
16285                    try {
16286                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16287                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16288                                installFlags, packageAbiOverride);
16289                    } catch (InstallerException e) {
16290                        Slog.w(TAG, "Failed to free cache", e);
16291                    }
16292
16293                    /*
16294                     * The cache free must have deleted the file we
16295                     * downloaded to install.
16296                     *
16297                     * TODO: fix the "freeCache" call to not delete
16298                     *       the file we care about.
16299                     */
16300                    if (pkgLite.recommendedInstallLocation
16301                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16302                        pkgLite.recommendedInstallLocation
16303                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16304                    }
16305                }
16306            }
16307
16308            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16309                int loc = pkgLite.recommendedInstallLocation;
16310                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16311                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16312                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16313                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16314                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16315                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16316                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16317                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16318                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16319                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16320                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16321                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16322                } else {
16323                    // Override with defaults if needed.
16324                    loc = installLocationPolicy(pkgLite);
16325                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16326                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16327                    } else if (!onSd && !onInt) {
16328                        // Override install location with flags
16329                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16330                            // Set the flag to install on external media.
16331                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16332                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16333                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16334                            if (DEBUG_EPHEMERAL) {
16335                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16336                            }
16337                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16338                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16339                                    |PackageManager.INSTALL_INTERNAL);
16340                        } else {
16341                            // Make sure the flag for installing on external
16342                            // media is unset
16343                            installFlags |= PackageManager.INSTALL_INTERNAL;
16344                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16345                        }
16346                    }
16347                }
16348            }
16349
16350            final InstallArgs args = createInstallArgs(this);
16351            mArgs = args;
16352
16353            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16354                // TODO: http://b/22976637
16355                // Apps installed for "all" users use the device owner to verify the app
16356                UserHandle verifierUser = getUser();
16357                if (verifierUser == UserHandle.ALL) {
16358                    verifierUser = UserHandle.SYSTEM;
16359                }
16360
16361                /*
16362                 * Determine if we have any installed package verifiers. If we
16363                 * do, then we'll defer to them to verify the packages.
16364                 */
16365                final int requiredUid = mRequiredVerifierPackage == null ? -1
16366                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16367                                verifierUser.getIdentifier());
16368                final int installerUid =
16369                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16370                if (!origin.existing && requiredUid != -1
16371                        && isVerificationEnabled(
16372                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16373                    final Intent verification = new Intent(
16374                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16375                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16376                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16377                            PACKAGE_MIME_TYPE);
16378                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16379
16380                    // Query all live verifiers based on current user state
16381                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16382                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16383                            false /*allowDynamicSplits*/);
16384
16385                    if (DEBUG_VERIFY) {
16386                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16387                                + verification.toString() + " with " + pkgLite.verifiers.length
16388                                + " optional verifiers");
16389                    }
16390
16391                    final int verificationId = mPendingVerificationToken++;
16392
16393                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16394
16395                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16396                            installerPackageName);
16397
16398                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16399                            installFlags);
16400
16401                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16402                            pkgLite.packageName);
16403
16404                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16405                            pkgLite.versionCode);
16406
16407                    if (verificationInfo != null) {
16408                        if (verificationInfo.originatingUri != null) {
16409                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16410                                    verificationInfo.originatingUri);
16411                        }
16412                        if (verificationInfo.referrer != null) {
16413                            verification.putExtra(Intent.EXTRA_REFERRER,
16414                                    verificationInfo.referrer);
16415                        }
16416                        if (verificationInfo.originatingUid >= 0) {
16417                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16418                                    verificationInfo.originatingUid);
16419                        }
16420                        if (verificationInfo.installerUid >= 0) {
16421                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16422                                    verificationInfo.installerUid);
16423                        }
16424                    }
16425
16426                    final PackageVerificationState verificationState = new PackageVerificationState(
16427                            requiredUid, args);
16428
16429                    mPendingVerification.append(verificationId, verificationState);
16430
16431                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16432                            receivers, verificationState);
16433
16434                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16435                    final long idleDuration = getVerificationTimeout();
16436
16437                    /*
16438                     * If any sufficient verifiers were listed in the package
16439                     * manifest, attempt to ask them.
16440                     */
16441                    if (sufficientVerifiers != null) {
16442                        final int N = sufficientVerifiers.size();
16443                        if (N == 0) {
16444                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16445                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16446                        } else {
16447                            for (int i = 0; i < N; i++) {
16448                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16449                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16450                                        verifierComponent.getPackageName(), idleDuration,
16451                                        verifierUser.getIdentifier(), false, "package verifier");
16452
16453                                final Intent sufficientIntent = new Intent(verification);
16454                                sufficientIntent.setComponent(verifierComponent);
16455                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16456                            }
16457                        }
16458                    }
16459
16460                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16461                            mRequiredVerifierPackage, receivers);
16462                    if (ret == PackageManager.INSTALL_SUCCEEDED
16463                            && mRequiredVerifierPackage != null) {
16464                        Trace.asyncTraceBegin(
16465                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16466                        /*
16467                         * Send the intent to the required verification agent,
16468                         * but only start the verification timeout after the
16469                         * target BroadcastReceivers have run.
16470                         */
16471                        verification.setComponent(requiredVerifierComponent);
16472                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16473                                mRequiredVerifierPackage, idleDuration,
16474                                verifierUser.getIdentifier(), false, "package verifier");
16475                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16476                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16477                                new BroadcastReceiver() {
16478                                    @Override
16479                                    public void onReceive(Context context, Intent intent) {
16480                                        final Message msg = mHandler
16481                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16482                                        msg.arg1 = verificationId;
16483                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16484                                    }
16485                                }, null, 0, null, null);
16486
16487                        /*
16488                         * We don't want the copy to proceed until verification
16489                         * succeeds, so null out this field.
16490                         */
16491                        mArgs = null;
16492                    }
16493                } else {
16494                    /*
16495                     * No package verification is enabled, so immediately start
16496                     * the remote call to initiate copy using temporary file.
16497                     */
16498                    ret = args.copyApk(mContainerService, true);
16499                }
16500            }
16501
16502            mRet = ret;
16503        }
16504
16505        @Override
16506        void handleReturnCode() {
16507            // If mArgs is null, then MCS couldn't be reached. When it
16508            // reconnects, it will try again to install. At that point, this
16509            // will succeed.
16510            if (mArgs != null) {
16511                processPendingInstall(mArgs, mRet);
16512            }
16513        }
16514
16515        @Override
16516        void handleServiceError() {
16517            mArgs = createInstallArgs(this);
16518            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16519        }
16520
16521        public boolean isForwardLocked() {
16522            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16523        }
16524    }
16525
16526    /**
16527     * Used during creation of InstallArgs
16528     *
16529     * @param installFlags package installation flags
16530     * @return true if should be installed on external storage
16531     */
16532    private static boolean installOnExternalAsec(int installFlags) {
16533        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16534            return false;
16535        }
16536        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16537            return true;
16538        }
16539        return false;
16540    }
16541
16542    /**
16543     * Used during creation of InstallArgs
16544     *
16545     * @param installFlags package installation flags
16546     * @return true if should be installed as forward locked
16547     */
16548    private static boolean installForwardLocked(int installFlags) {
16549        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16550    }
16551
16552    private InstallArgs createInstallArgs(InstallParams params) {
16553        if (params.move != null) {
16554            return new MoveInstallArgs(params);
16555        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16556            return new AsecInstallArgs(params);
16557        } else {
16558            return new FileInstallArgs(params);
16559        }
16560    }
16561
16562    /**
16563     * Create args that describe an existing installed package. Typically used
16564     * when cleaning up old installs, or used as a move source.
16565     */
16566    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16567            String resourcePath, String[] instructionSets) {
16568        final boolean isInAsec;
16569        if (installOnExternalAsec(installFlags)) {
16570            /* Apps on SD card are always in ASEC containers. */
16571            isInAsec = true;
16572        } else if (installForwardLocked(installFlags)
16573                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16574            /*
16575             * Forward-locked apps are only in ASEC containers if they're the
16576             * new style
16577             */
16578            isInAsec = true;
16579        } else {
16580            isInAsec = false;
16581        }
16582
16583        if (isInAsec) {
16584            return new AsecInstallArgs(codePath, instructionSets,
16585                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16586        } else {
16587            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16588        }
16589    }
16590
16591    static abstract class InstallArgs {
16592        /** @see InstallParams#origin */
16593        final OriginInfo origin;
16594        /** @see InstallParams#move */
16595        final MoveInfo move;
16596
16597        final IPackageInstallObserver2 observer;
16598        // Always refers to PackageManager flags only
16599        final int installFlags;
16600        final String installerPackageName;
16601        final String volumeUuid;
16602        final UserHandle user;
16603        final String abiOverride;
16604        final String[] installGrantPermissions;
16605        /** If non-null, drop an async trace when the install completes */
16606        final String traceMethod;
16607        final int traceCookie;
16608        final Certificate[][] certificates;
16609        final int installReason;
16610
16611        // The list of instruction sets supported by this app. This is currently
16612        // only used during the rmdex() phase to clean up resources. We can get rid of this
16613        // if we move dex files under the common app path.
16614        /* nullable */ String[] instructionSets;
16615
16616        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16617                int installFlags, String installerPackageName, String volumeUuid,
16618                UserHandle user, String[] instructionSets,
16619                String abiOverride, String[] installGrantPermissions,
16620                String traceMethod, int traceCookie, Certificate[][] certificates,
16621                int installReason) {
16622            this.origin = origin;
16623            this.move = move;
16624            this.installFlags = installFlags;
16625            this.observer = observer;
16626            this.installerPackageName = installerPackageName;
16627            this.volumeUuid = volumeUuid;
16628            this.user = user;
16629            this.instructionSets = instructionSets;
16630            this.abiOverride = abiOverride;
16631            this.installGrantPermissions = installGrantPermissions;
16632            this.traceMethod = traceMethod;
16633            this.traceCookie = traceCookie;
16634            this.certificates = certificates;
16635            this.installReason = installReason;
16636        }
16637
16638        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16639        abstract int doPreInstall(int status);
16640
16641        /**
16642         * Rename package into final resting place. All paths on the given
16643         * scanned package should be updated to reflect the rename.
16644         */
16645        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16646        abstract int doPostInstall(int status, int uid);
16647
16648        /** @see PackageSettingBase#codePathString */
16649        abstract String getCodePath();
16650        /** @see PackageSettingBase#resourcePathString */
16651        abstract String getResourcePath();
16652
16653        // Need installer lock especially for dex file removal.
16654        abstract void cleanUpResourcesLI();
16655        abstract boolean doPostDeleteLI(boolean delete);
16656
16657        /**
16658         * Called before the source arguments are copied. This is used mostly
16659         * for MoveParams when it needs to read the source file to put it in the
16660         * destination.
16661         */
16662        int doPreCopy() {
16663            return PackageManager.INSTALL_SUCCEEDED;
16664        }
16665
16666        /**
16667         * Called after the source arguments are copied. This is used mostly for
16668         * MoveParams when it needs to read the source file to put it in the
16669         * destination.
16670         */
16671        int doPostCopy(int uid) {
16672            return PackageManager.INSTALL_SUCCEEDED;
16673        }
16674
16675        protected boolean isFwdLocked() {
16676            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16677        }
16678
16679        protected boolean isExternalAsec() {
16680            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16681        }
16682
16683        protected boolean isEphemeral() {
16684            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16685        }
16686
16687        UserHandle getUser() {
16688            return user;
16689        }
16690    }
16691
16692    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16693        if (!allCodePaths.isEmpty()) {
16694            if (instructionSets == null) {
16695                throw new IllegalStateException("instructionSet == null");
16696            }
16697            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16698            for (String codePath : allCodePaths) {
16699                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16700                    try {
16701                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16702                    } catch (InstallerException ignored) {
16703                    }
16704                }
16705            }
16706        }
16707    }
16708
16709    /**
16710     * Logic to handle installation of non-ASEC applications, including copying
16711     * and renaming logic.
16712     */
16713    class FileInstallArgs extends InstallArgs {
16714        private File codeFile;
16715        private File resourceFile;
16716
16717        // Example topology:
16718        // /data/app/com.example/base.apk
16719        // /data/app/com.example/split_foo.apk
16720        // /data/app/com.example/lib/arm/libfoo.so
16721        // /data/app/com.example/lib/arm64/libfoo.so
16722        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16723
16724        /** New install */
16725        FileInstallArgs(InstallParams params) {
16726            super(params.origin, params.move, params.observer, params.installFlags,
16727                    params.installerPackageName, params.volumeUuid,
16728                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16729                    params.grantedRuntimePermissions,
16730                    params.traceMethod, params.traceCookie, params.certificates,
16731                    params.installReason);
16732            if (isFwdLocked()) {
16733                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16734            }
16735        }
16736
16737        /** Existing install */
16738        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16739            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16740                    null, null, null, 0, null /*certificates*/,
16741                    PackageManager.INSTALL_REASON_UNKNOWN);
16742            this.codeFile = (codePath != null) ? new File(codePath) : null;
16743            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16744        }
16745
16746        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16747            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16748            try {
16749                return doCopyApk(imcs, temp);
16750            } finally {
16751                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16752            }
16753        }
16754
16755        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16756            if (origin.staged) {
16757                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16758                codeFile = origin.file;
16759                resourceFile = origin.file;
16760                return PackageManager.INSTALL_SUCCEEDED;
16761            }
16762
16763            try {
16764                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16765                final File tempDir =
16766                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16767                codeFile = tempDir;
16768                resourceFile = tempDir;
16769            } catch (IOException e) {
16770                Slog.w(TAG, "Failed to create copy file: " + e);
16771                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16772            }
16773
16774            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16775                @Override
16776                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16777                    if (!FileUtils.isValidExtFilename(name)) {
16778                        throw new IllegalArgumentException("Invalid filename: " + name);
16779                    }
16780                    try {
16781                        final File file = new File(codeFile, name);
16782                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16783                                O_RDWR | O_CREAT, 0644);
16784                        Os.chmod(file.getAbsolutePath(), 0644);
16785                        return new ParcelFileDescriptor(fd);
16786                    } catch (ErrnoException e) {
16787                        throw new RemoteException("Failed to open: " + e.getMessage());
16788                    }
16789                }
16790            };
16791
16792            int ret = PackageManager.INSTALL_SUCCEEDED;
16793            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16794            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16795                Slog.e(TAG, "Failed to copy package");
16796                return ret;
16797            }
16798
16799            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16800            NativeLibraryHelper.Handle handle = null;
16801            try {
16802                handle = NativeLibraryHelper.Handle.create(codeFile);
16803                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16804                        abiOverride);
16805            } catch (IOException e) {
16806                Slog.e(TAG, "Copying native libraries failed", e);
16807                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16808            } finally {
16809                IoUtils.closeQuietly(handle);
16810            }
16811
16812            return ret;
16813        }
16814
16815        int doPreInstall(int status) {
16816            if (status != PackageManager.INSTALL_SUCCEEDED) {
16817                cleanUp();
16818            }
16819            return status;
16820        }
16821
16822        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16823            if (status != PackageManager.INSTALL_SUCCEEDED) {
16824                cleanUp();
16825                return false;
16826            }
16827
16828            final File targetDir = codeFile.getParentFile();
16829            final File beforeCodeFile = codeFile;
16830            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16831
16832            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16833            try {
16834                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16835            } catch (ErrnoException e) {
16836                Slog.w(TAG, "Failed to rename", e);
16837                return false;
16838            }
16839
16840            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16841                Slog.w(TAG, "Failed to restorecon");
16842                return false;
16843            }
16844
16845            // Reflect the rename internally
16846            codeFile = afterCodeFile;
16847            resourceFile = afterCodeFile;
16848
16849            // Reflect the rename in scanned details
16850            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16851            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16852                    afterCodeFile, pkg.baseCodePath));
16853            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16854                    afterCodeFile, pkg.splitCodePaths));
16855
16856            // Reflect the rename in app info
16857            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16858            pkg.setApplicationInfoCodePath(pkg.codePath);
16859            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16860            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16861            pkg.setApplicationInfoResourcePath(pkg.codePath);
16862            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16863            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16864
16865            return true;
16866        }
16867
16868        int doPostInstall(int status, int uid) {
16869            if (status != PackageManager.INSTALL_SUCCEEDED) {
16870                cleanUp();
16871            }
16872            return status;
16873        }
16874
16875        @Override
16876        String getCodePath() {
16877            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16878        }
16879
16880        @Override
16881        String getResourcePath() {
16882            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16883        }
16884
16885        private boolean cleanUp() {
16886            if (codeFile == null || !codeFile.exists()) {
16887                return false;
16888            }
16889
16890            removeCodePathLI(codeFile);
16891
16892            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16893                resourceFile.delete();
16894            }
16895
16896            return true;
16897        }
16898
16899        void cleanUpResourcesLI() {
16900            // Try enumerating all code paths before deleting
16901            List<String> allCodePaths = Collections.EMPTY_LIST;
16902            if (codeFile != null && codeFile.exists()) {
16903                try {
16904                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16905                    allCodePaths = pkg.getAllCodePaths();
16906                } catch (PackageParserException e) {
16907                    // Ignored; we tried our best
16908                }
16909            }
16910
16911            cleanUp();
16912            removeDexFiles(allCodePaths, instructionSets);
16913        }
16914
16915        boolean doPostDeleteLI(boolean delete) {
16916            // XXX err, shouldn't we respect the delete flag?
16917            cleanUpResourcesLI();
16918            return true;
16919        }
16920    }
16921
16922    private boolean isAsecExternal(String cid) {
16923        final String asecPath = PackageHelper.getSdFilesystem(cid);
16924        return !asecPath.startsWith(mAsecInternalPath);
16925    }
16926
16927    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16928            PackageManagerException {
16929        if (copyRet < 0) {
16930            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16931                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16932                throw new PackageManagerException(copyRet, message);
16933            }
16934        }
16935    }
16936
16937    /**
16938     * Extract the StorageManagerService "container ID" from the full code path of an
16939     * .apk.
16940     */
16941    static String cidFromCodePath(String fullCodePath) {
16942        int eidx = fullCodePath.lastIndexOf("/");
16943        String subStr1 = fullCodePath.substring(0, eidx);
16944        int sidx = subStr1.lastIndexOf("/");
16945        return subStr1.substring(sidx+1, eidx);
16946    }
16947
16948    /**
16949     * Logic to handle installation of ASEC applications, including copying and
16950     * renaming logic.
16951     */
16952    class AsecInstallArgs extends InstallArgs {
16953        static final String RES_FILE_NAME = "pkg.apk";
16954        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16955
16956        String cid;
16957        String packagePath;
16958        String resourcePath;
16959
16960        /** New install */
16961        AsecInstallArgs(InstallParams params) {
16962            super(params.origin, params.move, params.observer, params.installFlags,
16963                    params.installerPackageName, params.volumeUuid,
16964                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16965                    params.grantedRuntimePermissions,
16966                    params.traceMethod, params.traceCookie, params.certificates,
16967                    params.installReason);
16968        }
16969
16970        /** Existing install */
16971        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16972                        boolean isExternal, boolean isForwardLocked) {
16973            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16974                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16975                    instructionSets, null, null, null, 0, null /*certificates*/,
16976                    PackageManager.INSTALL_REASON_UNKNOWN);
16977            // Hackily pretend we're still looking at a full code path
16978            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16979                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16980            }
16981
16982            // Extract cid from fullCodePath
16983            int eidx = fullCodePath.lastIndexOf("/");
16984            String subStr1 = fullCodePath.substring(0, eidx);
16985            int sidx = subStr1.lastIndexOf("/");
16986            cid = subStr1.substring(sidx+1, eidx);
16987            setMountPath(subStr1);
16988        }
16989
16990        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16991            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16992                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16993                    instructionSets, null, null, null, 0, null /*certificates*/,
16994                    PackageManager.INSTALL_REASON_UNKNOWN);
16995            this.cid = cid;
16996            setMountPath(PackageHelper.getSdDir(cid));
16997        }
16998
16999        void createCopyFile() {
17000            cid = mInstallerService.allocateExternalStageCidLegacy();
17001        }
17002
17003        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
17004            if (origin.staged && origin.cid != null) {
17005                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
17006                cid = origin.cid;
17007                setMountPath(PackageHelper.getSdDir(cid));
17008                return PackageManager.INSTALL_SUCCEEDED;
17009            }
17010
17011            if (temp) {
17012                createCopyFile();
17013            } else {
17014                /*
17015                 * Pre-emptively destroy the container since it's destroyed if
17016                 * copying fails due to it existing anyway.
17017                 */
17018                PackageHelper.destroySdDir(cid);
17019            }
17020
17021            final String newMountPath = imcs.copyPackageToContainer(
17022                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
17023                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
17024
17025            if (newMountPath != null) {
17026                setMountPath(newMountPath);
17027                return PackageManager.INSTALL_SUCCEEDED;
17028            } else {
17029                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17030            }
17031        }
17032
17033        @Override
17034        String getCodePath() {
17035            return packagePath;
17036        }
17037
17038        @Override
17039        String getResourcePath() {
17040            return resourcePath;
17041        }
17042
17043        int doPreInstall(int status) {
17044            if (status != PackageManager.INSTALL_SUCCEEDED) {
17045                // Destroy container
17046                PackageHelper.destroySdDir(cid);
17047            } else {
17048                boolean mounted = PackageHelper.isContainerMounted(cid);
17049                if (!mounted) {
17050                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
17051                            Process.SYSTEM_UID);
17052                    if (newMountPath != null) {
17053                        setMountPath(newMountPath);
17054                    } else {
17055                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17056                    }
17057                }
17058            }
17059            return status;
17060        }
17061
17062        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17063            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
17064            String newMountPath = null;
17065            if (PackageHelper.isContainerMounted(cid)) {
17066                // Unmount the container
17067                if (!PackageHelper.unMountSdDir(cid)) {
17068                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
17069                    return false;
17070                }
17071            }
17072            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17073                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
17074                        " which might be stale. Will try to clean up.");
17075                // Clean up the stale container and proceed to recreate.
17076                if (!PackageHelper.destroySdDir(newCacheId)) {
17077                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
17078                    return false;
17079                }
17080                // Successfully cleaned up stale container. Try to rename again.
17081                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
17082                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
17083                            + " inspite of cleaning it up.");
17084                    return false;
17085                }
17086            }
17087            if (!PackageHelper.isContainerMounted(newCacheId)) {
17088                Slog.w(TAG, "Mounting container " + newCacheId);
17089                newMountPath = PackageHelper.mountSdDir(newCacheId,
17090                        getEncryptKey(), Process.SYSTEM_UID);
17091            } else {
17092                newMountPath = PackageHelper.getSdDir(newCacheId);
17093            }
17094            if (newMountPath == null) {
17095                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
17096                return false;
17097            }
17098            Log.i(TAG, "Succesfully renamed " + cid +
17099                    " to " + newCacheId +
17100                    " at new path: " + newMountPath);
17101            cid = newCacheId;
17102
17103            final File beforeCodeFile = new File(packagePath);
17104            setMountPath(newMountPath);
17105            final File afterCodeFile = new File(packagePath);
17106
17107            // Reflect the rename in scanned details
17108            pkg.setCodePath(afterCodeFile.getAbsolutePath());
17109            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
17110                    afterCodeFile, pkg.baseCodePath));
17111            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17112                    afterCodeFile, pkg.splitCodePaths));
17113
17114            // Reflect the rename in app info
17115            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17116            pkg.setApplicationInfoCodePath(pkg.codePath);
17117            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17118            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17119            pkg.setApplicationInfoResourcePath(pkg.codePath);
17120            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17121            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17122
17123            return true;
17124        }
17125
17126        private void setMountPath(String mountPath) {
17127            final File mountFile = new File(mountPath);
17128
17129            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17130            if (monolithicFile.exists()) {
17131                packagePath = monolithicFile.getAbsolutePath();
17132                if (isFwdLocked()) {
17133                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17134                } else {
17135                    resourcePath = packagePath;
17136                }
17137            } else {
17138                packagePath = mountFile.getAbsolutePath();
17139                resourcePath = packagePath;
17140            }
17141        }
17142
17143        int doPostInstall(int status, int uid) {
17144            if (status != PackageManager.INSTALL_SUCCEEDED) {
17145                cleanUp();
17146            } else {
17147                final int groupOwner;
17148                final String protectedFile;
17149                if (isFwdLocked()) {
17150                    groupOwner = UserHandle.getSharedAppGid(uid);
17151                    protectedFile = RES_FILE_NAME;
17152                } else {
17153                    groupOwner = -1;
17154                    protectedFile = null;
17155                }
17156
17157                if (uid < Process.FIRST_APPLICATION_UID
17158                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17159                    Slog.e(TAG, "Failed to finalize " + cid);
17160                    PackageHelper.destroySdDir(cid);
17161                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17162                }
17163
17164                boolean mounted = PackageHelper.isContainerMounted(cid);
17165                if (!mounted) {
17166                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17167                }
17168            }
17169            return status;
17170        }
17171
17172        private void cleanUp() {
17173            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17174
17175            // Destroy secure container
17176            PackageHelper.destroySdDir(cid);
17177        }
17178
17179        private List<String> getAllCodePaths() {
17180            final File codeFile = new File(getCodePath());
17181            if (codeFile != null && codeFile.exists()) {
17182                try {
17183                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17184                    return pkg.getAllCodePaths();
17185                } catch (PackageParserException e) {
17186                    // Ignored; we tried our best
17187                }
17188            }
17189            return Collections.EMPTY_LIST;
17190        }
17191
17192        void cleanUpResourcesLI() {
17193            // Enumerate all code paths before deleting
17194            cleanUpResourcesLI(getAllCodePaths());
17195        }
17196
17197        private void cleanUpResourcesLI(List<String> allCodePaths) {
17198            cleanUp();
17199            removeDexFiles(allCodePaths, instructionSets);
17200        }
17201
17202        String getPackageName() {
17203            return getAsecPackageName(cid);
17204        }
17205
17206        boolean doPostDeleteLI(boolean delete) {
17207            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17208            final List<String> allCodePaths = getAllCodePaths();
17209            boolean mounted = PackageHelper.isContainerMounted(cid);
17210            if (mounted) {
17211                // Unmount first
17212                if (PackageHelper.unMountSdDir(cid)) {
17213                    mounted = false;
17214                }
17215            }
17216            if (!mounted && delete) {
17217                cleanUpResourcesLI(allCodePaths);
17218            }
17219            return !mounted;
17220        }
17221
17222        @Override
17223        int doPreCopy() {
17224            if (isFwdLocked()) {
17225                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17226                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17227                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17228                }
17229            }
17230
17231            return PackageManager.INSTALL_SUCCEEDED;
17232        }
17233
17234        @Override
17235        int doPostCopy(int uid) {
17236            if (isFwdLocked()) {
17237                if (uid < Process.FIRST_APPLICATION_UID
17238                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17239                                RES_FILE_NAME)) {
17240                    Slog.e(TAG, "Failed to finalize " + cid);
17241                    PackageHelper.destroySdDir(cid);
17242                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17243                }
17244            }
17245
17246            return PackageManager.INSTALL_SUCCEEDED;
17247        }
17248    }
17249
17250    /**
17251     * Logic to handle movement of existing installed applications.
17252     */
17253    class MoveInstallArgs extends InstallArgs {
17254        private File codeFile;
17255        private File resourceFile;
17256
17257        /** New install */
17258        MoveInstallArgs(InstallParams params) {
17259            super(params.origin, params.move, params.observer, params.installFlags,
17260                    params.installerPackageName, params.volumeUuid,
17261                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17262                    params.grantedRuntimePermissions,
17263                    params.traceMethod, params.traceCookie, params.certificates,
17264                    params.installReason);
17265        }
17266
17267        int copyApk(IMediaContainerService imcs, boolean temp) {
17268            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17269                    + move.fromUuid + " to " + move.toUuid);
17270            synchronized (mInstaller) {
17271                try {
17272                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17273                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17274                } catch (InstallerException e) {
17275                    Slog.w(TAG, "Failed to move app", e);
17276                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17277                }
17278            }
17279
17280            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17281            resourceFile = codeFile;
17282            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17283
17284            return PackageManager.INSTALL_SUCCEEDED;
17285        }
17286
17287        int doPreInstall(int status) {
17288            if (status != PackageManager.INSTALL_SUCCEEDED) {
17289                cleanUp(move.toUuid);
17290            }
17291            return status;
17292        }
17293
17294        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17295            if (status != PackageManager.INSTALL_SUCCEEDED) {
17296                cleanUp(move.toUuid);
17297                return false;
17298            }
17299
17300            // Reflect the move in app info
17301            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17302            pkg.setApplicationInfoCodePath(pkg.codePath);
17303            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17304            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17305            pkg.setApplicationInfoResourcePath(pkg.codePath);
17306            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17307            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17308
17309            return true;
17310        }
17311
17312        int doPostInstall(int status, int uid) {
17313            if (status == PackageManager.INSTALL_SUCCEEDED) {
17314                cleanUp(move.fromUuid);
17315            } else {
17316                cleanUp(move.toUuid);
17317            }
17318            return status;
17319        }
17320
17321        @Override
17322        String getCodePath() {
17323            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17324        }
17325
17326        @Override
17327        String getResourcePath() {
17328            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17329        }
17330
17331        private boolean cleanUp(String volumeUuid) {
17332            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17333                    move.dataAppName);
17334            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17335            final int[] userIds = sUserManager.getUserIds();
17336            synchronized (mInstallLock) {
17337                // Clean up both app data and code
17338                // All package moves are frozen until finished
17339                for (int userId : userIds) {
17340                    try {
17341                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17342                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17343                    } catch (InstallerException e) {
17344                        Slog.w(TAG, String.valueOf(e));
17345                    }
17346                }
17347                removeCodePathLI(codeFile);
17348            }
17349            return true;
17350        }
17351
17352        void cleanUpResourcesLI() {
17353            throw new UnsupportedOperationException();
17354        }
17355
17356        boolean doPostDeleteLI(boolean delete) {
17357            throw new UnsupportedOperationException();
17358        }
17359    }
17360
17361    static String getAsecPackageName(String packageCid) {
17362        int idx = packageCid.lastIndexOf("-");
17363        if (idx == -1) {
17364            return packageCid;
17365        }
17366        return packageCid.substring(0, idx);
17367    }
17368
17369    // Utility method used to create code paths based on package name and available index.
17370    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17371        String idxStr = "";
17372        int idx = 1;
17373        // Fall back to default value of idx=1 if prefix is not
17374        // part of oldCodePath
17375        if (oldCodePath != null) {
17376            String subStr = oldCodePath;
17377            // Drop the suffix right away
17378            if (suffix != null && subStr.endsWith(suffix)) {
17379                subStr = subStr.substring(0, subStr.length() - suffix.length());
17380            }
17381            // If oldCodePath already contains prefix find out the
17382            // ending index to either increment or decrement.
17383            int sidx = subStr.lastIndexOf(prefix);
17384            if (sidx != -1) {
17385                subStr = subStr.substring(sidx + prefix.length());
17386                if (subStr != null) {
17387                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17388                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17389                    }
17390                    try {
17391                        idx = Integer.parseInt(subStr);
17392                        if (idx <= 1) {
17393                            idx++;
17394                        } else {
17395                            idx--;
17396                        }
17397                    } catch(NumberFormatException e) {
17398                    }
17399                }
17400            }
17401        }
17402        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17403        return prefix + idxStr;
17404    }
17405
17406    private File getNextCodePath(File targetDir, String packageName) {
17407        File result;
17408        SecureRandom random = new SecureRandom();
17409        byte[] bytes = new byte[16];
17410        do {
17411            random.nextBytes(bytes);
17412            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17413            result = new File(targetDir, packageName + "-" + suffix);
17414        } while (result.exists());
17415        return result;
17416    }
17417
17418    // Utility method that returns the relative package path with respect
17419    // to the installation directory. Like say for /data/data/com.test-1.apk
17420    // string com.test-1 is returned.
17421    static String deriveCodePathName(String codePath) {
17422        if (codePath == null) {
17423            return null;
17424        }
17425        final File codeFile = new File(codePath);
17426        final String name = codeFile.getName();
17427        if (codeFile.isDirectory()) {
17428            return name;
17429        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17430            final int lastDot = name.lastIndexOf('.');
17431            return name.substring(0, lastDot);
17432        } else {
17433            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17434            return null;
17435        }
17436    }
17437
17438    static class PackageInstalledInfo {
17439        String name;
17440        int uid;
17441        // The set of users that originally had this package installed.
17442        int[] origUsers;
17443        // The set of users that now have this package installed.
17444        int[] newUsers;
17445        PackageParser.Package pkg;
17446        int returnCode;
17447        String returnMsg;
17448        String installerPackageName;
17449        PackageRemovedInfo removedInfo;
17450        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17451
17452        public void setError(int code, String msg) {
17453            setReturnCode(code);
17454            setReturnMessage(msg);
17455            Slog.w(TAG, msg);
17456        }
17457
17458        public void setError(String msg, PackageParserException e) {
17459            setReturnCode(e.error);
17460            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17461            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17462            for (int i = 0; i < childCount; i++) {
17463                addedChildPackages.valueAt(i).setError(msg, e);
17464            }
17465            Slog.w(TAG, msg, e);
17466        }
17467
17468        public void setError(String msg, PackageManagerException e) {
17469            returnCode = e.error;
17470            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17471            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17472            for (int i = 0; i < childCount; i++) {
17473                addedChildPackages.valueAt(i).setError(msg, e);
17474            }
17475            Slog.w(TAG, msg, e);
17476        }
17477
17478        public void setReturnCode(int returnCode) {
17479            this.returnCode = returnCode;
17480            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17481            for (int i = 0; i < childCount; i++) {
17482                addedChildPackages.valueAt(i).returnCode = returnCode;
17483            }
17484        }
17485
17486        private void setReturnMessage(String returnMsg) {
17487            this.returnMsg = returnMsg;
17488            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17489            for (int i = 0; i < childCount; i++) {
17490                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17491            }
17492        }
17493
17494        // In some error cases we want to convey more info back to the observer
17495        String origPackage;
17496        String origPermission;
17497    }
17498
17499    /*
17500     * Install a non-existing package.
17501     */
17502    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17503            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17504            PackageInstalledInfo res, int installReason) {
17505        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17506
17507        // Remember this for later, in case we need to rollback this install
17508        String pkgName = pkg.packageName;
17509
17510        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17511
17512        synchronized(mPackages) {
17513            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17514            if (renamedPackage != null) {
17515                // A package with the same name is already installed, though
17516                // it has been renamed to an older name.  The package we
17517                // are trying to install should be installed as an update to
17518                // the existing one, but that has not been requested, so bail.
17519                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17520                        + " without first uninstalling package running as "
17521                        + renamedPackage);
17522                return;
17523            }
17524            if (mPackages.containsKey(pkgName)) {
17525                // Don't allow installation over an existing package with the same name.
17526                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17527                        + " without first uninstalling.");
17528                return;
17529            }
17530        }
17531
17532        try {
17533            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17534                    System.currentTimeMillis(), user);
17535
17536            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17537
17538            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17539                prepareAppDataAfterInstallLIF(newPackage);
17540
17541            } else {
17542                // Remove package from internal structures, but keep around any
17543                // data that might have already existed
17544                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17545                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17546            }
17547        } catch (PackageManagerException e) {
17548            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17549        }
17550
17551        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17552    }
17553
17554    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17555        // Can't rotate keys during boot or if sharedUser.
17556        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17557                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17558            return false;
17559        }
17560        // app is using upgradeKeySets; make sure all are valid
17561        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17562        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17563        for (int i = 0; i < upgradeKeySets.length; i++) {
17564            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17565                Slog.wtf(TAG, "Package "
17566                         + (oldPs.name != null ? oldPs.name : "<null>")
17567                         + " contains upgrade-key-set reference to unknown key-set: "
17568                         + upgradeKeySets[i]
17569                         + " reverting to signatures check.");
17570                return false;
17571            }
17572        }
17573        return true;
17574    }
17575
17576    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17577        // Upgrade keysets are being used.  Determine if new package has a superset of the
17578        // required keys.
17579        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17580        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17581        for (int i = 0; i < upgradeKeySets.length; i++) {
17582            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17583            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17584                return true;
17585            }
17586        }
17587        return false;
17588    }
17589
17590    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17591        try (DigestInputStream digestStream =
17592                new DigestInputStream(new FileInputStream(file), digest)) {
17593            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17594        }
17595    }
17596
17597    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17598            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17599            int installReason) {
17600        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17601
17602        final PackageParser.Package oldPackage;
17603        final PackageSetting ps;
17604        final String pkgName = pkg.packageName;
17605        final int[] allUsers;
17606        final int[] installedUsers;
17607
17608        synchronized(mPackages) {
17609            oldPackage = mPackages.get(pkgName);
17610            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17611
17612            // don't allow upgrade to target a release SDK from a pre-release SDK
17613            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17614                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17615            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17616                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17617            if (oldTargetsPreRelease
17618                    && !newTargetsPreRelease
17619                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17620                Slog.w(TAG, "Can't install package targeting released sdk");
17621                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17622                return;
17623            }
17624
17625            ps = mSettings.mPackages.get(pkgName);
17626
17627            // verify signatures are valid
17628            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17629                if (!checkUpgradeKeySetLP(ps, pkg)) {
17630                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17631                            "New package not signed by keys specified by upgrade-keysets: "
17632                                    + pkgName);
17633                    return;
17634                }
17635            } else {
17636                // default to original signature matching
17637                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17638                        != PackageManager.SIGNATURE_MATCH) {
17639                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17640                            "New package has a different signature: " + pkgName);
17641                    return;
17642                }
17643            }
17644
17645            // don't allow a system upgrade unless the upgrade hash matches
17646            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17647                byte[] digestBytes = null;
17648                try {
17649                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17650                    updateDigest(digest, new File(pkg.baseCodePath));
17651                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17652                        for (String path : pkg.splitCodePaths) {
17653                            updateDigest(digest, new File(path));
17654                        }
17655                    }
17656                    digestBytes = digest.digest();
17657                } catch (NoSuchAlgorithmException | IOException e) {
17658                    res.setError(INSTALL_FAILED_INVALID_APK,
17659                            "Could not compute hash: " + pkgName);
17660                    return;
17661                }
17662                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17663                    res.setError(INSTALL_FAILED_INVALID_APK,
17664                            "New package fails restrict-update check: " + pkgName);
17665                    return;
17666                }
17667                // retain upgrade restriction
17668                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17669            }
17670
17671            // Check for shared user id changes
17672            String invalidPackageName =
17673                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17674            if (invalidPackageName != null) {
17675                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17676                        "Package " + invalidPackageName + " tried to change user "
17677                                + oldPackage.mSharedUserId);
17678                return;
17679            }
17680
17681            // In case of rollback, remember per-user/profile install state
17682            allUsers = sUserManager.getUserIds();
17683            installedUsers = ps.queryInstalledUsers(allUsers, true);
17684
17685            // don't allow an upgrade from full to ephemeral
17686            if (isInstantApp) {
17687                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17688                    for (int currentUser : allUsers) {
17689                        if (!ps.getInstantApp(currentUser)) {
17690                            // can't downgrade from full to instant
17691                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17692                                    + " for user: " + currentUser);
17693                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17694                            return;
17695                        }
17696                    }
17697                } else if (!ps.getInstantApp(user.getIdentifier())) {
17698                    // can't downgrade from full to instant
17699                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17700                            + " for user: " + user.getIdentifier());
17701                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17702                    return;
17703                }
17704            }
17705        }
17706
17707        // Update what is removed
17708        res.removedInfo = new PackageRemovedInfo(this);
17709        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17710        res.removedInfo.removedPackage = oldPackage.packageName;
17711        res.removedInfo.installerPackageName = ps.installerPackageName;
17712        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17713        res.removedInfo.isUpdate = true;
17714        res.removedInfo.origUsers = installedUsers;
17715        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17716        for (int i = 0; i < installedUsers.length; i++) {
17717            final int userId = installedUsers[i];
17718            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17719        }
17720
17721        final int childCount = (oldPackage.childPackages != null)
17722                ? oldPackage.childPackages.size() : 0;
17723        for (int i = 0; i < childCount; i++) {
17724            boolean childPackageUpdated = false;
17725            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17726            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17727            if (res.addedChildPackages != null) {
17728                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17729                if (childRes != null) {
17730                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17731                    childRes.removedInfo.removedPackage = childPkg.packageName;
17732                    if (childPs != null) {
17733                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17734                    }
17735                    childRes.removedInfo.isUpdate = true;
17736                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17737                    childPackageUpdated = true;
17738                }
17739            }
17740            if (!childPackageUpdated) {
17741                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17742                childRemovedRes.removedPackage = childPkg.packageName;
17743                if (childPs != null) {
17744                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17745                }
17746                childRemovedRes.isUpdate = false;
17747                childRemovedRes.dataRemoved = true;
17748                synchronized (mPackages) {
17749                    if (childPs != null) {
17750                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17751                    }
17752                }
17753                if (res.removedInfo.removedChildPackages == null) {
17754                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17755                }
17756                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17757            }
17758        }
17759
17760        boolean sysPkg = (isSystemApp(oldPackage));
17761        if (sysPkg) {
17762            // Set the system/privileged flags as needed
17763            final boolean privileged =
17764                    (oldPackage.applicationInfo.privateFlags
17765                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17766            final int systemPolicyFlags = policyFlags
17767                    | PackageParser.PARSE_IS_SYSTEM
17768                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17769
17770            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17771                    user, allUsers, installerPackageName, res, installReason);
17772        } else {
17773            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17774                    user, allUsers, installerPackageName, res, installReason);
17775        }
17776    }
17777
17778    @Override
17779    public List<String> getPreviousCodePaths(String packageName) {
17780        final int callingUid = Binder.getCallingUid();
17781        final List<String> result = new ArrayList<>();
17782        if (getInstantAppPackageName(callingUid) != null) {
17783            return result;
17784        }
17785        final PackageSetting ps = mSettings.mPackages.get(packageName);
17786        if (ps != null
17787                && ps.oldCodePaths != null
17788                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17789            result.addAll(ps.oldCodePaths);
17790        }
17791        return result;
17792    }
17793
17794    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17795            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17796            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17797            int installReason) {
17798        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17799                + deletedPackage);
17800
17801        String pkgName = deletedPackage.packageName;
17802        boolean deletedPkg = true;
17803        boolean addedPkg = false;
17804        boolean updatedSettings = false;
17805        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17806        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17807                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17808
17809        final long origUpdateTime = (pkg.mExtras != null)
17810                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17811
17812        // First delete the existing package while retaining the data directory
17813        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17814                res.removedInfo, true, pkg)) {
17815            // If the existing package wasn't successfully deleted
17816            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17817            deletedPkg = false;
17818        } else {
17819            // Successfully deleted the old package; proceed with replace.
17820
17821            // If deleted package lived in a container, give users a chance to
17822            // relinquish resources before killing.
17823            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17824                if (DEBUG_INSTALL) {
17825                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17826                }
17827                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17828                final ArrayList<String> pkgList = new ArrayList<String>(1);
17829                pkgList.add(deletedPackage.applicationInfo.packageName);
17830                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17831            }
17832
17833            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17834                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17835            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17836
17837            try {
17838                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17839                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17840                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17841                        installReason);
17842
17843                // Update the in-memory copy of the previous code paths.
17844                PackageSetting ps = mSettings.mPackages.get(pkgName);
17845                if (!killApp) {
17846                    if (ps.oldCodePaths == null) {
17847                        ps.oldCodePaths = new ArraySet<>();
17848                    }
17849                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17850                    if (deletedPackage.splitCodePaths != null) {
17851                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17852                    }
17853                } else {
17854                    ps.oldCodePaths = null;
17855                }
17856                if (ps.childPackageNames != null) {
17857                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17858                        final String childPkgName = ps.childPackageNames.get(i);
17859                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17860                        childPs.oldCodePaths = ps.oldCodePaths;
17861                    }
17862                }
17863                // set instant app status, but, only if it's explicitly specified
17864                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17865                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17866                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17867                prepareAppDataAfterInstallLIF(newPackage);
17868                addedPkg = true;
17869                mDexManager.notifyPackageUpdated(newPackage.packageName,
17870                        newPackage.baseCodePath, newPackage.splitCodePaths);
17871            } catch (PackageManagerException e) {
17872                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17873            }
17874        }
17875
17876        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17877            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17878
17879            // Revert all internal state mutations and added folders for the failed install
17880            if (addedPkg) {
17881                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17882                        res.removedInfo, true, null);
17883            }
17884
17885            // Restore the old package
17886            if (deletedPkg) {
17887                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17888                File restoreFile = new File(deletedPackage.codePath);
17889                // Parse old package
17890                boolean oldExternal = isExternal(deletedPackage);
17891                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17892                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17893                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17894                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17895                try {
17896                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17897                            null);
17898                } catch (PackageManagerException e) {
17899                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17900                            + e.getMessage());
17901                    return;
17902                }
17903
17904                synchronized (mPackages) {
17905                    // Ensure the installer package name up to date
17906                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17907
17908                    // Update permissions for restored package
17909                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17910
17911                    mSettings.writeLPr();
17912                }
17913
17914                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17915            }
17916        } else {
17917            synchronized (mPackages) {
17918                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17919                if (ps != null) {
17920                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17921                    if (res.removedInfo.removedChildPackages != null) {
17922                        final int childCount = res.removedInfo.removedChildPackages.size();
17923                        // Iterate in reverse as we may modify the collection
17924                        for (int i = childCount - 1; i >= 0; i--) {
17925                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17926                            if (res.addedChildPackages.containsKey(childPackageName)) {
17927                                res.removedInfo.removedChildPackages.removeAt(i);
17928                            } else {
17929                                PackageRemovedInfo childInfo = res.removedInfo
17930                                        .removedChildPackages.valueAt(i);
17931                                childInfo.removedForAllUsers = mPackages.get(
17932                                        childInfo.removedPackage) == null;
17933                            }
17934                        }
17935                    }
17936                }
17937            }
17938        }
17939    }
17940
17941    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17942            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17943            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17944            int installReason) {
17945        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17946                + ", old=" + deletedPackage);
17947
17948        final boolean disabledSystem;
17949
17950        // Remove existing system package
17951        removePackageLI(deletedPackage, true);
17952
17953        synchronized (mPackages) {
17954            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17955        }
17956        if (!disabledSystem) {
17957            // We didn't need to disable the .apk as a current system package,
17958            // which means we are replacing another update that is already
17959            // installed.  We need to make sure to delete the older one's .apk.
17960            res.removedInfo.args = createInstallArgsForExisting(0,
17961                    deletedPackage.applicationInfo.getCodePath(),
17962                    deletedPackage.applicationInfo.getResourcePath(),
17963                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17964        } else {
17965            res.removedInfo.args = null;
17966        }
17967
17968        // Successfully disabled the old package. Now proceed with re-installation
17969        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17970                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17971        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17972
17973        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17974        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17975                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17976
17977        PackageParser.Package newPackage = null;
17978        try {
17979            // Add the package to the internal data structures
17980            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17981
17982            // Set the update and install times
17983            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17984            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17985                    System.currentTimeMillis());
17986
17987            // Update the package dynamic state if succeeded
17988            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17989                // Now that the install succeeded make sure we remove data
17990                // directories for any child package the update removed.
17991                final int deletedChildCount = (deletedPackage.childPackages != null)
17992                        ? deletedPackage.childPackages.size() : 0;
17993                final int newChildCount = (newPackage.childPackages != null)
17994                        ? newPackage.childPackages.size() : 0;
17995                for (int i = 0; i < deletedChildCount; i++) {
17996                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17997                    boolean childPackageDeleted = true;
17998                    for (int j = 0; j < newChildCount; j++) {
17999                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
18000                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
18001                            childPackageDeleted = false;
18002                            break;
18003                        }
18004                    }
18005                    if (childPackageDeleted) {
18006                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
18007                                deletedChildPkg.packageName);
18008                        if (ps != null && res.removedInfo.removedChildPackages != null) {
18009                            PackageRemovedInfo removedChildRes = res.removedInfo
18010                                    .removedChildPackages.get(deletedChildPkg.packageName);
18011                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
18012                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
18013                        }
18014                    }
18015                }
18016
18017                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
18018                        installReason);
18019                prepareAppDataAfterInstallLIF(newPackage);
18020
18021                mDexManager.notifyPackageUpdated(newPackage.packageName,
18022                            newPackage.baseCodePath, newPackage.splitCodePaths);
18023            }
18024        } catch (PackageManagerException e) {
18025            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
18026            res.setError("Package couldn't be installed in " + pkg.codePath, e);
18027        }
18028
18029        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
18030            // Re installation failed. Restore old information
18031            // Remove new pkg information
18032            if (newPackage != null) {
18033                removeInstalledPackageLI(newPackage, true);
18034            }
18035            // Add back the old system package
18036            try {
18037                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
18038            } catch (PackageManagerException e) {
18039                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
18040            }
18041
18042            synchronized (mPackages) {
18043                if (disabledSystem) {
18044                    enableSystemPackageLPw(deletedPackage);
18045                }
18046
18047                // Ensure the installer package name up to date
18048                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
18049
18050                // Update permissions for restored package
18051                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
18052
18053                mSettings.writeLPr();
18054            }
18055
18056            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
18057                    + " after failed upgrade");
18058        }
18059    }
18060
18061    /**
18062     * Checks whether the parent or any of the child packages have a change shared
18063     * user. For a package to be a valid update the shred users of the parent and
18064     * the children should match. We may later support changing child shared users.
18065     * @param oldPkg The updated package.
18066     * @param newPkg The update package.
18067     * @return The shared user that change between the versions.
18068     */
18069    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
18070            PackageParser.Package newPkg) {
18071        // Check parent shared user
18072        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
18073            return newPkg.packageName;
18074        }
18075        // Check child shared users
18076        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18077        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
18078        for (int i = 0; i < newChildCount; i++) {
18079            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
18080            // If this child was present, did it have the same shared user?
18081            for (int j = 0; j < oldChildCount; j++) {
18082                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
18083                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
18084                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
18085                    return newChildPkg.packageName;
18086                }
18087            }
18088        }
18089        return null;
18090    }
18091
18092    private void removeNativeBinariesLI(PackageSetting ps) {
18093        // Remove the lib path for the parent package
18094        if (ps != null) {
18095            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
18096            // Remove the lib path for the child packages
18097            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18098            for (int i = 0; i < childCount; i++) {
18099                PackageSetting childPs = null;
18100                synchronized (mPackages) {
18101                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18102                }
18103                if (childPs != null) {
18104                    NativeLibraryHelper.removeNativeBinariesLI(childPs
18105                            .legacyNativeLibraryPathString);
18106                }
18107            }
18108        }
18109    }
18110
18111    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18112        // Enable the parent package
18113        mSettings.enableSystemPackageLPw(pkg.packageName);
18114        // Enable the child packages
18115        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18116        for (int i = 0; i < childCount; i++) {
18117            PackageParser.Package childPkg = pkg.childPackages.get(i);
18118            mSettings.enableSystemPackageLPw(childPkg.packageName);
18119        }
18120    }
18121
18122    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18123            PackageParser.Package newPkg) {
18124        // Disable the parent package (parent always replaced)
18125        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18126        // Disable the child packages
18127        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18128        for (int i = 0; i < childCount; i++) {
18129            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18130            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18131            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18132        }
18133        return disabled;
18134    }
18135
18136    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18137            String installerPackageName) {
18138        // Enable the parent package
18139        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18140        // Enable the child packages
18141        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18142        for (int i = 0; i < childCount; i++) {
18143            PackageParser.Package childPkg = pkg.childPackages.get(i);
18144            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18145        }
18146    }
18147
18148    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18149        // Collect all used permissions in the UID
18150        ArraySet<String> usedPermissions = new ArraySet<>();
18151        final int packageCount = su.packages.size();
18152        for (int i = 0; i < packageCount; i++) {
18153            PackageSetting ps = su.packages.valueAt(i);
18154            if (ps.pkg == null) {
18155                continue;
18156            }
18157            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18158            for (int j = 0; j < requestedPermCount; j++) {
18159                String permission = ps.pkg.requestedPermissions.get(j);
18160                BasePermission bp = mSettings.mPermissions.get(permission);
18161                if (bp != null) {
18162                    usedPermissions.add(permission);
18163                }
18164            }
18165        }
18166
18167        PermissionsState permissionsState = su.getPermissionsState();
18168        // Prune install permissions
18169        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18170        final int installPermCount = installPermStates.size();
18171        for (int i = installPermCount - 1; i >= 0;  i--) {
18172            PermissionState permissionState = installPermStates.get(i);
18173            if (!usedPermissions.contains(permissionState.getName())) {
18174                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18175                if (bp != null) {
18176                    permissionsState.revokeInstallPermission(bp);
18177                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18178                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18179                }
18180            }
18181        }
18182
18183        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18184
18185        // Prune runtime permissions
18186        for (int userId : allUserIds) {
18187            List<PermissionState> runtimePermStates = permissionsState
18188                    .getRuntimePermissionStates(userId);
18189            final int runtimePermCount = runtimePermStates.size();
18190            for (int i = runtimePermCount - 1; i >= 0; i--) {
18191                PermissionState permissionState = runtimePermStates.get(i);
18192                if (!usedPermissions.contains(permissionState.getName())) {
18193                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18194                    if (bp != null) {
18195                        permissionsState.revokeRuntimePermission(bp, userId);
18196                        permissionsState.updatePermissionFlags(bp, userId,
18197                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18198                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18199                                runtimePermissionChangedUserIds, userId);
18200                    }
18201                }
18202            }
18203        }
18204
18205        return runtimePermissionChangedUserIds;
18206    }
18207
18208    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18209            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18210        // Update the parent package setting
18211        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18212                res, user, installReason);
18213        // Update the child packages setting
18214        final int childCount = (newPackage.childPackages != null)
18215                ? newPackage.childPackages.size() : 0;
18216        for (int i = 0; i < childCount; i++) {
18217            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18218            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18219            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18220                    childRes.origUsers, childRes, user, installReason);
18221        }
18222    }
18223
18224    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18225            String installerPackageName, int[] allUsers, int[] installedForUsers,
18226            PackageInstalledInfo res, UserHandle user, int installReason) {
18227        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18228
18229        String pkgName = newPackage.packageName;
18230        synchronized (mPackages) {
18231            //write settings. the installStatus will be incomplete at this stage.
18232            //note that the new package setting would have already been
18233            //added to mPackages. It hasn't been persisted yet.
18234            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18235            // TODO: Remove this write? It's also written at the end of this method
18236            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18237            mSettings.writeLPr();
18238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18239        }
18240
18241        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18242        synchronized (mPackages) {
18243            updatePermissionsLPw(newPackage.packageName, newPackage,
18244                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18245                            ? UPDATE_PERMISSIONS_ALL : 0));
18246            // For system-bundled packages, we assume that installing an upgraded version
18247            // of the package implies that the user actually wants to run that new code,
18248            // so we enable the package.
18249            PackageSetting ps = mSettings.mPackages.get(pkgName);
18250            final int userId = user.getIdentifier();
18251            if (ps != null) {
18252                if (isSystemApp(newPackage)) {
18253                    if (DEBUG_INSTALL) {
18254                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18255                    }
18256                    // Enable system package for requested users
18257                    if (res.origUsers != null) {
18258                        for (int origUserId : res.origUsers) {
18259                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18260                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18261                                        origUserId, installerPackageName);
18262                            }
18263                        }
18264                    }
18265                    // Also convey the prior install/uninstall state
18266                    if (allUsers != null && installedForUsers != null) {
18267                        for (int currentUserId : allUsers) {
18268                            final boolean installed = ArrayUtils.contains(
18269                                    installedForUsers, currentUserId);
18270                            if (DEBUG_INSTALL) {
18271                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18272                            }
18273                            ps.setInstalled(installed, currentUserId);
18274                        }
18275                        // these install state changes will be persisted in the
18276                        // upcoming call to mSettings.writeLPr().
18277                    }
18278                }
18279                // It's implied that when a user requests installation, they want the app to be
18280                // installed and enabled.
18281                if (userId != UserHandle.USER_ALL) {
18282                    ps.setInstalled(true, userId);
18283                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18284                }
18285
18286                // When replacing an existing package, preserve the original install reason for all
18287                // users that had the package installed before.
18288                final Set<Integer> previousUserIds = new ArraySet<>();
18289                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18290                    final int installReasonCount = res.removedInfo.installReasons.size();
18291                    for (int i = 0; i < installReasonCount; i++) {
18292                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18293                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18294                        ps.setInstallReason(previousInstallReason, previousUserId);
18295                        previousUserIds.add(previousUserId);
18296                    }
18297                }
18298
18299                // Set install reason for users that are having the package newly installed.
18300                if (userId == UserHandle.USER_ALL) {
18301                    for (int currentUserId : sUserManager.getUserIds()) {
18302                        if (!previousUserIds.contains(currentUserId)) {
18303                            ps.setInstallReason(installReason, currentUserId);
18304                        }
18305                    }
18306                } else if (!previousUserIds.contains(userId)) {
18307                    ps.setInstallReason(installReason, userId);
18308                }
18309                mSettings.writeKernelMappingLPr(ps);
18310            }
18311            res.name = pkgName;
18312            res.uid = newPackage.applicationInfo.uid;
18313            res.pkg = newPackage;
18314            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18315            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18316            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18317            //to update install status
18318            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18319            mSettings.writeLPr();
18320            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18321        }
18322
18323        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18324    }
18325
18326    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18327        try {
18328            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18329            installPackageLI(args, res);
18330        } finally {
18331            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18332        }
18333    }
18334
18335    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18336        final int installFlags = args.installFlags;
18337        final String installerPackageName = args.installerPackageName;
18338        final String volumeUuid = args.volumeUuid;
18339        final File tmpPackageFile = new File(args.getCodePath());
18340        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18341        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18342                || (args.volumeUuid != null));
18343        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18344        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18345        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18346        final boolean virtualPreload =
18347                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18348        boolean replace = false;
18349        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18350        if (args.move != null) {
18351            // moving a complete application; perform an initial scan on the new install location
18352            scanFlags |= SCAN_INITIAL;
18353        }
18354        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18355            scanFlags |= SCAN_DONT_KILL_APP;
18356        }
18357        if (instantApp) {
18358            scanFlags |= SCAN_AS_INSTANT_APP;
18359        }
18360        if (fullApp) {
18361            scanFlags |= SCAN_AS_FULL_APP;
18362        }
18363        if (virtualPreload) {
18364            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18365        }
18366
18367        // Result object to be returned
18368        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18369        res.installerPackageName = installerPackageName;
18370
18371        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18372
18373        // Sanity check
18374        if (instantApp && (forwardLocked || onExternal)) {
18375            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18376                    + " external=" + onExternal);
18377            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18378            return;
18379        }
18380
18381        // Retrieve PackageSettings and parse package
18382        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18383                | PackageParser.PARSE_ENFORCE_CODE
18384                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18385                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18386                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18387                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18388        PackageParser pp = new PackageParser();
18389        pp.setSeparateProcesses(mSeparateProcesses);
18390        pp.setDisplayMetrics(mMetrics);
18391        pp.setCallback(mPackageParserCallback);
18392
18393        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18394        final PackageParser.Package pkg;
18395        try {
18396            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18397        } catch (PackageParserException e) {
18398            res.setError("Failed parse during installPackageLI", e);
18399            return;
18400        } finally {
18401            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18402        }
18403
18404        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18405        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18406            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18407            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18408                    "Instant app package must target O");
18409            return;
18410        }
18411        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18412            Slog.w(TAG, "Instant app package " + pkg.packageName
18413                    + " does not target targetSandboxVersion 2");
18414            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18415                    "Instant app package must use targetSanboxVersion 2");
18416            return;
18417        }
18418
18419        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18420            // Static shared libraries have synthetic package names
18421            renameStaticSharedLibraryPackage(pkg);
18422
18423            // No static shared libs on external storage
18424            if (onExternal) {
18425                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18426                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18427                        "Packages declaring static-shared libs cannot be updated");
18428                return;
18429            }
18430        }
18431
18432        // If we are installing a clustered package add results for the children
18433        if (pkg.childPackages != null) {
18434            synchronized (mPackages) {
18435                final int childCount = pkg.childPackages.size();
18436                for (int i = 0; i < childCount; i++) {
18437                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18438                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18439                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18440                    childRes.pkg = childPkg;
18441                    childRes.name = childPkg.packageName;
18442                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18443                    if (childPs != null) {
18444                        childRes.origUsers = childPs.queryInstalledUsers(
18445                                sUserManager.getUserIds(), true);
18446                    }
18447                    if ((mPackages.containsKey(childPkg.packageName))) {
18448                        childRes.removedInfo = new PackageRemovedInfo(this);
18449                        childRes.removedInfo.removedPackage = childPkg.packageName;
18450                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18451                    }
18452                    if (res.addedChildPackages == null) {
18453                        res.addedChildPackages = new ArrayMap<>();
18454                    }
18455                    res.addedChildPackages.put(childPkg.packageName, childRes);
18456                }
18457            }
18458        }
18459
18460        // If package doesn't declare API override, mark that we have an install
18461        // time CPU ABI override.
18462        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18463            pkg.cpuAbiOverride = args.abiOverride;
18464        }
18465
18466        String pkgName = res.name = pkg.packageName;
18467        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18468            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18469                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18470                return;
18471            }
18472        }
18473
18474        try {
18475            // either use what we've been given or parse directly from the APK
18476            if (args.certificates != null) {
18477                try {
18478                    PackageParser.populateCertificates(pkg, args.certificates);
18479                } catch (PackageParserException e) {
18480                    // there was something wrong with the certificates we were given;
18481                    // try to pull them from the APK
18482                    PackageParser.collectCertificates(pkg, parseFlags);
18483                }
18484            } else {
18485                PackageParser.collectCertificates(pkg, parseFlags);
18486            }
18487        } catch (PackageParserException e) {
18488            res.setError("Failed collect during installPackageLI", e);
18489            return;
18490        }
18491
18492        // Get rid of all references to package scan path via parser.
18493        pp = null;
18494        String oldCodePath = null;
18495        boolean systemApp = false;
18496        synchronized (mPackages) {
18497            // Check if installing already existing package
18498            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18499                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18500                if (pkg.mOriginalPackages != null
18501                        && pkg.mOriginalPackages.contains(oldName)
18502                        && mPackages.containsKey(oldName)) {
18503                    // This package is derived from an original package,
18504                    // and this device has been updating from that original
18505                    // name.  We must continue using the original name, so
18506                    // rename the new package here.
18507                    pkg.setPackageName(oldName);
18508                    pkgName = pkg.packageName;
18509                    replace = true;
18510                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18511                            + oldName + " pkgName=" + pkgName);
18512                } else if (mPackages.containsKey(pkgName)) {
18513                    // This package, under its official name, already exists
18514                    // on the device; we should replace it.
18515                    replace = true;
18516                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18517                }
18518
18519                // Child packages are installed through the parent package
18520                if (pkg.parentPackage != null) {
18521                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18522                            "Package " + pkg.packageName + " is child of package "
18523                                    + pkg.parentPackage.parentPackage + ". Child packages "
18524                                    + "can be updated only through the parent package.");
18525                    return;
18526                }
18527
18528                if (replace) {
18529                    // Prevent apps opting out from runtime permissions
18530                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18531                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18532                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18533                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18534                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18535                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18536                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18537                                        + " doesn't support runtime permissions but the old"
18538                                        + " target SDK " + oldTargetSdk + " does.");
18539                        return;
18540                    }
18541                    // Prevent apps from downgrading their targetSandbox.
18542                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18543                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18544                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18545                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18546                                "Package " + pkg.packageName + " new target sandbox "
18547                                + newTargetSandbox + " is incompatible with the previous value of"
18548                                + oldTargetSandbox + ".");
18549                        return;
18550                    }
18551
18552                    // Prevent installing of child packages
18553                    if (oldPackage.parentPackage != null) {
18554                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18555                                "Package " + pkg.packageName + " is child of package "
18556                                        + oldPackage.parentPackage + ". Child packages "
18557                                        + "can be updated only through the parent package.");
18558                        return;
18559                    }
18560                }
18561            }
18562
18563            PackageSetting ps = mSettings.mPackages.get(pkgName);
18564            if (ps != null) {
18565                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18566
18567                // Static shared libs have same package with different versions where
18568                // we internally use a synthetic package name to allow multiple versions
18569                // of the same package, therefore we need to compare signatures against
18570                // the package setting for the latest library version.
18571                PackageSetting signatureCheckPs = ps;
18572                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18573                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18574                    if (libraryEntry != null) {
18575                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18576                    }
18577                }
18578
18579                // Quick sanity check that we're signed correctly if updating;
18580                // we'll check this again later when scanning, but we want to
18581                // bail early here before tripping over redefined permissions.
18582                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18583                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18584                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18585                                + pkg.packageName + " upgrade keys do not match the "
18586                                + "previously installed version");
18587                        return;
18588                    }
18589                } else {
18590                    try {
18591                        verifySignaturesLP(signatureCheckPs, pkg);
18592                    } catch (PackageManagerException e) {
18593                        res.setError(e.error, e.getMessage());
18594                        return;
18595                    }
18596                }
18597
18598                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18599                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18600                    systemApp = (ps.pkg.applicationInfo.flags &
18601                            ApplicationInfo.FLAG_SYSTEM) != 0;
18602                }
18603                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18604            }
18605
18606            int N = pkg.permissions.size();
18607            for (int i = N-1; i >= 0; i--) {
18608                PackageParser.Permission perm = pkg.permissions.get(i);
18609                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18610
18611                // Don't allow anyone but the system to define ephemeral permissions.
18612                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
18613                        && !systemApp) {
18614                    Slog.w(TAG, "Non-System package " + pkg.packageName
18615                            + " attempting to delcare ephemeral permission "
18616                            + perm.info.name + "; Removing ephemeral.");
18617                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
18618                }
18619                // Check whether the newly-scanned package wants to define an already-defined perm
18620                if (bp != null) {
18621                    // If the defining package is signed with our cert, it's okay.  This
18622                    // also includes the "updating the same package" case, of course.
18623                    // "updating same package" could also involve key-rotation.
18624                    final boolean sigsOk;
18625                    if (bp.sourcePackage.equals(pkg.packageName)
18626                            && (bp.packageSetting instanceof PackageSetting)
18627                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18628                                    scanFlags))) {
18629                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18630                    } else {
18631                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18632                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18633                    }
18634                    if (!sigsOk) {
18635                        // If the owning package is the system itself, we log but allow
18636                        // install to proceed; we fail the install on all other permission
18637                        // redefinitions.
18638                        if (!bp.sourcePackage.equals("android")) {
18639                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18640                                    + pkg.packageName + " attempting to redeclare permission "
18641                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18642                            res.origPermission = perm.info.name;
18643                            res.origPackage = bp.sourcePackage;
18644                            return;
18645                        } else {
18646                            Slog.w(TAG, "Package " + pkg.packageName
18647                                    + " attempting to redeclare system permission "
18648                                    + perm.info.name + "; ignoring new declaration");
18649                            pkg.permissions.remove(i);
18650                        }
18651                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18652                        // Prevent apps to change protection level to dangerous from any other
18653                        // type as this would allow a privilege escalation where an app adds a
18654                        // normal/signature permission in other app's group and later redefines
18655                        // it as dangerous leading to the group auto-grant.
18656                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18657                                == PermissionInfo.PROTECTION_DANGEROUS) {
18658                            if (bp != null && !bp.isRuntime()) {
18659                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18660                                        + "non-runtime permission " + perm.info.name
18661                                        + " to runtime; keeping old protection level");
18662                                perm.info.protectionLevel = bp.protectionLevel;
18663                            }
18664                        }
18665                    }
18666                }
18667            }
18668        }
18669
18670        if (systemApp) {
18671            if (onExternal) {
18672                // Abort update; system app can't be replaced with app on sdcard
18673                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18674                        "Cannot install updates to system apps on sdcard");
18675                return;
18676            } else if (instantApp) {
18677                // Abort update; system app can't be replaced with an instant app
18678                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18679                        "Cannot update a system app with an instant app");
18680                return;
18681            }
18682        }
18683
18684        if (args.move != null) {
18685            // We did an in-place move, so dex is ready to roll
18686            scanFlags |= SCAN_NO_DEX;
18687            scanFlags |= SCAN_MOVE;
18688
18689            synchronized (mPackages) {
18690                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18691                if (ps == null) {
18692                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18693                            "Missing settings for moved package " + pkgName);
18694                }
18695
18696                // We moved the entire application as-is, so bring over the
18697                // previously derived ABI information.
18698                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18699                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18700            }
18701
18702        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18703            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18704            scanFlags |= SCAN_NO_DEX;
18705
18706            try {
18707                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18708                    args.abiOverride : pkg.cpuAbiOverride);
18709                final boolean extractNativeLibs = !pkg.isLibrary();
18710                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18711                        extractNativeLibs, mAppLib32InstallDir);
18712            } catch (PackageManagerException pme) {
18713                Slog.e(TAG, "Error deriving application ABI", pme);
18714                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18715                return;
18716            }
18717
18718            // Shared libraries for the package need to be updated.
18719            synchronized (mPackages) {
18720                try {
18721                    updateSharedLibrariesLPr(pkg, null);
18722                } catch (PackageManagerException e) {
18723                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18724                }
18725            }
18726        }
18727
18728        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18729            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18730            return;
18731        }
18732
18733        // Verify if we need to dexopt the app.
18734        //
18735        // NOTE: it is *important* to call dexopt after doRename which will sync the
18736        // package data from PackageParser.Package and its corresponding ApplicationInfo.
18737        //
18738        // We only need to dexopt if the package meets ALL of the following conditions:
18739        //   1) it is not forward locked.
18740        //   2) it is not on on an external ASEC container.
18741        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
18742        //
18743        // Note that we do not dexopt instant apps by default. dexopt can take some time to
18744        // complete, so we skip this step during installation. Instead, we'll take extra time
18745        // the first time the instant app starts. It's preferred to do it this way to provide
18746        // continuous progress to the useur instead of mysteriously blocking somewhere in the
18747        // middle of running an instant app. The default behaviour can be overridden
18748        // via gservices.
18749        final boolean performDexopt = !forwardLocked
18750            && !pkg.applicationInfo.isExternalAsec()
18751            && (!instantApp || Global.getInt(mContext.getContentResolver(),
18752                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
18753
18754        if (performDexopt) {
18755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18756            // Do not run PackageDexOptimizer through the local performDexOpt
18757            // method because `pkg` may not be in `mPackages` yet.
18758            //
18759            // Also, don't fail application installs if the dexopt step fails.
18760            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18761                REASON_INSTALL,
18762                DexoptOptions.DEXOPT_BOOT_COMPLETE);
18763            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18764                null /* instructionSets */,
18765                getOrCreateCompilerPackageStats(pkg),
18766                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18767                dexoptOptions);
18768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18769        }
18770
18771        // Notify BackgroundDexOptService that the package has been changed.
18772        // If this is an update of a package which used to fail to compile,
18773        // BackgroundDexOptService will remove it from its blacklist.
18774        // TODO: Layering violation
18775        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18776
18777        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18778
18779        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18780                "installPackageLI")) {
18781            if (replace) {
18782                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18783                    // Static libs have a synthetic package name containing the version
18784                    // and cannot be updated as an update would get a new package name,
18785                    // unless this is the exact same version code which is useful for
18786                    // development.
18787                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18788                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18789                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18790                                + "static-shared libs cannot be updated");
18791                        return;
18792                    }
18793                }
18794                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18795                        installerPackageName, res, args.installReason);
18796            } else {
18797                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18798                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18799            }
18800        }
18801
18802        synchronized (mPackages) {
18803            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18804            if (ps != null) {
18805                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18806                ps.setUpdateAvailable(false /*updateAvailable*/);
18807            }
18808
18809            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18810            for (int i = 0; i < childCount; i++) {
18811                PackageParser.Package childPkg = pkg.childPackages.get(i);
18812                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18813                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18814                if (childPs != null) {
18815                    childRes.newUsers = childPs.queryInstalledUsers(
18816                            sUserManager.getUserIds(), true);
18817                }
18818            }
18819
18820            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18821                updateSequenceNumberLP(ps, res.newUsers);
18822                updateInstantAppInstallerLocked(pkgName);
18823            }
18824        }
18825    }
18826
18827    private void startIntentFilterVerifications(int userId, boolean replacing,
18828            PackageParser.Package pkg) {
18829        if (mIntentFilterVerifierComponent == null) {
18830            Slog.w(TAG, "No IntentFilter verification will not be done as "
18831                    + "there is no IntentFilterVerifier available!");
18832            return;
18833        }
18834
18835        final int verifierUid = getPackageUid(
18836                mIntentFilterVerifierComponent.getPackageName(),
18837                MATCH_DEBUG_TRIAGED_MISSING,
18838                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18839
18840        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18841        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18842        mHandler.sendMessage(msg);
18843
18844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18845        for (int i = 0; i < childCount; i++) {
18846            PackageParser.Package childPkg = pkg.childPackages.get(i);
18847            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18848            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18849            mHandler.sendMessage(msg);
18850        }
18851    }
18852
18853    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18854            PackageParser.Package pkg) {
18855        int size = pkg.activities.size();
18856        if (size == 0) {
18857            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18858                    "No activity, so no need to verify any IntentFilter!");
18859            return;
18860        }
18861
18862        final boolean hasDomainURLs = hasDomainURLs(pkg);
18863        if (!hasDomainURLs) {
18864            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18865                    "No domain URLs, so no need to verify any IntentFilter!");
18866            return;
18867        }
18868
18869        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18870                + " if any IntentFilter from the " + size
18871                + " Activities needs verification ...");
18872
18873        int count = 0;
18874        final String packageName = pkg.packageName;
18875
18876        synchronized (mPackages) {
18877            // If this is a new install and we see that we've already run verification for this
18878            // package, we have nothing to do: it means the state was restored from backup.
18879            if (!replacing) {
18880                IntentFilterVerificationInfo ivi =
18881                        mSettings.getIntentFilterVerificationLPr(packageName);
18882                if (ivi != null) {
18883                    if (DEBUG_DOMAIN_VERIFICATION) {
18884                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18885                                + ivi.getStatusString());
18886                    }
18887                    return;
18888                }
18889            }
18890
18891            // If any filters need to be verified, then all need to be.
18892            boolean needToVerify = false;
18893            for (PackageParser.Activity a : pkg.activities) {
18894                for (ActivityIntentInfo filter : a.intents) {
18895                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18896                        if (DEBUG_DOMAIN_VERIFICATION) {
18897                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18898                        }
18899                        needToVerify = true;
18900                        break;
18901                    }
18902                }
18903            }
18904
18905            if (needToVerify) {
18906                final int verificationId = mIntentFilterVerificationToken++;
18907                for (PackageParser.Activity a : pkg.activities) {
18908                    for (ActivityIntentInfo filter : a.intents) {
18909                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18910                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18911                                    "Verification needed for IntentFilter:" + filter.toString());
18912                            mIntentFilterVerifier.addOneIntentFilterVerification(
18913                                    verifierUid, userId, verificationId, filter, packageName);
18914                            count++;
18915                        }
18916                    }
18917                }
18918            }
18919        }
18920
18921        if (count > 0) {
18922            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18923                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18924                    +  " for userId:" + userId);
18925            mIntentFilterVerifier.startVerifications(userId);
18926        } else {
18927            if (DEBUG_DOMAIN_VERIFICATION) {
18928                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18929            }
18930        }
18931    }
18932
18933    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18934        final ComponentName cn  = filter.activity.getComponentName();
18935        final String packageName = cn.getPackageName();
18936
18937        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18938                packageName);
18939        if (ivi == null) {
18940            return true;
18941        }
18942        int status = ivi.getStatus();
18943        switch (status) {
18944            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18945            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18946                return true;
18947
18948            default:
18949                // Nothing to do
18950                return false;
18951        }
18952    }
18953
18954    private static boolean isMultiArch(ApplicationInfo info) {
18955        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18956    }
18957
18958    private static boolean isExternal(PackageParser.Package pkg) {
18959        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18960    }
18961
18962    private static boolean isExternal(PackageSetting ps) {
18963        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18964    }
18965
18966    private static boolean isSystemApp(PackageParser.Package pkg) {
18967        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18968    }
18969
18970    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18971        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18972    }
18973
18974    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18975        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18976    }
18977
18978    private static boolean isSystemApp(PackageSetting ps) {
18979        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18980    }
18981
18982    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18983        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18984    }
18985
18986    private int packageFlagsToInstallFlags(PackageSetting ps) {
18987        int installFlags = 0;
18988        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18989            // This existing package was an external ASEC install when we have
18990            // the external flag without a UUID
18991            installFlags |= PackageManager.INSTALL_EXTERNAL;
18992        }
18993        if (ps.isForwardLocked()) {
18994            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18995        }
18996        return installFlags;
18997    }
18998
18999    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
19000        if (isExternal(pkg)) {
19001            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19002                return StorageManager.UUID_PRIMARY_PHYSICAL;
19003            } else {
19004                return pkg.volumeUuid;
19005            }
19006        } else {
19007            return StorageManager.UUID_PRIVATE_INTERNAL;
19008        }
19009    }
19010
19011    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
19012        if (isExternal(pkg)) {
19013            if (TextUtils.isEmpty(pkg.volumeUuid)) {
19014                return mSettings.getExternalVersion();
19015            } else {
19016                return mSettings.findOrCreateVersion(pkg.volumeUuid);
19017            }
19018        } else {
19019            return mSettings.getInternalVersion();
19020        }
19021    }
19022
19023    private void deleteTempPackageFiles() {
19024        final FilenameFilter filter = new FilenameFilter() {
19025            public boolean accept(File dir, String name) {
19026                return name.startsWith("vmdl") && name.endsWith(".tmp");
19027            }
19028        };
19029        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
19030            file.delete();
19031        }
19032    }
19033
19034    @Override
19035    public void deletePackageAsUser(String packageName, int versionCode,
19036            IPackageDeleteObserver observer, int userId, int flags) {
19037        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
19038                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
19039    }
19040
19041    @Override
19042    public void deletePackageVersioned(VersionedPackage versionedPackage,
19043            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
19044        final int callingUid = Binder.getCallingUid();
19045        mContext.enforceCallingOrSelfPermission(
19046                android.Manifest.permission.DELETE_PACKAGES, null);
19047        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
19048        Preconditions.checkNotNull(versionedPackage);
19049        Preconditions.checkNotNull(observer);
19050        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
19051                PackageManager.VERSION_CODE_HIGHEST,
19052                Integer.MAX_VALUE, "versionCode must be >= -1");
19053
19054        final String packageName = versionedPackage.getPackageName();
19055        final int versionCode = versionedPackage.getVersionCode();
19056        final String internalPackageName;
19057        synchronized (mPackages) {
19058            // Normalize package name to handle renamed packages and static libs
19059            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
19060                    versionedPackage.getVersionCode());
19061        }
19062
19063        final int uid = Binder.getCallingUid();
19064        if (!isOrphaned(internalPackageName)
19065                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
19066            try {
19067                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
19068                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
19069                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
19070                observer.onUserActionRequired(intent);
19071            } catch (RemoteException re) {
19072            }
19073            return;
19074        }
19075        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
19076        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
19077        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
19078            mContext.enforceCallingOrSelfPermission(
19079                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
19080                    "deletePackage for user " + userId);
19081        }
19082
19083        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
19084            try {
19085                observer.onPackageDeleted(packageName,
19086                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
19087            } catch (RemoteException re) {
19088            }
19089            return;
19090        }
19091
19092        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
19093            try {
19094                observer.onPackageDeleted(packageName,
19095                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
19096            } catch (RemoteException re) {
19097            }
19098            return;
19099        }
19100
19101        if (DEBUG_REMOVE) {
19102            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
19103                    + " deleteAllUsers: " + deleteAllUsers + " version="
19104                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
19105                    ? "VERSION_CODE_HIGHEST" : versionCode));
19106        }
19107        // Queue up an async operation since the package deletion may take a little while.
19108        mHandler.post(new Runnable() {
19109            public void run() {
19110                mHandler.removeCallbacks(this);
19111                int returnCode;
19112                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
19113                boolean doDeletePackage = true;
19114                if (ps != null) {
19115                    final boolean targetIsInstantApp =
19116                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19117                    doDeletePackage = !targetIsInstantApp
19118                            || canViewInstantApps;
19119                }
19120                if (doDeletePackage) {
19121                    if (!deleteAllUsers) {
19122                        returnCode = deletePackageX(internalPackageName, versionCode,
19123                                userId, deleteFlags);
19124                    } else {
19125                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19126                                internalPackageName, users);
19127                        // If nobody is blocking uninstall, proceed with delete for all users
19128                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19129                            returnCode = deletePackageX(internalPackageName, versionCode,
19130                                    userId, deleteFlags);
19131                        } else {
19132                            // Otherwise uninstall individually for users with blockUninstalls=false
19133                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19134                            for (int userId : users) {
19135                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19136                                    returnCode = deletePackageX(internalPackageName, versionCode,
19137                                            userId, userFlags);
19138                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19139                                        Slog.w(TAG, "Package delete failed for user " + userId
19140                                                + ", returnCode " + returnCode);
19141                                    }
19142                                }
19143                            }
19144                            // The app has only been marked uninstalled for certain users.
19145                            // We still need to report that delete was blocked
19146                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19147                        }
19148                    }
19149                } else {
19150                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19151                }
19152                try {
19153                    observer.onPackageDeleted(packageName, returnCode, null);
19154                } catch (RemoteException e) {
19155                    Log.i(TAG, "Observer no longer exists.");
19156                } //end catch
19157            } //end run
19158        });
19159    }
19160
19161    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19162        if (pkg.staticSharedLibName != null) {
19163            return pkg.manifestPackageName;
19164        }
19165        return pkg.packageName;
19166    }
19167
19168    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19169        // Handle renamed packages
19170        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19171        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19172
19173        // Is this a static library?
19174        SparseArray<SharedLibraryEntry> versionedLib =
19175                mStaticLibsByDeclaringPackage.get(packageName);
19176        if (versionedLib == null || versionedLib.size() <= 0) {
19177            return packageName;
19178        }
19179
19180        // Figure out which lib versions the caller can see
19181        SparseIntArray versionsCallerCanSee = null;
19182        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19183        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19184                && callingAppId != Process.ROOT_UID) {
19185            versionsCallerCanSee = new SparseIntArray();
19186            String libName = versionedLib.valueAt(0).info.getName();
19187            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19188            if (uidPackages != null) {
19189                for (String uidPackage : uidPackages) {
19190                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19191                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19192                    if (libIdx >= 0) {
19193                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19194                        versionsCallerCanSee.append(libVersion, libVersion);
19195                    }
19196                }
19197            }
19198        }
19199
19200        // Caller can see nothing - done
19201        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19202            return packageName;
19203        }
19204
19205        // Find the version the caller can see and the app version code
19206        SharedLibraryEntry highestVersion = null;
19207        final int versionCount = versionedLib.size();
19208        for (int i = 0; i < versionCount; i++) {
19209            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19210            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19211                    libEntry.info.getVersion()) < 0) {
19212                continue;
19213            }
19214            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19215            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19216                if (libVersionCode == versionCode) {
19217                    return libEntry.apk;
19218                }
19219            } else if (highestVersion == null) {
19220                highestVersion = libEntry;
19221            } else if (libVersionCode  > highestVersion.info
19222                    .getDeclaringPackage().getVersionCode()) {
19223                highestVersion = libEntry;
19224            }
19225        }
19226
19227        if (highestVersion != null) {
19228            return highestVersion.apk;
19229        }
19230
19231        return packageName;
19232    }
19233
19234    boolean isCallerVerifier(int callingUid) {
19235        final int callingUserId = UserHandle.getUserId(callingUid);
19236        return mRequiredVerifierPackage != null &&
19237                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19238    }
19239
19240    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19241        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19242              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19243            return true;
19244        }
19245        final int callingUserId = UserHandle.getUserId(callingUid);
19246        // If the caller installed the pkgName, then allow it to silently uninstall.
19247        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19248            return true;
19249        }
19250
19251        // Allow package verifier to silently uninstall.
19252        if (mRequiredVerifierPackage != null &&
19253                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19254            return true;
19255        }
19256
19257        // Allow package uninstaller to silently uninstall.
19258        if (mRequiredUninstallerPackage != null &&
19259                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19260            return true;
19261        }
19262
19263        // Allow storage manager to silently uninstall.
19264        if (mStorageManagerPackage != null &&
19265                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19266            return true;
19267        }
19268
19269        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19270        // uninstall for device owner provisioning.
19271        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19272                == PERMISSION_GRANTED) {
19273            return true;
19274        }
19275
19276        return false;
19277    }
19278
19279    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19280        int[] result = EMPTY_INT_ARRAY;
19281        for (int userId : userIds) {
19282            if (getBlockUninstallForUser(packageName, userId)) {
19283                result = ArrayUtils.appendInt(result, userId);
19284            }
19285        }
19286        return result;
19287    }
19288
19289    @Override
19290    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19291        final int callingUid = Binder.getCallingUid();
19292        if (getInstantAppPackageName(callingUid) != null
19293                && !isCallerSameApp(packageName, callingUid)) {
19294            return false;
19295        }
19296        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19297    }
19298
19299    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19300        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19301                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19302        try {
19303            if (dpm != null) {
19304                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19305                        /* callingUserOnly =*/ false);
19306                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19307                        : deviceOwnerComponentName.getPackageName();
19308                // Does the package contains the device owner?
19309                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19310                // this check is probably not needed, since DO should be registered as a device
19311                // admin on some user too. (Original bug for this: b/17657954)
19312                if (packageName.equals(deviceOwnerPackageName)) {
19313                    return true;
19314                }
19315                // Does it contain a device admin for any user?
19316                int[] users;
19317                if (userId == UserHandle.USER_ALL) {
19318                    users = sUserManager.getUserIds();
19319                } else {
19320                    users = new int[]{userId};
19321                }
19322                for (int i = 0; i < users.length; ++i) {
19323                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19324                        return true;
19325                    }
19326                }
19327            }
19328        } catch (RemoteException e) {
19329        }
19330        return false;
19331    }
19332
19333    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19334        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19335    }
19336
19337    /**
19338     *  This method is an internal method that could be get invoked either
19339     *  to delete an installed package or to clean up a failed installation.
19340     *  After deleting an installed package, a broadcast is sent to notify any
19341     *  listeners that the package has been removed. For cleaning up a failed
19342     *  installation, the broadcast is not necessary since the package's
19343     *  installation wouldn't have sent the initial broadcast either
19344     *  The key steps in deleting a package are
19345     *  deleting the package information in internal structures like mPackages,
19346     *  deleting the packages base directories through installd
19347     *  updating mSettings to reflect current status
19348     *  persisting settings for later use
19349     *  sending a broadcast if necessary
19350     */
19351    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19352        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19353        final boolean res;
19354
19355        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19356                ? UserHandle.USER_ALL : userId;
19357
19358        if (isPackageDeviceAdmin(packageName, removeUser)) {
19359            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19360            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19361        }
19362
19363        PackageSetting uninstalledPs = null;
19364        PackageParser.Package pkg = null;
19365
19366        // for the uninstall-updates case and restricted profiles, remember the per-
19367        // user handle installed state
19368        int[] allUsers;
19369        synchronized (mPackages) {
19370            uninstalledPs = mSettings.mPackages.get(packageName);
19371            if (uninstalledPs == null) {
19372                Slog.w(TAG, "Not removing non-existent package " + packageName);
19373                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19374            }
19375
19376            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19377                    && uninstalledPs.versionCode != versionCode) {
19378                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19379                        + uninstalledPs.versionCode + " != " + versionCode);
19380                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19381            }
19382
19383            // Static shared libs can be declared by any package, so let us not
19384            // allow removing a package if it provides a lib others depend on.
19385            pkg = mPackages.get(packageName);
19386
19387            allUsers = sUserManager.getUserIds();
19388
19389            if (pkg != null && pkg.staticSharedLibName != null) {
19390                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19391                        pkg.staticSharedLibVersion);
19392                if (libEntry != null) {
19393                    for (int currUserId : allUsers) {
19394                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19395                            continue;
19396                        }
19397                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19398                                libEntry.info, 0, currUserId);
19399                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19400                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19401                                    + " hosting lib " + libEntry.info.getName() + " version "
19402                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19403                                    + " for user " + currUserId);
19404                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19405                        }
19406                    }
19407                }
19408            }
19409
19410            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19411        }
19412
19413        final int freezeUser;
19414        if (isUpdatedSystemApp(uninstalledPs)
19415                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19416            // We're downgrading a system app, which will apply to all users, so
19417            // freeze them all during the downgrade
19418            freezeUser = UserHandle.USER_ALL;
19419        } else {
19420            freezeUser = removeUser;
19421        }
19422
19423        synchronized (mInstallLock) {
19424            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19425            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19426                    deleteFlags, "deletePackageX")) {
19427                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19428                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19429            }
19430            synchronized (mPackages) {
19431                if (res) {
19432                    if (pkg != null) {
19433                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19434                    }
19435                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19436                    updateInstantAppInstallerLocked(packageName);
19437                }
19438            }
19439        }
19440
19441        if (res) {
19442            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19443            info.sendPackageRemovedBroadcasts(killApp);
19444            info.sendSystemPackageUpdatedBroadcasts();
19445            info.sendSystemPackageAppearedBroadcasts();
19446        }
19447        // Force a gc here.
19448        Runtime.getRuntime().gc();
19449        // Delete the resources here after sending the broadcast to let
19450        // other processes clean up before deleting resources.
19451        if (info.args != null) {
19452            synchronized (mInstallLock) {
19453                info.args.doPostDeleteLI(true);
19454            }
19455        }
19456
19457        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19458    }
19459
19460    static class PackageRemovedInfo {
19461        final PackageSender packageSender;
19462        String removedPackage;
19463        String installerPackageName;
19464        int uid = -1;
19465        int removedAppId = -1;
19466        int[] origUsers;
19467        int[] removedUsers = null;
19468        int[] broadcastUsers = null;
19469        SparseArray<Integer> installReasons;
19470        boolean isRemovedPackageSystemUpdate = false;
19471        boolean isUpdate;
19472        boolean dataRemoved;
19473        boolean removedForAllUsers;
19474        boolean isStaticSharedLib;
19475        // Clean up resources deleted packages.
19476        InstallArgs args = null;
19477        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19478        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19479
19480        PackageRemovedInfo(PackageSender packageSender) {
19481            this.packageSender = packageSender;
19482        }
19483
19484        void sendPackageRemovedBroadcasts(boolean killApp) {
19485            sendPackageRemovedBroadcastInternal(killApp);
19486            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19487            for (int i = 0; i < childCount; i++) {
19488                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19489                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19490            }
19491        }
19492
19493        void sendSystemPackageUpdatedBroadcasts() {
19494            if (isRemovedPackageSystemUpdate) {
19495                sendSystemPackageUpdatedBroadcastsInternal();
19496                final int childCount = (removedChildPackages != null)
19497                        ? removedChildPackages.size() : 0;
19498                for (int i = 0; i < childCount; i++) {
19499                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19500                    if (childInfo.isRemovedPackageSystemUpdate) {
19501                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19502                    }
19503                }
19504            }
19505        }
19506
19507        void sendSystemPackageAppearedBroadcasts() {
19508            final int packageCount = (appearedChildPackages != null)
19509                    ? appearedChildPackages.size() : 0;
19510            for (int i = 0; i < packageCount; i++) {
19511                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19512                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19513                    true /*sendBootCompleted*/, false /*startReceiver*/,
19514                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19515            }
19516        }
19517
19518        private void sendSystemPackageUpdatedBroadcastsInternal() {
19519            Bundle extras = new Bundle(2);
19520            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19521            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19522            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19523                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19524            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19525                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19526            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19527                null, null, 0, removedPackage, null, null);
19528            if (installerPackageName != null) {
19529                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19530                        removedPackage, extras, 0 /*flags*/,
19531                        installerPackageName, null, null);
19532                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19533                        removedPackage, extras, 0 /*flags*/,
19534                        installerPackageName, null, null);
19535            }
19536        }
19537
19538        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19539            // Don't send static shared library removal broadcasts as these
19540            // libs are visible only the the apps that depend on them an one
19541            // cannot remove the library if it has a dependency.
19542            if (isStaticSharedLib) {
19543                return;
19544            }
19545            Bundle extras = new Bundle(2);
19546            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19547            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19548            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19549            if (isUpdate || isRemovedPackageSystemUpdate) {
19550                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19551            }
19552            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19553            if (removedPackage != null) {
19554                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19555                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19556                if (installerPackageName != null) {
19557                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19558                            removedPackage, extras, 0 /*flags*/,
19559                            installerPackageName, null, broadcastUsers);
19560                }
19561                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19562                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19563                        removedPackage, extras,
19564                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19565                        null, null, broadcastUsers);
19566                }
19567            }
19568            if (removedAppId >= 0) {
19569                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19570                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19571                    null, null, broadcastUsers);
19572            }
19573        }
19574
19575        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19576            removedUsers = userIds;
19577            if (removedUsers == null) {
19578                broadcastUsers = null;
19579                return;
19580            }
19581
19582            broadcastUsers = EMPTY_INT_ARRAY;
19583            for (int i = userIds.length - 1; i >= 0; --i) {
19584                final int userId = userIds[i];
19585                if (deletedPackageSetting.getInstantApp(userId)) {
19586                    continue;
19587                }
19588                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19589            }
19590        }
19591    }
19592
19593    /*
19594     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19595     * flag is not set, the data directory is removed as well.
19596     * make sure this flag is set for partially installed apps. If not its meaningless to
19597     * delete a partially installed application.
19598     */
19599    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19600            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19601        String packageName = ps.name;
19602        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19603        // Retrieve object to delete permissions for shared user later on
19604        final PackageParser.Package deletedPkg;
19605        final PackageSetting deletedPs;
19606        // reader
19607        synchronized (mPackages) {
19608            deletedPkg = mPackages.get(packageName);
19609            deletedPs = mSettings.mPackages.get(packageName);
19610            if (outInfo != null) {
19611                outInfo.removedPackage = packageName;
19612                outInfo.installerPackageName = ps.installerPackageName;
19613                outInfo.isStaticSharedLib = deletedPkg != null
19614                        && deletedPkg.staticSharedLibName != null;
19615                outInfo.populateUsers(deletedPs == null ? null
19616                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19617            }
19618        }
19619
19620        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19621
19622        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19623            final PackageParser.Package resolvedPkg;
19624            if (deletedPkg != null) {
19625                resolvedPkg = deletedPkg;
19626            } else {
19627                // We don't have a parsed package when it lives on an ejected
19628                // adopted storage device, so fake something together
19629                resolvedPkg = new PackageParser.Package(ps.name);
19630                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19631            }
19632            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19633                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19634            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19635            if (outInfo != null) {
19636                outInfo.dataRemoved = true;
19637            }
19638            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19639        }
19640
19641        int removedAppId = -1;
19642
19643        // writer
19644        synchronized (mPackages) {
19645            boolean installedStateChanged = false;
19646            if (deletedPs != null) {
19647                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19648                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19649                    clearDefaultBrowserIfNeeded(packageName);
19650                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19651                    removedAppId = mSettings.removePackageLPw(packageName);
19652                    if (outInfo != null) {
19653                        outInfo.removedAppId = removedAppId;
19654                    }
19655                    updatePermissionsLPw(deletedPs.name, null, 0);
19656                    if (deletedPs.sharedUser != null) {
19657                        // Remove permissions associated with package. Since runtime
19658                        // permissions are per user we have to kill the removed package
19659                        // or packages running under the shared user of the removed
19660                        // package if revoking the permissions requested only by the removed
19661                        // package is successful and this causes a change in gids.
19662                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19663                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19664                                    userId);
19665                            if (userIdToKill == UserHandle.USER_ALL
19666                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19667                                // If gids changed for this user, kill all affected packages.
19668                                mHandler.post(new Runnable() {
19669                                    @Override
19670                                    public void run() {
19671                                        // This has to happen with no lock held.
19672                                        killApplication(deletedPs.name, deletedPs.appId,
19673                                                KILL_APP_REASON_GIDS_CHANGED);
19674                                    }
19675                                });
19676                                break;
19677                            }
19678                        }
19679                    }
19680                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19681                }
19682                // make sure to preserve per-user disabled state if this removal was just
19683                // a downgrade of a system app to the factory package
19684                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19685                    if (DEBUG_REMOVE) {
19686                        Slog.d(TAG, "Propagating install state across downgrade");
19687                    }
19688                    for (int userId : allUserHandles) {
19689                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19690                        if (DEBUG_REMOVE) {
19691                            Slog.d(TAG, "    user " + userId + " => " + installed);
19692                        }
19693                        if (installed != ps.getInstalled(userId)) {
19694                            installedStateChanged = true;
19695                        }
19696                        ps.setInstalled(installed, userId);
19697                    }
19698                }
19699            }
19700            // can downgrade to reader
19701            if (writeSettings) {
19702                // Save settings now
19703                mSettings.writeLPr();
19704            }
19705            if (installedStateChanged) {
19706                mSettings.writeKernelMappingLPr(ps);
19707            }
19708        }
19709        if (removedAppId != -1) {
19710            // A user ID was deleted here. Go through all users and remove it
19711            // from KeyStore.
19712            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19713        }
19714    }
19715
19716    static boolean locationIsPrivileged(File path) {
19717        try {
19718            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19719                    .getCanonicalPath();
19720            return path.getCanonicalPath().startsWith(privilegedAppDir);
19721        } catch (IOException e) {
19722            Slog.e(TAG, "Unable to access code path " + path);
19723        }
19724        return false;
19725    }
19726
19727    /*
19728     * Tries to delete system package.
19729     */
19730    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19731            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19732            boolean writeSettings) {
19733        if (deletedPs.parentPackageName != null) {
19734            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19735            return false;
19736        }
19737
19738        final boolean applyUserRestrictions
19739                = (allUserHandles != null) && (outInfo.origUsers != null);
19740        final PackageSetting disabledPs;
19741        // Confirm if the system package has been updated
19742        // An updated system app can be deleted. This will also have to restore
19743        // the system pkg from system partition
19744        // reader
19745        synchronized (mPackages) {
19746            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19747        }
19748
19749        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19750                + " disabledPs=" + disabledPs);
19751
19752        if (disabledPs == null) {
19753            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19754            return false;
19755        } else if (DEBUG_REMOVE) {
19756            Slog.d(TAG, "Deleting system pkg from data partition");
19757        }
19758
19759        if (DEBUG_REMOVE) {
19760            if (applyUserRestrictions) {
19761                Slog.d(TAG, "Remembering install states:");
19762                for (int userId : allUserHandles) {
19763                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19764                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19765                }
19766            }
19767        }
19768
19769        // Delete the updated package
19770        outInfo.isRemovedPackageSystemUpdate = true;
19771        if (outInfo.removedChildPackages != null) {
19772            final int childCount = (deletedPs.childPackageNames != null)
19773                    ? deletedPs.childPackageNames.size() : 0;
19774            for (int i = 0; i < childCount; i++) {
19775                String childPackageName = deletedPs.childPackageNames.get(i);
19776                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19777                        .contains(childPackageName)) {
19778                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19779                            childPackageName);
19780                    if (childInfo != null) {
19781                        childInfo.isRemovedPackageSystemUpdate = true;
19782                    }
19783                }
19784            }
19785        }
19786
19787        if (disabledPs.versionCode < deletedPs.versionCode) {
19788            // Delete data for downgrades
19789            flags &= ~PackageManager.DELETE_KEEP_DATA;
19790        } else {
19791            // Preserve data by setting flag
19792            flags |= PackageManager.DELETE_KEEP_DATA;
19793        }
19794
19795        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19796                outInfo, writeSettings, disabledPs.pkg);
19797        if (!ret) {
19798            return false;
19799        }
19800
19801        // writer
19802        synchronized (mPackages) {
19803            // NOTE: The system package always needs to be enabled; even if it's for
19804            // a compressed stub. If we don't, installing the system package fails
19805            // during scan [scanning checks the disabled packages]. We will reverse
19806            // this later, after we've "installed" the stub.
19807            // Reinstate the old system package
19808            enableSystemPackageLPw(disabledPs.pkg);
19809            // Remove any native libraries from the upgraded package.
19810            removeNativeBinariesLI(deletedPs);
19811        }
19812
19813        // Install the system package
19814        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19815        try {
19816            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
19817                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19818        } catch (PackageManagerException e) {
19819            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19820                    + e.getMessage());
19821            return false;
19822        } finally {
19823            if (disabledPs.pkg.isStub) {
19824                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
19825            }
19826        }
19827        return true;
19828    }
19829
19830    /**
19831     * Installs a package that's already on the system partition.
19832     */
19833    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
19834            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19835            @Nullable PermissionsState origPermissionState, boolean writeSettings)
19836                    throws PackageManagerException {
19837        int parseFlags = mDefParseFlags
19838                | PackageParser.PARSE_MUST_BE_APK
19839                | PackageParser.PARSE_IS_SYSTEM
19840                | PackageParser.PARSE_IS_SYSTEM_DIR;
19841        if (isPrivileged || locationIsPrivileged(codePath)) {
19842            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19843        }
19844
19845        final PackageParser.Package newPkg =
19846                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
19847
19848        try {
19849            // update shared libraries for the newly re-installed system package
19850            updateSharedLibrariesLPr(newPkg, null);
19851        } catch (PackageManagerException e) {
19852            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19853        }
19854
19855        prepareAppDataAfterInstallLIF(newPkg);
19856
19857        // writer
19858        synchronized (mPackages) {
19859            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19860
19861            // Propagate the permissions state as we do not want to drop on the floor
19862            // runtime permissions. The update permissions method below will take
19863            // care of removing obsolete permissions and grant install permissions.
19864            if (origPermissionState != null) {
19865                ps.getPermissionsState().copyFrom(origPermissionState);
19866            }
19867            updatePermissionsLPw(newPkg.packageName, newPkg,
19868                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19869
19870            final boolean applyUserRestrictions
19871                    = (allUserHandles != null) && (origUserHandles != null);
19872            if (applyUserRestrictions) {
19873                boolean installedStateChanged = false;
19874                if (DEBUG_REMOVE) {
19875                    Slog.d(TAG, "Propagating install state across reinstall");
19876                }
19877                for (int userId : allUserHandles) {
19878                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19879                    if (DEBUG_REMOVE) {
19880                        Slog.d(TAG, "    user " + userId + " => " + installed);
19881                    }
19882                    if (installed != ps.getInstalled(userId)) {
19883                        installedStateChanged = true;
19884                    }
19885                    ps.setInstalled(installed, userId);
19886
19887                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19888                }
19889                // Regardless of writeSettings we need to ensure that this restriction
19890                // state propagation is persisted
19891                mSettings.writeAllUsersPackageRestrictionsLPr();
19892                if (installedStateChanged) {
19893                    mSettings.writeKernelMappingLPr(ps);
19894                }
19895            }
19896            // can downgrade to reader here
19897            if (writeSettings) {
19898                mSettings.writeLPr();
19899            }
19900        }
19901        return newPkg;
19902    }
19903
19904    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19905            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19906            PackageRemovedInfo outInfo, boolean writeSettings,
19907            PackageParser.Package replacingPackage) {
19908        synchronized (mPackages) {
19909            if (outInfo != null) {
19910                outInfo.uid = ps.appId;
19911            }
19912
19913            if (outInfo != null && outInfo.removedChildPackages != null) {
19914                final int childCount = (ps.childPackageNames != null)
19915                        ? ps.childPackageNames.size() : 0;
19916                for (int i = 0; i < childCount; i++) {
19917                    String childPackageName = ps.childPackageNames.get(i);
19918                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19919                    if (childPs == null) {
19920                        return false;
19921                    }
19922                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19923                            childPackageName);
19924                    if (childInfo != null) {
19925                        childInfo.uid = childPs.appId;
19926                    }
19927                }
19928            }
19929        }
19930
19931        // Delete package data from internal structures and also remove data if flag is set
19932        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19933
19934        // Delete the child packages data
19935        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19936        for (int i = 0; i < childCount; i++) {
19937            PackageSetting childPs;
19938            synchronized (mPackages) {
19939                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19940            }
19941            if (childPs != null) {
19942                PackageRemovedInfo childOutInfo = (outInfo != null
19943                        && outInfo.removedChildPackages != null)
19944                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19945                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19946                        && (replacingPackage != null
19947                        && !replacingPackage.hasChildPackage(childPs.name))
19948                        ? flags & ~DELETE_KEEP_DATA : flags;
19949                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19950                        deleteFlags, writeSettings);
19951            }
19952        }
19953
19954        // Delete application code and resources only for parent packages
19955        if (ps.parentPackageName == null) {
19956            if (deleteCodeAndResources && (outInfo != null)) {
19957                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19958                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19959                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19960            }
19961        }
19962
19963        return true;
19964    }
19965
19966    @Override
19967    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19968            int userId) {
19969        mContext.enforceCallingOrSelfPermission(
19970                android.Manifest.permission.DELETE_PACKAGES, null);
19971        synchronized (mPackages) {
19972            // Cannot block uninstall of static shared libs as they are
19973            // considered a part of the using app (emulating static linking).
19974            // Also static libs are installed always on internal storage.
19975            PackageParser.Package pkg = mPackages.get(packageName);
19976            if (pkg != null && pkg.staticSharedLibName != null) {
19977                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19978                        + " providing static shared library: " + pkg.staticSharedLibName);
19979                return false;
19980            }
19981            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19982            mSettings.writePackageRestrictionsLPr(userId);
19983        }
19984        return true;
19985    }
19986
19987    @Override
19988    public boolean getBlockUninstallForUser(String packageName, int userId) {
19989        synchronized (mPackages) {
19990            final PackageSetting ps = mSettings.mPackages.get(packageName);
19991            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19992                return false;
19993            }
19994            return mSettings.getBlockUninstallLPr(userId, packageName);
19995        }
19996    }
19997
19998    @Override
19999    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
20000        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
20001        synchronized (mPackages) {
20002            PackageSetting ps = mSettings.mPackages.get(packageName);
20003            if (ps == null) {
20004                Log.w(TAG, "Package doesn't exist: " + packageName);
20005                return false;
20006            }
20007            if (systemUserApp) {
20008                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20009            } else {
20010                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
20011            }
20012            mSettings.writeLPr();
20013        }
20014        return true;
20015    }
20016
20017    /*
20018     * This method handles package deletion in general
20019     */
20020    private boolean deletePackageLIF(String packageName, UserHandle user,
20021            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
20022            PackageRemovedInfo outInfo, boolean writeSettings,
20023            PackageParser.Package replacingPackage) {
20024        if (packageName == null) {
20025            Slog.w(TAG, "Attempt to delete null packageName.");
20026            return false;
20027        }
20028
20029        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
20030
20031        PackageSetting ps;
20032        synchronized (mPackages) {
20033            ps = mSettings.mPackages.get(packageName);
20034            if (ps == null) {
20035                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20036                return false;
20037            }
20038
20039            if (ps.parentPackageName != null && (!isSystemApp(ps)
20040                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
20041                if (DEBUG_REMOVE) {
20042                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
20043                            + ((user == null) ? UserHandle.USER_ALL : user));
20044                }
20045                final int removedUserId = (user != null) ? user.getIdentifier()
20046                        : UserHandle.USER_ALL;
20047                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
20048                    return false;
20049                }
20050                markPackageUninstalledForUserLPw(ps, user);
20051                scheduleWritePackageRestrictionsLocked(user);
20052                return true;
20053            }
20054        }
20055
20056        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
20057                && user.getIdentifier() != UserHandle.USER_ALL)) {
20058            // The caller is asking that the package only be deleted for a single
20059            // user.  To do this, we just mark its uninstalled state and delete
20060            // its data. If this is a system app, we only allow this to happen if
20061            // they have set the special DELETE_SYSTEM_APP which requests different
20062            // semantics than normal for uninstalling system apps.
20063            markPackageUninstalledForUserLPw(ps, user);
20064
20065            if (!isSystemApp(ps)) {
20066                // Do not uninstall the APK if an app should be cached
20067                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
20068                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
20069                    // Other user still have this package installed, so all
20070                    // we need to do is clear this user's data and save that
20071                    // it is uninstalled.
20072                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
20073                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20074                        return false;
20075                    }
20076                    scheduleWritePackageRestrictionsLocked(user);
20077                    return true;
20078                } else {
20079                    // We need to set it back to 'installed' so the uninstall
20080                    // broadcasts will be sent correctly.
20081                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
20082                    ps.setInstalled(true, user.getIdentifier());
20083                    mSettings.writeKernelMappingLPr(ps);
20084                }
20085            } else {
20086                // This is a system app, so we assume that the
20087                // other users still have this package installed, so all
20088                // we need to do is clear this user's data and save that
20089                // it is uninstalled.
20090                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
20091                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
20092                    return false;
20093                }
20094                scheduleWritePackageRestrictionsLocked(user);
20095                return true;
20096            }
20097        }
20098
20099        // If we are deleting a composite package for all users, keep track
20100        // of result for each child.
20101        if (ps.childPackageNames != null && outInfo != null) {
20102            synchronized (mPackages) {
20103                final int childCount = ps.childPackageNames.size();
20104                outInfo.removedChildPackages = new ArrayMap<>(childCount);
20105                for (int i = 0; i < childCount; i++) {
20106                    String childPackageName = ps.childPackageNames.get(i);
20107                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
20108                    childInfo.removedPackage = childPackageName;
20109                    childInfo.installerPackageName = ps.installerPackageName;
20110                    outInfo.removedChildPackages.put(childPackageName, childInfo);
20111                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20112                    if (childPs != null) {
20113                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
20114                    }
20115                }
20116            }
20117        }
20118
20119        boolean ret = false;
20120        if (isSystemApp(ps)) {
20121            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
20122            // When an updated system application is deleted we delete the existing resources
20123            // as well and fall back to existing code in system partition
20124            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
20125        } else {
20126            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
20127            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
20128                    outInfo, writeSettings, replacingPackage);
20129        }
20130
20131        // Take a note whether we deleted the package for all users
20132        if (outInfo != null) {
20133            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
20134            if (outInfo.removedChildPackages != null) {
20135                synchronized (mPackages) {
20136                    final int childCount = outInfo.removedChildPackages.size();
20137                    for (int i = 0; i < childCount; i++) {
20138                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
20139                        if (childInfo != null) {
20140                            childInfo.removedForAllUsers = mPackages.get(
20141                                    childInfo.removedPackage) == null;
20142                        }
20143                    }
20144                }
20145            }
20146            // If we uninstalled an update to a system app there may be some
20147            // child packages that appeared as they are declared in the system
20148            // app but were not declared in the update.
20149            if (isSystemApp(ps)) {
20150                synchronized (mPackages) {
20151                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20152                    final int childCount = (updatedPs.childPackageNames != null)
20153                            ? updatedPs.childPackageNames.size() : 0;
20154                    for (int i = 0; i < childCount; i++) {
20155                        String childPackageName = updatedPs.childPackageNames.get(i);
20156                        if (outInfo.removedChildPackages == null
20157                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20158                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20159                            if (childPs == null) {
20160                                continue;
20161                            }
20162                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20163                            installRes.name = childPackageName;
20164                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20165                            installRes.pkg = mPackages.get(childPackageName);
20166                            installRes.uid = childPs.pkg.applicationInfo.uid;
20167                            if (outInfo.appearedChildPackages == null) {
20168                                outInfo.appearedChildPackages = new ArrayMap<>();
20169                            }
20170                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20171                        }
20172                    }
20173                }
20174            }
20175        }
20176
20177        return ret;
20178    }
20179
20180    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20181        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20182                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20183        for (int nextUserId : userIds) {
20184            if (DEBUG_REMOVE) {
20185                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20186            }
20187            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20188                    false /*installed*/,
20189                    true /*stopped*/,
20190                    true /*notLaunched*/,
20191                    false /*hidden*/,
20192                    false /*suspended*/,
20193                    false /*instantApp*/,
20194                    false /*virtualPreload*/,
20195                    null /*lastDisableAppCaller*/,
20196                    null /*enabledComponents*/,
20197                    null /*disabledComponents*/,
20198                    ps.readUserState(nextUserId).domainVerificationStatus,
20199                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20200        }
20201        mSettings.writeKernelMappingLPr(ps);
20202    }
20203
20204    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20205            PackageRemovedInfo outInfo) {
20206        final PackageParser.Package pkg;
20207        synchronized (mPackages) {
20208            pkg = mPackages.get(ps.name);
20209        }
20210
20211        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20212                : new int[] {userId};
20213        for (int nextUserId : userIds) {
20214            if (DEBUG_REMOVE) {
20215                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20216                        + nextUserId);
20217            }
20218
20219            destroyAppDataLIF(pkg, userId,
20220                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20221            destroyAppProfilesLIF(pkg, userId);
20222            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20223            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20224            schedulePackageCleaning(ps.name, nextUserId, false);
20225            synchronized (mPackages) {
20226                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20227                    scheduleWritePackageRestrictionsLocked(nextUserId);
20228                }
20229                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20230            }
20231        }
20232
20233        if (outInfo != null) {
20234            outInfo.removedPackage = ps.name;
20235            outInfo.installerPackageName = ps.installerPackageName;
20236            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20237            outInfo.removedAppId = ps.appId;
20238            outInfo.removedUsers = userIds;
20239            outInfo.broadcastUsers = userIds;
20240        }
20241
20242        return true;
20243    }
20244
20245    private final class ClearStorageConnection implements ServiceConnection {
20246        IMediaContainerService mContainerService;
20247
20248        @Override
20249        public void onServiceConnected(ComponentName name, IBinder service) {
20250            synchronized (this) {
20251                mContainerService = IMediaContainerService.Stub
20252                        .asInterface(Binder.allowBlocking(service));
20253                notifyAll();
20254            }
20255        }
20256
20257        @Override
20258        public void onServiceDisconnected(ComponentName name) {
20259        }
20260    }
20261
20262    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20263        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20264
20265        final boolean mounted;
20266        if (Environment.isExternalStorageEmulated()) {
20267            mounted = true;
20268        } else {
20269            final String status = Environment.getExternalStorageState();
20270
20271            mounted = status.equals(Environment.MEDIA_MOUNTED)
20272                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20273        }
20274
20275        if (!mounted) {
20276            return;
20277        }
20278
20279        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20280        int[] users;
20281        if (userId == UserHandle.USER_ALL) {
20282            users = sUserManager.getUserIds();
20283        } else {
20284            users = new int[] { userId };
20285        }
20286        final ClearStorageConnection conn = new ClearStorageConnection();
20287        if (mContext.bindServiceAsUser(
20288                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20289            try {
20290                for (int curUser : users) {
20291                    long timeout = SystemClock.uptimeMillis() + 5000;
20292                    synchronized (conn) {
20293                        long now;
20294                        while (conn.mContainerService == null &&
20295                                (now = SystemClock.uptimeMillis()) < timeout) {
20296                            try {
20297                                conn.wait(timeout - now);
20298                            } catch (InterruptedException e) {
20299                            }
20300                        }
20301                    }
20302                    if (conn.mContainerService == null) {
20303                        return;
20304                    }
20305
20306                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20307                    clearDirectory(conn.mContainerService,
20308                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20309                    if (allData) {
20310                        clearDirectory(conn.mContainerService,
20311                                userEnv.buildExternalStorageAppDataDirs(packageName));
20312                        clearDirectory(conn.mContainerService,
20313                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20314                    }
20315                }
20316            } finally {
20317                mContext.unbindService(conn);
20318            }
20319        }
20320    }
20321
20322    @Override
20323    public void clearApplicationProfileData(String packageName) {
20324        enforceSystemOrRoot("Only the system can clear all profile data");
20325
20326        final PackageParser.Package pkg;
20327        synchronized (mPackages) {
20328            pkg = mPackages.get(packageName);
20329        }
20330
20331        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20332            synchronized (mInstallLock) {
20333                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20334            }
20335        }
20336    }
20337
20338    @Override
20339    public void clearApplicationUserData(final String packageName,
20340            final IPackageDataObserver observer, final int userId) {
20341        mContext.enforceCallingOrSelfPermission(
20342                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20343
20344        final int callingUid = Binder.getCallingUid();
20345        enforceCrossUserPermission(callingUid, userId,
20346                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20347
20348        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20349        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
20350        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20351            throw new SecurityException("Cannot clear data for a protected package: "
20352                    + packageName);
20353        }
20354        // Queue up an async operation since the package deletion may take a little while.
20355        mHandler.post(new Runnable() {
20356            public void run() {
20357                mHandler.removeCallbacks(this);
20358                final boolean succeeded;
20359                if (!filterApp) {
20360                    try (PackageFreezer freezer = freezePackage(packageName,
20361                            "clearApplicationUserData")) {
20362                        synchronized (mInstallLock) {
20363                            succeeded = clearApplicationUserDataLIF(packageName, userId);
20364                        }
20365                        clearExternalStorageDataSync(packageName, userId, true);
20366                        synchronized (mPackages) {
20367                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20368                                    packageName, userId);
20369                        }
20370                    }
20371                    if (succeeded) {
20372                        // invoke DeviceStorageMonitor's update method to clear any notifications
20373                        DeviceStorageMonitorInternal dsm = LocalServices
20374                                .getService(DeviceStorageMonitorInternal.class);
20375                        if (dsm != null) {
20376                            dsm.checkMemory();
20377                        }
20378                    }
20379                } else {
20380                    succeeded = false;
20381                }
20382                if (observer != null) {
20383                    try {
20384                        observer.onRemoveCompleted(packageName, succeeded);
20385                    } catch (RemoteException e) {
20386                        Log.i(TAG, "Observer no longer exists.");
20387                    }
20388                } //end if observer
20389            } //end run
20390        });
20391    }
20392
20393    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20394        if (packageName == null) {
20395            Slog.w(TAG, "Attempt to delete null packageName.");
20396            return false;
20397        }
20398
20399        // Try finding details about the requested package
20400        PackageParser.Package pkg;
20401        synchronized (mPackages) {
20402            pkg = mPackages.get(packageName);
20403            if (pkg == null) {
20404                final PackageSetting ps = mSettings.mPackages.get(packageName);
20405                if (ps != null) {
20406                    pkg = ps.pkg;
20407                }
20408            }
20409
20410            if (pkg == null) {
20411                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20412                return false;
20413            }
20414
20415            PackageSetting ps = (PackageSetting) pkg.mExtras;
20416            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20417        }
20418
20419        clearAppDataLIF(pkg, userId,
20420                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20421
20422        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20423        removeKeystoreDataIfNeeded(userId, appId);
20424
20425        UserManagerInternal umInternal = getUserManagerInternal();
20426        final int flags;
20427        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20428            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20429        } else if (umInternal.isUserRunning(userId)) {
20430            flags = StorageManager.FLAG_STORAGE_DE;
20431        } else {
20432            flags = 0;
20433        }
20434        prepareAppDataContentsLIF(pkg, userId, flags);
20435
20436        return true;
20437    }
20438
20439    /**
20440     * Reverts user permission state changes (permissions and flags) in
20441     * all packages for a given user.
20442     *
20443     * @param userId The device user for which to do a reset.
20444     */
20445    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20446        final int packageCount = mPackages.size();
20447        for (int i = 0; i < packageCount; i++) {
20448            PackageParser.Package pkg = mPackages.valueAt(i);
20449            PackageSetting ps = (PackageSetting) pkg.mExtras;
20450            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20451        }
20452    }
20453
20454    private void resetNetworkPolicies(int userId) {
20455        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20456    }
20457
20458    /**
20459     * Reverts user permission state changes (permissions and flags).
20460     *
20461     * @param ps The package for which to reset.
20462     * @param userId The device user for which to do a reset.
20463     */
20464    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20465            final PackageSetting ps, final int userId) {
20466        if (ps.pkg == null) {
20467            return;
20468        }
20469
20470        // These are flags that can change base on user actions.
20471        final int userSettableMask = FLAG_PERMISSION_USER_SET
20472                | FLAG_PERMISSION_USER_FIXED
20473                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20474                | FLAG_PERMISSION_REVIEW_REQUIRED;
20475
20476        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20477                | FLAG_PERMISSION_POLICY_FIXED;
20478
20479        boolean writeInstallPermissions = false;
20480        boolean writeRuntimePermissions = false;
20481
20482        final int permissionCount = ps.pkg.requestedPermissions.size();
20483        for (int i = 0; i < permissionCount; i++) {
20484            String permission = ps.pkg.requestedPermissions.get(i);
20485
20486            BasePermission bp = mSettings.mPermissions.get(permission);
20487            if (bp == null) {
20488                continue;
20489            }
20490
20491            // If shared user we just reset the state to which only this app contributed.
20492            if (ps.sharedUser != null) {
20493                boolean used = false;
20494                final int packageCount = ps.sharedUser.packages.size();
20495                for (int j = 0; j < packageCount; j++) {
20496                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20497                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20498                            && pkg.pkg.requestedPermissions.contains(permission)) {
20499                        used = true;
20500                        break;
20501                    }
20502                }
20503                if (used) {
20504                    continue;
20505                }
20506            }
20507
20508            PermissionsState permissionsState = ps.getPermissionsState();
20509
20510            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20511
20512            // Always clear the user settable flags.
20513            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20514                    bp.name) != null;
20515            // If permission review is enabled and this is a legacy app, mark the
20516            // permission as requiring a review as this is the initial state.
20517            int flags = 0;
20518            if (mPermissionReviewRequired
20519                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20520                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20521            }
20522            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20523                if (hasInstallState) {
20524                    writeInstallPermissions = true;
20525                } else {
20526                    writeRuntimePermissions = true;
20527                }
20528            }
20529
20530            // Below is only runtime permission handling.
20531            if (!bp.isRuntime()) {
20532                continue;
20533            }
20534
20535            // Never clobber system or policy.
20536            if ((oldFlags & policyOrSystemFlags) != 0) {
20537                continue;
20538            }
20539
20540            // If this permission was granted by default, make sure it is.
20541            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20542                if (permissionsState.grantRuntimePermission(bp, userId)
20543                        != PERMISSION_OPERATION_FAILURE) {
20544                    writeRuntimePermissions = true;
20545                }
20546            // If permission review is enabled the permissions for a legacy apps
20547            // are represented as constantly granted runtime ones, so don't revoke.
20548            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20549                // Otherwise, reset the permission.
20550                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20551                switch (revokeResult) {
20552                    case PERMISSION_OPERATION_SUCCESS:
20553                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20554                        writeRuntimePermissions = true;
20555                        final int appId = ps.appId;
20556                        mHandler.post(new Runnable() {
20557                            @Override
20558                            public void run() {
20559                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20560                            }
20561                        });
20562                    } break;
20563                }
20564            }
20565        }
20566
20567        // Synchronously write as we are taking permissions away.
20568        if (writeRuntimePermissions) {
20569            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20570        }
20571
20572        // Synchronously write as we are taking permissions away.
20573        if (writeInstallPermissions) {
20574            mSettings.writeLPr();
20575        }
20576    }
20577
20578    /**
20579     * Remove entries from the keystore daemon. Will only remove it if the
20580     * {@code appId} is valid.
20581     */
20582    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20583        if (appId < 0) {
20584            return;
20585        }
20586
20587        final KeyStore keyStore = KeyStore.getInstance();
20588        if (keyStore != null) {
20589            if (userId == UserHandle.USER_ALL) {
20590                for (final int individual : sUserManager.getUserIds()) {
20591                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20592                }
20593            } else {
20594                keyStore.clearUid(UserHandle.getUid(userId, appId));
20595            }
20596        } else {
20597            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20598        }
20599    }
20600
20601    @Override
20602    public void deleteApplicationCacheFiles(final String packageName,
20603            final IPackageDataObserver observer) {
20604        final int userId = UserHandle.getCallingUserId();
20605        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20606    }
20607
20608    @Override
20609    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20610            final IPackageDataObserver observer) {
20611        final int callingUid = Binder.getCallingUid();
20612        mContext.enforceCallingOrSelfPermission(
20613                android.Manifest.permission.DELETE_CACHE_FILES, null);
20614        enforceCrossUserPermission(callingUid, userId,
20615                /* requireFullPermission= */ true, /* checkShell= */ false,
20616                "delete application cache files");
20617        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20618                android.Manifest.permission.ACCESS_INSTANT_APPS);
20619
20620        final PackageParser.Package pkg;
20621        synchronized (mPackages) {
20622            pkg = mPackages.get(packageName);
20623        }
20624
20625        // Queue up an async operation since the package deletion may take a little while.
20626        mHandler.post(new Runnable() {
20627            public void run() {
20628                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20629                boolean doClearData = true;
20630                if (ps != null) {
20631                    final boolean targetIsInstantApp =
20632                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20633                    doClearData = !targetIsInstantApp
20634                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20635                }
20636                if (doClearData) {
20637                    synchronized (mInstallLock) {
20638                        final int flags = StorageManager.FLAG_STORAGE_DE
20639                                | StorageManager.FLAG_STORAGE_CE;
20640                        // We're only clearing cache files, so we don't care if the
20641                        // app is unfrozen and still able to run
20642                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20643                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20644                    }
20645                    clearExternalStorageDataSync(packageName, userId, false);
20646                }
20647                if (observer != null) {
20648                    try {
20649                        observer.onRemoveCompleted(packageName, true);
20650                    } catch (RemoteException e) {
20651                        Log.i(TAG, "Observer no longer exists.");
20652                    }
20653                }
20654            }
20655        });
20656    }
20657
20658    @Override
20659    public void getPackageSizeInfo(final String packageName, int userHandle,
20660            final IPackageStatsObserver observer) {
20661        throw new UnsupportedOperationException(
20662                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20663    }
20664
20665    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20666        final PackageSetting ps;
20667        synchronized (mPackages) {
20668            ps = mSettings.mPackages.get(packageName);
20669            if (ps == null) {
20670                Slog.w(TAG, "Failed to find settings for " + packageName);
20671                return false;
20672            }
20673        }
20674
20675        final String[] packageNames = { packageName };
20676        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20677        final String[] codePaths = { ps.codePathString };
20678
20679        try {
20680            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20681                    ps.appId, ceDataInodes, codePaths, stats);
20682
20683            // For now, ignore code size of packages on system partition
20684            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20685                stats.codeSize = 0;
20686            }
20687
20688            // External clients expect these to be tracked separately
20689            stats.dataSize -= stats.cacheSize;
20690
20691        } catch (InstallerException e) {
20692            Slog.w(TAG, String.valueOf(e));
20693            return false;
20694        }
20695
20696        return true;
20697    }
20698
20699    private int getUidTargetSdkVersionLockedLPr(int uid) {
20700        Object obj = mSettings.getUserIdLPr(uid);
20701        if (obj instanceof SharedUserSetting) {
20702            final SharedUserSetting sus = (SharedUserSetting) obj;
20703            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20704            final Iterator<PackageSetting> it = sus.packages.iterator();
20705            while (it.hasNext()) {
20706                final PackageSetting ps = it.next();
20707                if (ps.pkg != null) {
20708                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20709                    if (v < vers) vers = v;
20710                }
20711            }
20712            return vers;
20713        } else if (obj instanceof PackageSetting) {
20714            final PackageSetting ps = (PackageSetting) obj;
20715            if (ps.pkg != null) {
20716                return ps.pkg.applicationInfo.targetSdkVersion;
20717            }
20718        }
20719        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20720    }
20721
20722    @Override
20723    public void addPreferredActivity(IntentFilter filter, int match,
20724            ComponentName[] set, ComponentName activity, int userId) {
20725        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20726                "Adding preferred");
20727    }
20728
20729    private void addPreferredActivityInternal(IntentFilter filter, int match,
20730            ComponentName[] set, ComponentName activity, boolean always, int userId,
20731            String opname) {
20732        // writer
20733        int callingUid = Binder.getCallingUid();
20734        enforceCrossUserPermission(callingUid, userId,
20735                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20736        if (filter.countActions() == 0) {
20737            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20738            return;
20739        }
20740        synchronized (mPackages) {
20741            if (mContext.checkCallingOrSelfPermission(
20742                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20743                    != PackageManager.PERMISSION_GRANTED) {
20744                if (getUidTargetSdkVersionLockedLPr(callingUid)
20745                        < Build.VERSION_CODES.FROYO) {
20746                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20747                            + callingUid);
20748                    return;
20749                }
20750                mContext.enforceCallingOrSelfPermission(
20751                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20752            }
20753
20754            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20755            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20756                    + userId + ":");
20757            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20758            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20759            scheduleWritePackageRestrictionsLocked(userId);
20760            postPreferredActivityChangedBroadcast(userId);
20761        }
20762    }
20763
20764    private void postPreferredActivityChangedBroadcast(int userId) {
20765        mHandler.post(() -> {
20766            final IActivityManager am = ActivityManager.getService();
20767            if (am == null) {
20768                return;
20769            }
20770
20771            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20772            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20773            try {
20774                am.broadcastIntent(null, intent, null, null,
20775                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20776                        null, false, false, userId);
20777            } catch (RemoteException e) {
20778            }
20779        });
20780    }
20781
20782    @Override
20783    public void replacePreferredActivity(IntentFilter filter, int match,
20784            ComponentName[] set, ComponentName activity, int userId) {
20785        if (filter.countActions() != 1) {
20786            throw new IllegalArgumentException(
20787                    "replacePreferredActivity expects filter to have only 1 action.");
20788        }
20789        if (filter.countDataAuthorities() != 0
20790                || filter.countDataPaths() != 0
20791                || filter.countDataSchemes() > 1
20792                || filter.countDataTypes() != 0) {
20793            throw new IllegalArgumentException(
20794                    "replacePreferredActivity expects filter to have no data authorities, " +
20795                    "paths, or types; and at most one scheme.");
20796        }
20797
20798        final int callingUid = Binder.getCallingUid();
20799        enforceCrossUserPermission(callingUid, userId,
20800                true /* requireFullPermission */, false /* checkShell */,
20801                "replace preferred activity");
20802        synchronized (mPackages) {
20803            if (mContext.checkCallingOrSelfPermission(
20804                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20805                    != PackageManager.PERMISSION_GRANTED) {
20806                if (getUidTargetSdkVersionLockedLPr(callingUid)
20807                        < Build.VERSION_CODES.FROYO) {
20808                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20809                            + Binder.getCallingUid());
20810                    return;
20811                }
20812                mContext.enforceCallingOrSelfPermission(
20813                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20814            }
20815
20816            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20817            if (pir != null) {
20818                // Get all of the existing entries that exactly match this filter.
20819                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20820                if (existing != null && existing.size() == 1) {
20821                    PreferredActivity cur = existing.get(0);
20822                    if (DEBUG_PREFERRED) {
20823                        Slog.i(TAG, "Checking replace of preferred:");
20824                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20825                        if (!cur.mPref.mAlways) {
20826                            Slog.i(TAG, "  -- CUR; not mAlways!");
20827                        } else {
20828                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20829                            Slog.i(TAG, "  -- CUR: mSet="
20830                                    + Arrays.toString(cur.mPref.mSetComponents));
20831                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20832                            Slog.i(TAG, "  -- NEW: mMatch="
20833                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20834                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20835                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20836                        }
20837                    }
20838                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20839                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20840                            && cur.mPref.sameSet(set)) {
20841                        // Setting the preferred activity to what it happens to be already
20842                        if (DEBUG_PREFERRED) {
20843                            Slog.i(TAG, "Replacing with same preferred activity "
20844                                    + cur.mPref.mShortComponent + " for user "
20845                                    + userId + ":");
20846                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20847                        }
20848                        return;
20849                    }
20850                }
20851
20852                if (existing != null) {
20853                    if (DEBUG_PREFERRED) {
20854                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20855                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20856                    }
20857                    for (int i = 0; i < existing.size(); i++) {
20858                        PreferredActivity pa = existing.get(i);
20859                        if (DEBUG_PREFERRED) {
20860                            Slog.i(TAG, "Removing existing preferred activity "
20861                                    + pa.mPref.mComponent + ":");
20862                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20863                        }
20864                        pir.removeFilter(pa);
20865                    }
20866                }
20867            }
20868            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20869                    "Replacing preferred");
20870        }
20871    }
20872
20873    @Override
20874    public void clearPackagePreferredActivities(String packageName) {
20875        final int callingUid = Binder.getCallingUid();
20876        if (getInstantAppPackageName(callingUid) != null) {
20877            return;
20878        }
20879        // writer
20880        synchronized (mPackages) {
20881            PackageParser.Package pkg = mPackages.get(packageName);
20882            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20883                if (mContext.checkCallingOrSelfPermission(
20884                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20885                        != PackageManager.PERMISSION_GRANTED) {
20886                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20887                            < Build.VERSION_CODES.FROYO) {
20888                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20889                                + callingUid);
20890                        return;
20891                    }
20892                    mContext.enforceCallingOrSelfPermission(
20893                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20894                }
20895            }
20896            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20897            if (ps != null
20898                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20899                return;
20900            }
20901            int user = UserHandle.getCallingUserId();
20902            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20903                scheduleWritePackageRestrictionsLocked(user);
20904            }
20905        }
20906    }
20907
20908    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20909    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20910        ArrayList<PreferredActivity> removed = null;
20911        boolean changed = false;
20912        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20913            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20914            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20915            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20916                continue;
20917            }
20918            Iterator<PreferredActivity> it = pir.filterIterator();
20919            while (it.hasNext()) {
20920                PreferredActivity pa = it.next();
20921                // Mark entry for removal only if it matches the package name
20922                // and the entry is of type "always".
20923                if (packageName == null ||
20924                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20925                                && pa.mPref.mAlways)) {
20926                    if (removed == null) {
20927                        removed = new ArrayList<PreferredActivity>();
20928                    }
20929                    removed.add(pa);
20930                }
20931            }
20932            if (removed != null) {
20933                for (int j=0; j<removed.size(); j++) {
20934                    PreferredActivity pa = removed.get(j);
20935                    pir.removeFilter(pa);
20936                }
20937                changed = true;
20938            }
20939        }
20940        if (changed) {
20941            postPreferredActivityChangedBroadcast(userId);
20942        }
20943        return changed;
20944    }
20945
20946    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20947    private void clearIntentFilterVerificationsLPw(int userId) {
20948        final int packageCount = mPackages.size();
20949        for (int i = 0; i < packageCount; i++) {
20950            PackageParser.Package pkg = mPackages.valueAt(i);
20951            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20952        }
20953    }
20954
20955    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20956    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20957        if (userId == UserHandle.USER_ALL) {
20958            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20959                    sUserManager.getUserIds())) {
20960                for (int oneUserId : sUserManager.getUserIds()) {
20961                    scheduleWritePackageRestrictionsLocked(oneUserId);
20962                }
20963            }
20964        } else {
20965            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20966                scheduleWritePackageRestrictionsLocked(userId);
20967            }
20968        }
20969    }
20970
20971    /** Clears state for all users, and touches intent filter verification policy */
20972    void clearDefaultBrowserIfNeeded(String packageName) {
20973        for (int oneUserId : sUserManager.getUserIds()) {
20974            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20975        }
20976    }
20977
20978    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20979        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20980        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20981            if (packageName.equals(defaultBrowserPackageName)) {
20982                setDefaultBrowserPackageName(null, userId);
20983            }
20984        }
20985    }
20986
20987    @Override
20988    public void resetApplicationPreferences(int userId) {
20989        mContext.enforceCallingOrSelfPermission(
20990                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20991        final long identity = Binder.clearCallingIdentity();
20992        // writer
20993        try {
20994            synchronized (mPackages) {
20995                clearPackagePreferredActivitiesLPw(null, userId);
20996                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20997                // TODO: We have to reset the default SMS and Phone. This requires
20998                // significant refactoring to keep all default apps in the package
20999                // manager (cleaner but more work) or have the services provide
21000                // callbacks to the package manager to request a default app reset.
21001                applyFactoryDefaultBrowserLPw(userId);
21002                clearIntentFilterVerificationsLPw(userId);
21003                primeDomainVerificationsLPw(userId);
21004                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
21005                scheduleWritePackageRestrictionsLocked(userId);
21006            }
21007            resetNetworkPolicies(userId);
21008        } finally {
21009            Binder.restoreCallingIdentity(identity);
21010        }
21011    }
21012
21013    @Override
21014    public int getPreferredActivities(List<IntentFilter> outFilters,
21015            List<ComponentName> outActivities, String packageName) {
21016        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21017            return 0;
21018        }
21019        int num = 0;
21020        final int userId = UserHandle.getCallingUserId();
21021        // reader
21022        synchronized (mPackages) {
21023            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
21024            if (pir != null) {
21025                final Iterator<PreferredActivity> it = pir.filterIterator();
21026                while (it.hasNext()) {
21027                    final PreferredActivity pa = it.next();
21028                    if (packageName == null
21029                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
21030                                    && pa.mPref.mAlways)) {
21031                        if (outFilters != null) {
21032                            outFilters.add(new IntentFilter(pa));
21033                        }
21034                        if (outActivities != null) {
21035                            outActivities.add(pa.mPref.mComponent);
21036                        }
21037                    }
21038                }
21039            }
21040        }
21041
21042        return num;
21043    }
21044
21045    @Override
21046    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
21047            int userId) {
21048        int callingUid = Binder.getCallingUid();
21049        if (callingUid != Process.SYSTEM_UID) {
21050            throw new SecurityException(
21051                    "addPersistentPreferredActivity can only be run by the system");
21052        }
21053        if (filter.countActions() == 0) {
21054            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
21055            return;
21056        }
21057        synchronized (mPackages) {
21058            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
21059                    ":");
21060            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
21061            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
21062                    new PersistentPreferredActivity(filter, activity));
21063            scheduleWritePackageRestrictionsLocked(userId);
21064            postPreferredActivityChangedBroadcast(userId);
21065        }
21066    }
21067
21068    @Override
21069    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
21070        int callingUid = Binder.getCallingUid();
21071        if (callingUid != Process.SYSTEM_UID) {
21072            throw new SecurityException(
21073                    "clearPackagePersistentPreferredActivities can only be run by the system");
21074        }
21075        ArrayList<PersistentPreferredActivity> removed = null;
21076        boolean changed = false;
21077        synchronized (mPackages) {
21078            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
21079                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
21080                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
21081                        .valueAt(i);
21082                if (userId != thisUserId) {
21083                    continue;
21084                }
21085                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
21086                while (it.hasNext()) {
21087                    PersistentPreferredActivity ppa = it.next();
21088                    // Mark entry for removal only if it matches the package name.
21089                    if (ppa.mComponent.getPackageName().equals(packageName)) {
21090                        if (removed == null) {
21091                            removed = new ArrayList<PersistentPreferredActivity>();
21092                        }
21093                        removed.add(ppa);
21094                    }
21095                }
21096                if (removed != null) {
21097                    for (int j=0; j<removed.size(); j++) {
21098                        PersistentPreferredActivity ppa = removed.get(j);
21099                        ppir.removeFilter(ppa);
21100                    }
21101                    changed = true;
21102                }
21103            }
21104
21105            if (changed) {
21106                scheduleWritePackageRestrictionsLocked(userId);
21107                postPreferredActivityChangedBroadcast(userId);
21108            }
21109        }
21110    }
21111
21112    /**
21113     * Common machinery for picking apart a restored XML blob and passing
21114     * it to a caller-supplied functor to be applied to the running system.
21115     */
21116    private void restoreFromXml(XmlPullParser parser, int userId,
21117            String expectedStartTag, BlobXmlRestorer functor)
21118            throws IOException, XmlPullParserException {
21119        int type;
21120        while ((type = parser.next()) != XmlPullParser.START_TAG
21121                && type != XmlPullParser.END_DOCUMENT) {
21122        }
21123        if (type != XmlPullParser.START_TAG) {
21124            // oops didn't find a start tag?!
21125            if (DEBUG_BACKUP) {
21126                Slog.e(TAG, "Didn't find start tag during restore");
21127            }
21128            return;
21129        }
21130Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
21131        // this is supposed to be TAG_PREFERRED_BACKUP
21132        if (!expectedStartTag.equals(parser.getName())) {
21133            if (DEBUG_BACKUP) {
21134                Slog.e(TAG, "Found unexpected tag " + parser.getName());
21135            }
21136            return;
21137        }
21138
21139        // skip interfering stuff, then we're aligned with the backing implementation
21140        while ((type = parser.next()) == XmlPullParser.TEXT) { }
21141Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
21142        functor.apply(parser, userId);
21143    }
21144
21145    private interface BlobXmlRestorer {
21146        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
21147    }
21148
21149    /**
21150     * Non-Binder method, support for the backup/restore mechanism: write the
21151     * full set of preferred activities in its canonical XML format.  Returns the
21152     * XML output as a byte array, or null if there is none.
21153     */
21154    @Override
21155    public byte[] getPreferredActivityBackup(int userId) {
21156        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21157            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21158        }
21159
21160        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21161        try {
21162            final XmlSerializer serializer = new FastXmlSerializer();
21163            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21164            serializer.startDocument(null, true);
21165            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21166
21167            synchronized (mPackages) {
21168                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21169            }
21170
21171            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21172            serializer.endDocument();
21173            serializer.flush();
21174        } catch (Exception e) {
21175            if (DEBUG_BACKUP) {
21176                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21177            }
21178            return null;
21179        }
21180
21181        return dataStream.toByteArray();
21182    }
21183
21184    @Override
21185    public void restorePreferredActivities(byte[] backup, int userId) {
21186        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21187            throw new SecurityException("Only the system may call restorePreferredActivities()");
21188        }
21189
21190        try {
21191            final XmlPullParser parser = Xml.newPullParser();
21192            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21193            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21194                    new BlobXmlRestorer() {
21195                        @Override
21196                        public void apply(XmlPullParser parser, int userId)
21197                                throws XmlPullParserException, IOException {
21198                            synchronized (mPackages) {
21199                                mSettings.readPreferredActivitiesLPw(parser, userId);
21200                            }
21201                        }
21202                    } );
21203        } catch (Exception e) {
21204            if (DEBUG_BACKUP) {
21205                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21206            }
21207        }
21208    }
21209
21210    /**
21211     * Non-Binder method, support for the backup/restore mechanism: write the
21212     * default browser (etc) settings in its canonical XML format.  Returns the default
21213     * browser XML representation as a byte array, or null if there is none.
21214     */
21215    @Override
21216    public byte[] getDefaultAppsBackup(int userId) {
21217        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21218            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21219        }
21220
21221        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21222        try {
21223            final XmlSerializer serializer = new FastXmlSerializer();
21224            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21225            serializer.startDocument(null, true);
21226            serializer.startTag(null, TAG_DEFAULT_APPS);
21227
21228            synchronized (mPackages) {
21229                mSettings.writeDefaultAppsLPr(serializer, userId);
21230            }
21231
21232            serializer.endTag(null, TAG_DEFAULT_APPS);
21233            serializer.endDocument();
21234            serializer.flush();
21235        } catch (Exception e) {
21236            if (DEBUG_BACKUP) {
21237                Slog.e(TAG, "Unable to write default apps for backup", e);
21238            }
21239            return null;
21240        }
21241
21242        return dataStream.toByteArray();
21243    }
21244
21245    @Override
21246    public void restoreDefaultApps(byte[] backup, int userId) {
21247        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21248            throw new SecurityException("Only the system may call restoreDefaultApps()");
21249        }
21250
21251        try {
21252            final XmlPullParser parser = Xml.newPullParser();
21253            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21254            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21255                    new BlobXmlRestorer() {
21256                        @Override
21257                        public void apply(XmlPullParser parser, int userId)
21258                                throws XmlPullParserException, IOException {
21259                            synchronized (mPackages) {
21260                                mSettings.readDefaultAppsLPw(parser, userId);
21261                            }
21262                        }
21263                    } );
21264        } catch (Exception e) {
21265            if (DEBUG_BACKUP) {
21266                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21267            }
21268        }
21269    }
21270
21271    @Override
21272    public byte[] getIntentFilterVerificationBackup(int userId) {
21273        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21274            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21275        }
21276
21277        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21278        try {
21279            final XmlSerializer serializer = new FastXmlSerializer();
21280            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21281            serializer.startDocument(null, true);
21282            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21283
21284            synchronized (mPackages) {
21285                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21286            }
21287
21288            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21289            serializer.endDocument();
21290            serializer.flush();
21291        } catch (Exception e) {
21292            if (DEBUG_BACKUP) {
21293                Slog.e(TAG, "Unable to write default apps for backup", e);
21294            }
21295            return null;
21296        }
21297
21298        return dataStream.toByteArray();
21299    }
21300
21301    @Override
21302    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21303        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21304            throw new SecurityException("Only the system may call restorePreferredActivities()");
21305        }
21306
21307        try {
21308            final XmlPullParser parser = Xml.newPullParser();
21309            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21310            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21311                    new BlobXmlRestorer() {
21312                        @Override
21313                        public void apply(XmlPullParser parser, int userId)
21314                                throws XmlPullParserException, IOException {
21315                            synchronized (mPackages) {
21316                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21317                                mSettings.writeLPr();
21318                            }
21319                        }
21320                    } );
21321        } catch (Exception e) {
21322            if (DEBUG_BACKUP) {
21323                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21324            }
21325        }
21326    }
21327
21328    @Override
21329    public byte[] getPermissionGrantBackup(int userId) {
21330        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21331            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21332        }
21333
21334        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21335        try {
21336            final XmlSerializer serializer = new FastXmlSerializer();
21337            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21338            serializer.startDocument(null, true);
21339            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21340
21341            synchronized (mPackages) {
21342                serializeRuntimePermissionGrantsLPr(serializer, userId);
21343            }
21344
21345            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21346            serializer.endDocument();
21347            serializer.flush();
21348        } catch (Exception e) {
21349            if (DEBUG_BACKUP) {
21350                Slog.e(TAG, "Unable to write default apps for backup", e);
21351            }
21352            return null;
21353        }
21354
21355        return dataStream.toByteArray();
21356    }
21357
21358    @Override
21359    public void restorePermissionGrants(byte[] backup, int userId) {
21360        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21361            throw new SecurityException("Only the system may call restorePermissionGrants()");
21362        }
21363
21364        try {
21365            final XmlPullParser parser = Xml.newPullParser();
21366            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21367            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21368                    new BlobXmlRestorer() {
21369                        @Override
21370                        public void apply(XmlPullParser parser, int userId)
21371                                throws XmlPullParserException, IOException {
21372                            synchronized (mPackages) {
21373                                processRestoredPermissionGrantsLPr(parser, userId);
21374                            }
21375                        }
21376                    } );
21377        } catch (Exception e) {
21378            if (DEBUG_BACKUP) {
21379                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21380            }
21381        }
21382    }
21383
21384    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21385            throws IOException {
21386        serializer.startTag(null, TAG_ALL_GRANTS);
21387
21388        final int N = mSettings.mPackages.size();
21389        for (int i = 0; i < N; i++) {
21390            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21391            boolean pkgGrantsKnown = false;
21392
21393            PermissionsState packagePerms = ps.getPermissionsState();
21394
21395            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21396                final int grantFlags = state.getFlags();
21397                // only look at grants that are not system/policy fixed
21398                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21399                    final boolean isGranted = state.isGranted();
21400                    // And only back up the user-twiddled state bits
21401                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21402                        final String packageName = mSettings.mPackages.keyAt(i);
21403                        if (!pkgGrantsKnown) {
21404                            serializer.startTag(null, TAG_GRANT);
21405                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21406                            pkgGrantsKnown = true;
21407                        }
21408
21409                        final boolean userSet =
21410                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21411                        final boolean userFixed =
21412                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21413                        final boolean revoke =
21414                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21415
21416                        serializer.startTag(null, TAG_PERMISSION);
21417                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21418                        if (isGranted) {
21419                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21420                        }
21421                        if (userSet) {
21422                            serializer.attribute(null, ATTR_USER_SET, "true");
21423                        }
21424                        if (userFixed) {
21425                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21426                        }
21427                        if (revoke) {
21428                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21429                        }
21430                        serializer.endTag(null, TAG_PERMISSION);
21431                    }
21432                }
21433            }
21434
21435            if (pkgGrantsKnown) {
21436                serializer.endTag(null, TAG_GRANT);
21437            }
21438        }
21439
21440        serializer.endTag(null, TAG_ALL_GRANTS);
21441    }
21442
21443    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21444            throws XmlPullParserException, IOException {
21445        String pkgName = null;
21446        int outerDepth = parser.getDepth();
21447        int type;
21448        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21449                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21450            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21451                continue;
21452            }
21453
21454            final String tagName = parser.getName();
21455            if (tagName.equals(TAG_GRANT)) {
21456                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21457                if (DEBUG_BACKUP) {
21458                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21459                }
21460            } else if (tagName.equals(TAG_PERMISSION)) {
21461
21462                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21463                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21464
21465                int newFlagSet = 0;
21466                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21467                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21468                }
21469                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21470                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21471                }
21472                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21473                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21474                }
21475                if (DEBUG_BACKUP) {
21476                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21477                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21478                }
21479                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21480                if (ps != null) {
21481                    // Already installed so we apply the grant immediately
21482                    if (DEBUG_BACKUP) {
21483                        Slog.v(TAG, "        + already installed; applying");
21484                    }
21485                    PermissionsState perms = ps.getPermissionsState();
21486                    BasePermission bp = mSettings.mPermissions.get(permName);
21487                    if (bp != null) {
21488                        if (isGranted) {
21489                            perms.grantRuntimePermission(bp, userId);
21490                        }
21491                        if (newFlagSet != 0) {
21492                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21493                        }
21494                    }
21495                } else {
21496                    // Need to wait for post-restore install to apply the grant
21497                    if (DEBUG_BACKUP) {
21498                        Slog.v(TAG, "        - not yet installed; saving for later");
21499                    }
21500                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21501                            isGranted, newFlagSet, userId);
21502                }
21503            } else {
21504                PackageManagerService.reportSettingsProblem(Log.WARN,
21505                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21506                XmlUtils.skipCurrentTag(parser);
21507            }
21508        }
21509
21510        scheduleWriteSettingsLocked();
21511        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21512    }
21513
21514    @Override
21515    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21516            int sourceUserId, int targetUserId, int flags) {
21517        mContext.enforceCallingOrSelfPermission(
21518                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21519        int callingUid = Binder.getCallingUid();
21520        enforceOwnerRights(ownerPackage, callingUid);
21521        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21522        if (intentFilter.countActions() == 0) {
21523            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21524            return;
21525        }
21526        synchronized (mPackages) {
21527            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21528                    ownerPackage, targetUserId, flags);
21529            CrossProfileIntentResolver resolver =
21530                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21531            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21532            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21533            if (existing != null) {
21534                int size = existing.size();
21535                for (int i = 0; i < size; i++) {
21536                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21537                        return;
21538                    }
21539                }
21540            }
21541            resolver.addFilter(newFilter);
21542            scheduleWritePackageRestrictionsLocked(sourceUserId);
21543        }
21544    }
21545
21546    @Override
21547    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21548        mContext.enforceCallingOrSelfPermission(
21549                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21550        final int callingUid = Binder.getCallingUid();
21551        enforceOwnerRights(ownerPackage, callingUid);
21552        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21553        synchronized (mPackages) {
21554            CrossProfileIntentResolver resolver =
21555                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21556            ArraySet<CrossProfileIntentFilter> set =
21557                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21558            for (CrossProfileIntentFilter filter : set) {
21559                if (filter.getOwnerPackage().equals(ownerPackage)) {
21560                    resolver.removeFilter(filter);
21561                }
21562            }
21563            scheduleWritePackageRestrictionsLocked(sourceUserId);
21564        }
21565    }
21566
21567    // Enforcing that callingUid is owning pkg on userId
21568    private void enforceOwnerRights(String pkg, int callingUid) {
21569        // The system owns everything.
21570        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21571            return;
21572        }
21573        final int callingUserId = UserHandle.getUserId(callingUid);
21574        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21575        if (pi == null) {
21576            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21577                    + callingUserId);
21578        }
21579        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21580            throw new SecurityException("Calling uid " + callingUid
21581                    + " does not own package " + pkg);
21582        }
21583    }
21584
21585    @Override
21586    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21587        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21588            return null;
21589        }
21590        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21591    }
21592
21593    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21594        UserManagerService ums = UserManagerService.getInstance();
21595        if (ums != null) {
21596            final UserInfo parent = ums.getProfileParent(userId);
21597            final int launcherUid = (parent != null) ? parent.id : userId;
21598            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21599            if (launcherComponent != null) {
21600                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21601                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21602                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21603                        .setPackage(launcherComponent.getPackageName());
21604                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21605            }
21606        }
21607    }
21608
21609    /**
21610     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21611     * then reports the most likely home activity or null if there are more than one.
21612     */
21613    private ComponentName getDefaultHomeActivity(int userId) {
21614        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21615        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21616        if (cn != null) {
21617            return cn;
21618        }
21619
21620        // Find the launcher with the highest priority and return that component if there are no
21621        // other home activity with the same priority.
21622        int lastPriority = Integer.MIN_VALUE;
21623        ComponentName lastComponent = null;
21624        final int size = allHomeCandidates.size();
21625        for (int i = 0; i < size; i++) {
21626            final ResolveInfo ri = allHomeCandidates.get(i);
21627            if (ri.priority > lastPriority) {
21628                lastComponent = ri.activityInfo.getComponentName();
21629                lastPriority = ri.priority;
21630            } else if (ri.priority == lastPriority) {
21631                // Two components found with same priority.
21632                lastComponent = null;
21633            }
21634        }
21635        return lastComponent;
21636    }
21637
21638    private Intent getHomeIntent() {
21639        Intent intent = new Intent(Intent.ACTION_MAIN);
21640        intent.addCategory(Intent.CATEGORY_HOME);
21641        intent.addCategory(Intent.CATEGORY_DEFAULT);
21642        return intent;
21643    }
21644
21645    private IntentFilter getHomeFilter() {
21646        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21647        filter.addCategory(Intent.CATEGORY_HOME);
21648        filter.addCategory(Intent.CATEGORY_DEFAULT);
21649        return filter;
21650    }
21651
21652    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21653            int userId) {
21654        Intent intent  = getHomeIntent();
21655        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21656                PackageManager.GET_META_DATA, userId);
21657        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21658                true, false, false, userId);
21659
21660        allHomeCandidates.clear();
21661        if (list != null) {
21662            for (ResolveInfo ri : list) {
21663                allHomeCandidates.add(ri);
21664            }
21665        }
21666        return (preferred == null || preferred.activityInfo == null)
21667                ? null
21668                : new ComponentName(preferred.activityInfo.packageName,
21669                        preferred.activityInfo.name);
21670    }
21671
21672    @Override
21673    public void setHomeActivity(ComponentName comp, int userId) {
21674        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21675            return;
21676        }
21677        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21678        getHomeActivitiesAsUser(homeActivities, userId);
21679
21680        boolean found = false;
21681
21682        final int size = homeActivities.size();
21683        final ComponentName[] set = new ComponentName[size];
21684        for (int i = 0; i < size; i++) {
21685            final ResolveInfo candidate = homeActivities.get(i);
21686            final ActivityInfo info = candidate.activityInfo;
21687            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21688            set[i] = activityName;
21689            if (!found && activityName.equals(comp)) {
21690                found = true;
21691            }
21692        }
21693        if (!found) {
21694            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21695                    + userId);
21696        }
21697        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21698                set, comp, userId);
21699    }
21700
21701    private @Nullable String getSetupWizardPackageName() {
21702        final Intent intent = new Intent(Intent.ACTION_MAIN);
21703        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21704
21705        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21706                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21707                        | MATCH_DISABLED_COMPONENTS,
21708                UserHandle.myUserId());
21709        if (matches.size() == 1) {
21710            return matches.get(0).getComponentInfo().packageName;
21711        } else {
21712            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21713                    + ": matches=" + matches);
21714            return null;
21715        }
21716    }
21717
21718    private @Nullable String getStorageManagerPackageName() {
21719        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21720
21721        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21722                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21723                        | MATCH_DISABLED_COMPONENTS,
21724                UserHandle.myUserId());
21725        if (matches.size() == 1) {
21726            return matches.get(0).getComponentInfo().packageName;
21727        } else {
21728            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21729                    + matches.size() + ": matches=" + matches);
21730            return null;
21731        }
21732    }
21733
21734    @Override
21735    public void setApplicationEnabledSetting(String appPackageName,
21736            int newState, int flags, int userId, String callingPackage) {
21737        if (!sUserManager.exists(userId)) return;
21738        if (callingPackage == null) {
21739            callingPackage = Integer.toString(Binder.getCallingUid());
21740        }
21741        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21742    }
21743
21744    @Override
21745    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21746        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21747        synchronized (mPackages) {
21748            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21749            if (pkgSetting != null) {
21750                pkgSetting.setUpdateAvailable(updateAvailable);
21751            }
21752        }
21753    }
21754
21755    @Override
21756    public void setComponentEnabledSetting(ComponentName componentName,
21757            int newState, int flags, int userId) {
21758        if (!sUserManager.exists(userId)) return;
21759        setEnabledSetting(componentName.getPackageName(),
21760                componentName.getClassName(), newState, flags, userId, null);
21761    }
21762
21763    private void setEnabledSetting(final String packageName, String className, int newState,
21764            final int flags, int userId, String callingPackage) {
21765        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21766              || newState == COMPONENT_ENABLED_STATE_ENABLED
21767              || newState == COMPONENT_ENABLED_STATE_DISABLED
21768              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21769              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21770            throw new IllegalArgumentException("Invalid new component state: "
21771                    + newState);
21772        }
21773        PackageSetting pkgSetting;
21774        final int callingUid = Binder.getCallingUid();
21775        final int permission;
21776        if (callingUid == Process.SYSTEM_UID) {
21777            permission = PackageManager.PERMISSION_GRANTED;
21778        } else {
21779            permission = mContext.checkCallingOrSelfPermission(
21780                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21781        }
21782        enforceCrossUserPermission(callingUid, userId,
21783                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21784        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21785        boolean sendNow = false;
21786        boolean isApp = (className == null);
21787        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21788        String componentName = isApp ? packageName : className;
21789        int packageUid = -1;
21790        ArrayList<String> components;
21791
21792        // reader
21793        synchronized (mPackages) {
21794            pkgSetting = mSettings.mPackages.get(packageName);
21795            if (pkgSetting == null) {
21796                if (!isCallerInstantApp) {
21797                    if (className == null) {
21798                        throw new IllegalArgumentException("Unknown package: " + packageName);
21799                    }
21800                    throw new IllegalArgumentException(
21801                            "Unknown component: " + packageName + "/" + className);
21802                } else {
21803                    // throw SecurityException to prevent leaking package information
21804                    throw new SecurityException(
21805                            "Attempt to change component state; "
21806                            + "pid=" + Binder.getCallingPid()
21807                            + ", uid=" + callingUid
21808                            + (className == null
21809                                    ? ", package=" + packageName
21810                                    : ", component=" + packageName + "/" + className));
21811                }
21812            }
21813        }
21814
21815        // Limit who can change which apps
21816        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21817            // Don't allow apps that don't have permission to modify other apps
21818            if (!allowedByPermission
21819                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21820                throw new SecurityException(
21821                        "Attempt to change component state; "
21822                        + "pid=" + Binder.getCallingPid()
21823                        + ", uid=" + callingUid
21824                        + (className == null
21825                                ? ", package=" + packageName
21826                                : ", component=" + packageName + "/" + className));
21827            }
21828            // Don't allow changing protected packages.
21829            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21830                throw new SecurityException("Cannot disable a protected package: " + packageName);
21831            }
21832        }
21833
21834        synchronized (mPackages) {
21835            if (callingUid == Process.SHELL_UID
21836                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21837                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21838                // unless it is a test package.
21839                int oldState = pkgSetting.getEnabled(userId);
21840                if (className == null
21841                        &&
21842                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21843                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21844                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21845                        &&
21846                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21847                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
21848                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21849                    // ok
21850                } else {
21851                    throw new SecurityException(
21852                            "Shell cannot change component state for " + packageName + "/"
21853                                    + className + " to " + newState);
21854                }
21855            }
21856        }
21857        if (className == null) {
21858            // We're dealing with an application/package level state change
21859            synchronized (mPackages) {
21860                if (pkgSetting.getEnabled(userId) == newState) {
21861                    // Nothing to do
21862                    return;
21863                }
21864            }
21865            // If we're enabling a system stub, there's a little more work to do.
21866            // Prior to enabling the package, we need to decompress the APK(s) to the
21867            // data partition and then replace the version on the system partition.
21868            final PackageParser.Package deletedPkg = pkgSetting.pkg;
21869            final boolean isSystemStub = deletedPkg.isStub
21870                    && deletedPkg.isSystemApp();
21871            if (isSystemStub
21872                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21873                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21874                final File codePath = decompressPackage(deletedPkg);
21875                if (codePath == null) {
21876                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
21877                    return;
21878                }
21879                // TODO remove direct parsing of the package object during internal cleanup
21880                // of scan package
21881                // We need to call parse directly here for no other reason than we need
21882                // the new package in order to disable the old one [we use the information
21883                // for some internal optimization to optionally create a new package setting
21884                // object on replace]. However, we can't get the package from the scan
21885                // because the scan modifies live structures and we need to remove the
21886                // old [system] package from the system before a scan can be attempted.
21887                // Once scan is indempotent we can remove this parse and use the package
21888                // object we scanned, prior to adding it to package settings.
21889                final PackageParser pp = new PackageParser();
21890                pp.setSeparateProcesses(mSeparateProcesses);
21891                pp.setDisplayMetrics(mMetrics);
21892                pp.setCallback(mPackageParserCallback);
21893                final PackageParser.Package tmpPkg;
21894                try {
21895                    final int parseFlags = mDefParseFlags
21896                            | PackageParser.PARSE_MUST_BE_APK
21897                            | PackageParser.PARSE_IS_SYSTEM
21898                            | PackageParser.PARSE_IS_SYSTEM_DIR;
21899                    tmpPkg = pp.parsePackage(codePath, parseFlags);
21900                } catch (PackageParserException e) {
21901                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
21902                    return;
21903                }
21904                synchronized (mInstallLock) {
21905                    // Disable the stub and remove any package entries
21906                    removePackageLI(deletedPkg, true);
21907                    synchronized (mPackages) {
21908                        disableSystemPackageLPw(deletedPkg, tmpPkg);
21909                    }
21910                    final PackageParser.Package newPkg;
21911                    try (PackageFreezer freezer =
21912                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21913                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
21914                                | PackageParser.PARSE_ENFORCE_CODE;
21915                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
21916                                0 /*currentTime*/, null /*user*/);
21917                        prepareAppDataAfterInstallLIF(newPkg);
21918                        synchronized (mPackages) {
21919                            try {
21920                                updateSharedLibrariesLPr(newPkg, null);
21921                            } catch (PackageManagerException e) {
21922                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
21923                            }
21924                            updatePermissionsLPw(newPkg.packageName, newPkg,
21925                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
21926                            mSettings.writeLPr();
21927                        }
21928                    } catch (PackageManagerException e) {
21929                        // Whoops! Something went wrong; try to roll back to the stub
21930                        Slog.w(TAG, "Failed to install compressed system package:"
21931                                + pkgSetting.name, e);
21932                        // Remove the failed install
21933                        removeCodePathLI(codePath);
21934
21935                        // Install the system package
21936                        try (PackageFreezer freezer =
21937                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
21938                            synchronized (mPackages) {
21939                                // NOTE: The system package always needs to be enabled; even
21940                                // if it's for a compressed stub. If we don't, installing the
21941                                // system package fails during scan [scanning checks the disabled
21942                                // packages]. We will reverse this later, after we've "installed"
21943                                // the stub.
21944                                // This leaves us in a fragile state; the stub should never be
21945                                // enabled, so, cross your fingers and hope nothing goes wrong
21946                                // until we can disable the package later.
21947                                enableSystemPackageLPw(deletedPkg);
21948                            }
21949                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
21950                                    false /*isPrivileged*/, null /*allUserHandles*/,
21951                                    null /*origUserHandles*/, null /*origPermissionsState*/,
21952                                    true /*writeSettings*/);
21953                        } catch (PackageManagerException pme) {
21954                            Slog.w(TAG, "Failed to restore system package:"
21955                                    + deletedPkg.packageName, pme);
21956                        } finally {
21957                            synchronized (mPackages) {
21958                                mSettings.disableSystemPackageLPw(
21959                                        deletedPkg.packageName, true /*replaced*/);
21960                                mSettings.writeLPr();
21961                            }
21962                        }
21963                        return;
21964                    }
21965                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
21966                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21967                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
21968                    mDexManager.notifyPackageUpdated(newPkg.packageName,
21969                            newPkg.baseCodePath, newPkg.splitCodePaths);
21970                }
21971            }
21972            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21973                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21974                // Don't care about who enables an app.
21975                callingPackage = null;
21976            }
21977            synchronized (mPackages) {
21978                pkgSetting.setEnabled(newState, userId, callingPackage);
21979            }
21980        } else {
21981            synchronized (mPackages) {
21982                // We're dealing with a component level state change
21983                // First, verify that this is a valid class name.
21984                PackageParser.Package pkg = pkgSetting.pkg;
21985                if (pkg == null || !pkg.hasComponentClassName(className)) {
21986                    if (pkg != null &&
21987                            pkg.applicationInfo.targetSdkVersion >=
21988                                    Build.VERSION_CODES.JELLY_BEAN) {
21989                        throw new IllegalArgumentException("Component class " + className
21990                                + " does not exist in " + packageName);
21991                    } else {
21992                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21993                                + className + " does not exist in " + packageName);
21994                    }
21995                }
21996                switch (newState) {
21997                    case COMPONENT_ENABLED_STATE_ENABLED:
21998                        if (!pkgSetting.enableComponentLPw(className, userId)) {
21999                            return;
22000                        }
22001                        break;
22002                    case COMPONENT_ENABLED_STATE_DISABLED:
22003                        if (!pkgSetting.disableComponentLPw(className, userId)) {
22004                            return;
22005                        }
22006                        break;
22007                    case COMPONENT_ENABLED_STATE_DEFAULT:
22008                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
22009                            return;
22010                        }
22011                        break;
22012                    default:
22013                        Slog.e(TAG, "Invalid new component state: " + newState);
22014                        return;
22015                }
22016            }
22017        }
22018        synchronized (mPackages) {
22019            scheduleWritePackageRestrictionsLocked(userId);
22020            updateSequenceNumberLP(pkgSetting, new int[] { userId });
22021            final long callingId = Binder.clearCallingIdentity();
22022            try {
22023                updateInstantAppInstallerLocked(packageName);
22024            } finally {
22025                Binder.restoreCallingIdentity(callingId);
22026            }
22027            components = mPendingBroadcasts.get(userId, packageName);
22028            final boolean newPackage = components == null;
22029            if (newPackage) {
22030                components = new ArrayList<String>();
22031            }
22032            if (!components.contains(componentName)) {
22033                components.add(componentName);
22034            }
22035            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
22036                sendNow = true;
22037                // Purge entry from pending broadcast list if another one exists already
22038                // since we are sending one right away.
22039                mPendingBroadcasts.remove(userId, packageName);
22040            } else {
22041                if (newPackage) {
22042                    mPendingBroadcasts.put(userId, packageName, components);
22043                }
22044                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
22045                    // Schedule a message
22046                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
22047                }
22048            }
22049        }
22050
22051        long callingId = Binder.clearCallingIdentity();
22052        try {
22053            if (sendNow) {
22054                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
22055                sendPackageChangedBroadcast(packageName,
22056                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
22057            }
22058        } finally {
22059            Binder.restoreCallingIdentity(callingId);
22060        }
22061    }
22062
22063    @Override
22064    public void flushPackageRestrictionsAsUser(int userId) {
22065        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
22066            return;
22067        }
22068        if (!sUserManager.exists(userId)) {
22069            return;
22070        }
22071        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
22072                false /* checkShell */, "flushPackageRestrictions");
22073        synchronized (mPackages) {
22074            mSettings.writePackageRestrictionsLPr(userId);
22075            mDirtyUsers.remove(userId);
22076            if (mDirtyUsers.isEmpty()) {
22077                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
22078            }
22079        }
22080    }
22081
22082    private void sendPackageChangedBroadcast(String packageName,
22083            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
22084        if (DEBUG_INSTALL)
22085            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
22086                    + componentNames);
22087        Bundle extras = new Bundle(4);
22088        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
22089        String nameList[] = new String[componentNames.size()];
22090        componentNames.toArray(nameList);
22091        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
22092        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
22093        extras.putInt(Intent.EXTRA_UID, packageUid);
22094        // If this is not reporting a change of the overall package, then only send it
22095        // to registered receivers.  We don't want to launch a swath of apps for every
22096        // little component state change.
22097        final int flags = !componentNames.contains(packageName)
22098                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
22099        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
22100                new int[] {UserHandle.getUserId(packageUid)});
22101    }
22102
22103    @Override
22104    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
22105        if (!sUserManager.exists(userId)) return;
22106        final int callingUid = Binder.getCallingUid();
22107        if (getInstantAppPackageName(callingUid) != null) {
22108            return;
22109        }
22110        final int permission = mContext.checkCallingOrSelfPermission(
22111                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
22112        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
22113        enforceCrossUserPermission(callingUid, userId,
22114                true /* requireFullPermission */, true /* checkShell */, "stop package");
22115        // writer
22116        synchronized (mPackages) {
22117            final PackageSetting ps = mSettings.mPackages.get(packageName);
22118            if (!filterAppAccessLPr(ps, callingUid, userId)
22119                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
22120                            allowedByPermission, callingUid, userId)) {
22121                scheduleWritePackageRestrictionsLocked(userId);
22122            }
22123        }
22124    }
22125
22126    @Override
22127    public String getInstallerPackageName(String packageName) {
22128        final int callingUid = Binder.getCallingUid();
22129        if (getInstantAppPackageName(callingUid) != null) {
22130            return null;
22131        }
22132        // reader
22133        synchronized (mPackages) {
22134            final PackageSetting ps = mSettings.mPackages.get(packageName);
22135            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
22136                return null;
22137            }
22138            return mSettings.getInstallerPackageNameLPr(packageName);
22139        }
22140    }
22141
22142    public boolean isOrphaned(String packageName) {
22143        // reader
22144        synchronized (mPackages) {
22145            return mSettings.isOrphaned(packageName);
22146        }
22147    }
22148
22149    @Override
22150    public int getApplicationEnabledSetting(String packageName, int userId) {
22151        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22152        int callingUid = Binder.getCallingUid();
22153        enforceCrossUserPermission(callingUid, userId,
22154                false /* requireFullPermission */, false /* checkShell */, "get enabled");
22155        // reader
22156        synchronized (mPackages) {
22157            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
22158                return COMPONENT_ENABLED_STATE_DISABLED;
22159            }
22160            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
22161        }
22162    }
22163
22164    @Override
22165    public int getComponentEnabledSetting(ComponentName component, int userId) {
22166        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
22167        int callingUid = Binder.getCallingUid();
22168        enforceCrossUserPermission(callingUid, userId,
22169                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
22170        synchronized (mPackages) {
22171            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
22172                    component, TYPE_UNKNOWN, userId)) {
22173                return COMPONENT_ENABLED_STATE_DISABLED;
22174            }
22175            return mSettings.getComponentEnabledSettingLPr(component, userId);
22176        }
22177    }
22178
22179    @Override
22180    public void enterSafeMode() {
22181        enforceSystemOrRoot("Only the system can request entering safe mode");
22182
22183        if (!mSystemReady) {
22184            mSafeMode = true;
22185        }
22186    }
22187
22188    @Override
22189    public void systemReady() {
22190        enforceSystemOrRoot("Only the system can claim the system is ready");
22191
22192        mSystemReady = true;
22193        final ContentResolver resolver = mContext.getContentResolver();
22194        ContentObserver co = new ContentObserver(mHandler) {
22195            @Override
22196            public void onChange(boolean selfChange) {
22197                mEphemeralAppsDisabled =
22198                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
22199                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
22200            }
22201        };
22202        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22203                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
22204                false, co, UserHandle.USER_SYSTEM);
22205        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
22206                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
22207        co.onChange(true);
22208
22209        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
22210        // disabled after already being started.
22211        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
22212                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
22213
22214        // Read the compatibilty setting when the system is ready.
22215        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
22216                mContext.getContentResolver(),
22217                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
22218        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
22219        if (DEBUG_SETTINGS) {
22220            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
22221        }
22222
22223        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
22224
22225        synchronized (mPackages) {
22226            // Verify that all of the preferred activity components actually
22227            // exist.  It is possible for applications to be updated and at
22228            // that point remove a previously declared activity component that
22229            // had been set as a preferred activity.  We try to clean this up
22230            // the next time we encounter that preferred activity, but it is
22231            // possible for the user flow to never be able to return to that
22232            // situation so here we do a sanity check to make sure we haven't
22233            // left any junk around.
22234            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
22235            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22236                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22237                removed.clear();
22238                for (PreferredActivity pa : pir.filterSet()) {
22239                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
22240                        removed.add(pa);
22241                    }
22242                }
22243                if (removed.size() > 0) {
22244                    for (int r=0; r<removed.size(); r++) {
22245                        PreferredActivity pa = removed.get(r);
22246                        Slog.w(TAG, "Removing dangling preferred activity: "
22247                                + pa.mPref.mComponent);
22248                        pir.removeFilter(pa);
22249                    }
22250                    mSettings.writePackageRestrictionsLPr(
22251                            mSettings.mPreferredActivities.keyAt(i));
22252                }
22253            }
22254
22255            for (int userId : UserManagerService.getInstance().getUserIds()) {
22256                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
22257                    grantPermissionsUserIds = ArrayUtils.appendInt(
22258                            grantPermissionsUserIds, userId);
22259                }
22260            }
22261        }
22262        sUserManager.systemReady();
22263
22264        // If we upgraded grant all default permissions before kicking off.
22265        for (int userId : grantPermissionsUserIds) {
22266            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22267        }
22268
22269        // If we did not grant default permissions, we preload from this the
22270        // default permission exceptions lazily to ensure we don't hit the
22271        // disk on a new user creation.
22272        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22273            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22274        }
22275
22276        // Kick off any messages waiting for system ready
22277        if (mPostSystemReadyMessages != null) {
22278            for (Message msg : mPostSystemReadyMessages) {
22279                msg.sendToTarget();
22280            }
22281            mPostSystemReadyMessages = null;
22282        }
22283
22284        // Watch for external volumes that come and go over time
22285        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22286        storage.registerListener(mStorageListener);
22287
22288        mInstallerService.systemReady();
22289        mPackageDexOptimizer.systemReady();
22290
22291        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22292                StorageManagerInternal.class);
22293        StorageManagerInternal.addExternalStoragePolicy(
22294                new StorageManagerInternal.ExternalStorageMountPolicy() {
22295            @Override
22296            public int getMountMode(int uid, String packageName) {
22297                if (Process.isIsolated(uid)) {
22298                    return Zygote.MOUNT_EXTERNAL_NONE;
22299                }
22300                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22301                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22302                }
22303                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22304                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22305                }
22306                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22307                    return Zygote.MOUNT_EXTERNAL_READ;
22308                }
22309                return Zygote.MOUNT_EXTERNAL_WRITE;
22310            }
22311
22312            @Override
22313            public boolean hasExternalStorage(int uid, String packageName) {
22314                return true;
22315            }
22316        });
22317
22318        // Now that we're mostly running, clean up stale users and apps
22319        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22320        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22321
22322        if (mPrivappPermissionsViolations != null) {
22323            Slog.wtf(TAG,"Signature|privileged permissions not in "
22324                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22325            mPrivappPermissionsViolations = null;
22326        }
22327    }
22328
22329    public void waitForAppDataPrepared() {
22330        if (mPrepareAppDataFuture == null) {
22331            return;
22332        }
22333        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22334        mPrepareAppDataFuture = null;
22335    }
22336
22337    @Override
22338    public boolean isSafeMode() {
22339        // allow instant applications
22340        return mSafeMode;
22341    }
22342
22343    @Override
22344    public boolean hasSystemUidErrors() {
22345        // allow instant applications
22346        return mHasSystemUidErrors;
22347    }
22348
22349    static String arrayToString(int[] array) {
22350        StringBuffer buf = new StringBuffer(128);
22351        buf.append('[');
22352        if (array != null) {
22353            for (int i=0; i<array.length; i++) {
22354                if (i > 0) buf.append(", ");
22355                buf.append(array[i]);
22356            }
22357        }
22358        buf.append(']');
22359        return buf.toString();
22360    }
22361
22362    static class DumpState {
22363        public static final int DUMP_LIBS = 1 << 0;
22364        public static final int DUMP_FEATURES = 1 << 1;
22365        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22366        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22367        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22368        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22369        public static final int DUMP_PERMISSIONS = 1 << 6;
22370        public static final int DUMP_PACKAGES = 1 << 7;
22371        public static final int DUMP_SHARED_USERS = 1 << 8;
22372        public static final int DUMP_MESSAGES = 1 << 9;
22373        public static final int DUMP_PROVIDERS = 1 << 10;
22374        public static final int DUMP_VERIFIERS = 1 << 11;
22375        public static final int DUMP_PREFERRED = 1 << 12;
22376        public static final int DUMP_PREFERRED_XML = 1 << 13;
22377        public static final int DUMP_KEYSETS = 1 << 14;
22378        public static final int DUMP_VERSION = 1 << 15;
22379        public static final int DUMP_INSTALLS = 1 << 16;
22380        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22381        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22382        public static final int DUMP_FROZEN = 1 << 19;
22383        public static final int DUMP_DEXOPT = 1 << 20;
22384        public static final int DUMP_COMPILER_STATS = 1 << 21;
22385        public static final int DUMP_CHANGES = 1 << 22;
22386        public static final int DUMP_VOLUMES = 1 << 23;
22387
22388        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22389
22390        private int mTypes;
22391
22392        private int mOptions;
22393
22394        private boolean mTitlePrinted;
22395
22396        private SharedUserSetting mSharedUser;
22397
22398        public boolean isDumping(int type) {
22399            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22400                return true;
22401            }
22402
22403            return (mTypes & type) != 0;
22404        }
22405
22406        public void setDump(int type) {
22407            mTypes |= type;
22408        }
22409
22410        public boolean isOptionEnabled(int option) {
22411            return (mOptions & option) != 0;
22412        }
22413
22414        public void setOptionEnabled(int option) {
22415            mOptions |= option;
22416        }
22417
22418        public boolean onTitlePrinted() {
22419            final boolean printed = mTitlePrinted;
22420            mTitlePrinted = true;
22421            return printed;
22422        }
22423
22424        public boolean getTitlePrinted() {
22425            return mTitlePrinted;
22426        }
22427
22428        public void setTitlePrinted(boolean enabled) {
22429            mTitlePrinted = enabled;
22430        }
22431
22432        public SharedUserSetting getSharedUser() {
22433            return mSharedUser;
22434        }
22435
22436        public void setSharedUser(SharedUserSetting user) {
22437            mSharedUser = user;
22438        }
22439    }
22440
22441    @Override
22442    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22443            FileDescriptor err, String[] args, ShellCallback callback,
22444            ResultReceiver resultReceiver) {
22445        (new PackageManagerShellCommand(this)).exec(
22446                this, in, out, err, args, callback, resultReceiver);
22447    }
22448
22449    @Override
22450    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22451        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22452
22453        DumpState dumpState = new DumpState();
22454        boolean fullPreferred = false;
22455        boolean checkin = false;
22456
22457        String packageName = null;
22458        ArraySet<String> permissionNames = null;
22459
22460        int opti = 0;
22461        while (opti < args.length) {
22462            String opt = args[opti];
22463            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22464                break;
22465            }
22466            opti++;
22467
22468            if ("-a".equals(opt)) {
22469                // Right now we only know how to print all.
22470            } else if ("-h".equals(opt)) {
22471                pw.println("Package manager dump options:");
22472                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22473                pw.println("    --checkin: dump for a checkin");
22474                pw.println("    -f: print details of intent filters");
22475                pw.println("    -h: print this help");
22476                pw.println("  cmd may be one of:");
22477                pw.println("    l[ibraries]: list known shared libraries");
22478                pw.println("    f[eatures]: list device features");
22479                pw.println("    k[eysets]: print known keysets");
22480                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22481                pw.println("    perm[issions]: dump permissions");
22482                pw.println("    permission [name ...]: dump declaration and use of given permission");
22483                pw.println("    pref[erred]: print preferred package settings");
22484                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22485                pw.println("    prov[iders]: dump content providers");
22486                pw.println("    p[ackages]: dump installed packages");
22487                pw.println("    s[hared-users]: dump shared user IDs");
22488                pw.println("    m[essages]: print collected runtime messages");
22489                pw.println("    v[erifiers]: print package verifier info");
22490                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22491                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22492                pw.println("    version: print database version info");
22493                pw.println("    write: write current settings now");
22494                pw.println("    installs: details about install sessions");
22495                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22496                pw.println("    dexopt: dump dexopt state");
22497                pw.println("    compiler-stats: dump compiler statistics");
22498                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22499                pw.println("    <package.name>: info about given package");
22500                return;
22501            } else if ("--checkin".equals(opt)) {
22502                checkin = true;
22503            } else if ("-f".equals(opt)) {
22504                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22505            } else if ("--proto".equals(opt)) {
22506                dumpProto(fd);
22507                return;
22508            } else {
22509                pw.println("Unknown argument: " + opt + "; use -h for help");
22510            }
22511        }
22512
22513        // Is the caller requesting to dump a particular piece of data?
22514        if (opti < args.length) {
22515            String cmd = args[opti];
22516            opti++;
22517            // Is this a package name?
22518            if ("android".equals(cmd) || cmd.contains(".")) {
22519                packageName = cmd;
22520                // When dumping a single package, we always dump all of its
22521                // filter information since the amount of data will be reasonable.
22522                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22523            } else if ("check-permission".equals(cmd)) {
22524                if (opti >= args.length) {
22525                    pw.println("Error: check-permission missing permission argument");
22526                    return;
22527                }
22528                String perm = args[opti];
22529                opti++;
22530                if (opti >= args.length) {
22531                    pw.println("Error: check-permission missing package argument");
22532                    return;
22533                }
22534
22535                String pkg = args[opti];
22536                opti++;
22537                int user = UserHandle.getUserId(Binder.getCallingUid());
22538                if (opti < args.length) {
22539                    try {
22540                        user = Integer.parseInt(args[opti]);
22541                    } catch (NumberFormatException e) {
22542                        pw.println("Error: check-permission user argument is not a number: "
22543                                + args[opti]);
22544                        return;
22545                    }
22546                }
22547
22548                // Normalize package name to handle renamed packages and static libs
22549                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22550
22551                pw.println(checkPermission(perm, pkg, user));
22552                return;
22553            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22554                dumpState.setDump(DumpState.DUMP_LIBS);
22555            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22556                dumpState.setDump(DumpState.DUMP_FEATURES);
22557            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22558                if (opti >= args.length) {
22559                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22560                            | DumpState.DUMP_SERVICE_RESOLVERS
22561                            | DumpState.DUMP_RECEIVER_RESOLVERS
22562                            | DumpState.DUMP_CONTENT_RESOLVERS);
22563                } else {
22564                    while (opti < args.length) {
22565                        String name = args[opti];
22566                        if ("a".equals(name) || "activity".equals(name)) {
22567                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22568                        } else if ("s".equals(name) || "service".equals(name)) {
22569                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22570                        } else if ("r".equals(name) || "receiver".equals(name)) {
22571                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22572                        } else if ("c".equals(name) || "content".equals(name)) {
22573                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22574                        } else {
22575                            pw.println("Error: unknown resolver table type: " + name);
22576                            return;
22577                        }
22578                        opti++;
22579                    }
22580                }
22581            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22582                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22583            } else if ("permission".equals(cmd)) {
22584                if (opti >= args.length) {
22585                    pw.println("Error: permission requires permission name");
22586                    return;
22587                }
22588                permissionNames = new ArraySet<>();
22589                while (opti < args.length) {
22590                    permissionNames.add(args[opti]);
22591                    opti++;
22592                }
22593                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22594                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22595            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22596                dumpState.setDump(DumpState.DUMP_PREFERRED);
22597            } else if ("preferred-xml".equals(cmd)) {
22598                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22599                if (opti < args.length && "--full".equals(args[opti])) {
22600                    fullPreferred = true;
22601                    opti++;
22602                }
22603            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22604                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22605            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22606                dumpState.setDump(DumpState.DUMP_PACKAGES);
22607            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22608                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22609            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22610                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22611            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22612                dumpState.setDump(DumpState.DUMP_MESSAGES);
22613            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22614                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22615            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22616                    || "intent-filter-verifiers".equals(cmd)) {
22617                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22618            } else if ("version".equals(cmd)) {
22619                dumpState.setDump(DumpState.DUMP_VERSION);
22620            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22621                dumpState.setDump(DumpState.DUMP_KEYSETS);
22622            } else if ("installs".equals(cmd)) {
22623                dumpState.setDump(DumpState.DUMP_INSTALLS);
22624            } else if ("frozen".equals(cmd)) {
22625                dumpState.setDump(DumpState.DUMP_FROZEN);
22626            } else if ("volumes".equals(cmd)) {
22627                dumpState.setDump(DumpState.DUMP_VOLUMES);
22628            } else if ("dexopt".equals(cmd)) {
22629                dumpState.setDump(DumpState.DUMP_DEXOPT);
22630            } else if ("compiler-stats".equals(cmd)) {
22631                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22632            } else if ("changes".equals(cmd)) {
22633                dumpState.setDump(DumpState.DUMP_CHANGES);
22634            } else if ("write".equals(cmd)) {
22635                synchronized (mPackages) {
22636                    mSettings.writeLPr();
22637                    pw.println("Settings written.");
22638                    return;
22639                }
22640            }
22641        }
22642
22643        if (checkin) {
22644            pw.println("vers,1");
22645        }
22646
22647        // reader
22648        synchronized (mPackages) {
22649            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22650                if (!checkin) {
22651                    if (dumpState.onTitlePrinted())
22652                        pw.println();
22653                    pw.println("Database versions:");
22654                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22655                }
22656            }
22657
22658            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22659                if (!checkin) {
22660                    if (dumpState.onTitlePrinted())
22661                        pw.println();
22662                    pw.println("Verifiers:");
22663                    pw.print("  Required: ");
22664                    pw.print(mRequiredVerifierPackage);
22665                    pw.print(" (uid=");
22666                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22667                            UserHandle.USER_SYSTEM));
22668                    pw.println(")");
22669                } else if (mRequiredVerifierPackage != null) {
22670                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22671                    pw.print(",");
22672                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22673                            UserHandle.USER_SYSTEM));
22674                }
22675            }
22676
22677            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22678                    packageName == null) {
22679                if (mIntentFilterVerifierComponent != null) {
22680                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22681                    if (!checkin) {
22682                        if (dumpState.onTitlePrinted())
22683                            pw.println();
22684                        pw.println("Intent Filter Verifier:");
22685                        pw.print("  Using: ");
22686                        pw.print(verifierPackageName);
22687                        pw.print(" (uid=");
22688                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22689                                UserHandle.USER_SYSTEM));
22690                        pw.println(")");
22691                    } else if (verifierPackageName != null) {
22692                        pw.print("ifv,"); pw.print(verifierPackageName);
22693                        pw.print(",");
22694                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22695                                UserHandle.USER_SYSTEM));
22696                    }
22697                } else {
22698                    pw.println();
22699                    pw.println("No Intent Filter Verifier available!");
22700                }
22701            }
22702
22703            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22704                boolean printedHeader = false;
22705                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22706                while (it.hasNext()) {
22707                    String libName = it.next();
22708                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22709                    if (versionedLib == null) {
22710                        continue;
22711                    }
22712                    final int versionCount = versionedLib.size();
22713                    for (int i = 0; i < versionCount; i++) {
22714                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22715                        if (!checkin) {
22716                            if (!printedHeader) {
22717                                if (dumpState.onTitlePrinted())
22718                                    pw.println();
22719                                pw.println("Libraries:");
22720                                printedHeader = true;
22721                            }
22722                            pw.print("  ");
22723                        } else {
22724                            pw.print("lib,");
22725                        }
22726                        pw.print(libEntry.info.getName());
22727                        if (libEntry.info.isStatic()) {
22728                            pw.print(" version=" + libEntry.info.getVersion());
22729                        }
22730                        if (!checkin) {
22731                            pw.print(" -> ");
22732                        }
22733                        if (libEntry.path != null) {
22734                            pw.print(" (jar) ");
22735                            pw.print(libEntry.path);
22736                        } else {
22737                            pw.print(" (apk) ");
22738                            pw.print(libEntry.apk);
22739                        }
22740                        pw.println();
22741                    }
22742                }
22743            }
22744
22745            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22746                if (dumpState.onTitlePrinted())
22747                    pw.println();
22748                if (!checkin) {
22749                    pw.println("Features:");
22750                }
22751
22752                synchronized (mAvailableFeatures) {
22753                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22754                        if (checkin) {
22755                            pw.print("feat,");
22756                            pw.print(feat.name);
22757                            pw.print(",");
22758                            pw.println(feat.version);
22759                        } else {
22760                            pw.print("  ");
22761                            pw.print(feat.name);
22762                            if (feat.version > 0) {
22763                                pw.print(" version=");
22764                                pw.print(feat.version);
22765                            }
22766                            pw.println();
22767                        }
22768                    }
22769                }
22770            }
22771
22772            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22773                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22774                        : "Activity Resolver Table:", "  ", packageName,
22775                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22776                    dumpState.setTitlePrinted(true);
22777                }
22778            }
22779            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22780                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22781                        : "Receiver Resolver Table:", "  ", packageName,
22782                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22783                    dumpState.setTitlePrinted(true);
22784                }
22785            }
22786            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22787                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22788                        : "Service Resolver Table:", "  ", packageName,
22789                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22790                    dumpState.setTitlePrinted(true);
22791                }
22792            }
22793            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22794                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22795                        : "Provider Resolver Table:", "  ", packageName,
22796                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22797                    dumpState.setTitlePrinted(true);
22798                }
22799            }
22800
22801            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22802                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22803                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22804                    int user = mSettings.mPreferredActivities.keyAt(i);
22805                    if (pir.dump(pw,
22806                            dumpState.getTitlePrinted()
22807                                ? "\nPreferred Activities User " + user + ":"
22808                                : "Preferred Activities User " + user + ":", "  ",
22809                            packageName, true, false)) {
22810                        dumpState.setTitlePrinted(true);
22811                    }
22812                }
22813            }
22814
22815            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22816                pw.flush();
22817                FileOutputStream fout = new FileOutputStream(fd);
22818                BufferedOutputStream str = new BufferedOutputStream(fout);
22819                XmlSerializer serializer = new FastXmlSerializer();
22820                try {
22821                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22822                    serializer.startDocument(null, true);
22823                    serializer.setFeature(
22824                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22825                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22826                    serializer.endDocument();
22827                    serializer.flush();
22828                } catch (IllegalArgumentException e) {
22829                    pw.println("Failed writing: " + e);
22830                } catch (IllegalStateException e) {
22831                    pw.println("Failed writing: " + e);
22832                } catch (IOException e) {
22833                    pw.println("Failed writing: " + e);
22834                }
22835            }
22836
22837            if (!checkin
22838                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22839                    && packageName == null) {
22840                pw.println();
22841                int count = mSettings.mPackages.size();
22842                if (count == 0) {
22843                    pw.println("No applications!");
22844                    pw.println();
22845                } else {
22846                    final String prefix = "  ";
22847                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22848                    if (allPackageSettings.size() == 0) {
22849                        pw.println("No domain preferred apps!");
22850                        pw.println();
22851                    } else {
22852                        pw.println("App verification status:");
22853                        pw.println();
22854                        count = 0;
22855                        for (PackageSetting ps : allPackageSettings) {
22856                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22857                            if (ivi == null || ivi.getPackageName() == null) continue;
22858                            pw.println(prefix + "Package: " + ivi.getPackageName());
22859                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22860                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22861                            pw.println();
22862                            count++;
22863                        }
22864                        if (count == 0) {
22865                            pw.println(prefix + "No app verification established.");
22866                            pw.println();
22867                        }
22868                        for (int userId : sUserManager.getUserIds()) {
22869                            pw.println("App linkages for user " + userId + ":");
22870                            pw.println();
22871                            count = 0;
22872                            for (PackageSetting ps : allPackageSettings) {
22873                                final long status = ps.getDomainVerificationStatusForUser(userId);
22874                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22875                                        && !DEBUG_DOMAIN_VERIFICATION) {
22876                                    continue;
22877                                }
22878                                pw.println(prefix + "Package: " + ps.name);
22879                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22880                                String statusStr = IntentFilterVerificationInfo.
22881                                        getStatusStringFromValue(status);
22882                                pw.println(prefix + "Status:  " + statusStr);
22883                                pw.println();
22884                                count++;
22885                            }
22886                            if (count == 0) {
22887                                pw.println(prefix + "No configured app linkages.");
22888                                pw.println();
22889                            }
22890                        }
22891                    }
22892                }
22893            }
22894
22895            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22896                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22897                if (packageName == null && permissionNames == null) {
22898                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22899                        if (iperm == 0) {
22900                            if (dumpState.onTitlePrinted())
22901                                pw.println();
22902                            pw.println("AppOp Permissions:");
22903                        }
22904                        pw.print("  AppOp Permission ");
22905                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22906                        pw.println(":");
22907                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22908                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22909                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22910                        }
22911                    }
22912                }
22913            }
22914
22915            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22916                boolean printedSomething = false;
22917                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22918                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22919                        continue;
22920                    }
22921                    if (!printedSomething) {
22922                        if (dumpState.onTitlePrinted())
22923                            pw.println();
22924                        pw.println("Registered ContentProviders:");
22925                        printedSomething = true;
22926                    }
22927                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22928                    pw.print("    "); pw.println(p.toString());
22929                }
22930                printedSomething = false;
22931                for (Map.Entry<String, PackageParser.Provider> entry :
22932                        mProvidersByAuthority.entrySet()) {
22933                    PackageParser.Provider p = entry.getValue();
22934                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22935                        continue;
22936                    }
22937                    if (!printedSomething) {
22938                        if (dumpState.onTitlePrinted())
22939                            pw.println();
22940                        pw.println("ContentProvider Authorities:");
22941                        printedSomething = true;
22942                    }
22943                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22944                    pw.print("    "); pw.println(p.toString());
22945                    if (p.info != null && p.info.applicationInfo != null) {
22946                        final String appInfo = p.info.applicationInfo.toString();
22947                        pw.print("      applicationInfo="); pw.println(appInfo);
22948                    }
22949                }
22950            }
22951
22952            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22953                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22954            }
22955
22956            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22957                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22958            }
22959
22960            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22961                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22962            }
22963
22964            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22965                if (dumpState.onTitlePrinted()) pw.println();
22966                pw.println("Package Changes:");
22967                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22968                final int K = mChangedPackages.size();
22969                for (int i = 0; i < K; i++) {
22970                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22971                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22972                    final int N = changes.size();
22973                    if (N == 0) {
22974                        pw.print("    "); pw.println("No packages changed");
22975                    } else {
22976                        for (int j = 0; j < N; j++) {
22977                            final String pkgName = changes.valueAt(j);
22978                            final int sequenceNumber = changes.keyAt(j);
22979                            pw.print("    ");
22980                            pw.print("seq=");
22981                            pw.print(sequenceNumber);
22982                            pw.print(", package=");
22983                            pw.println(pkgName);
22984                        }
22985                    }
22986                }
22987            }
22988
22989            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22990                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22991            }
22992
22993            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22994                // XXX should handle packageName != null by dumping only install data that
22995                // the given package is involved with.
22996                if (dumpState.onTitlePrinted()) pw.println();
22997
22998                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22999                ipw.println();
23000                ipw.println("Frozen packages:");
23001                ipw.increaseIndent();
23002                if (mFrozenPackages.size() == 0) {
23003                    ipw.println("(none)");
23004                } else {
23005                    for (int i = 0; i < mFrozenPackages.size(); i++) {
23006                        ipw.println(mFrozenPackages.valueAt(i));
23007                    }
23008                }
23009                ipw.decreaseIndent();
23010            }
23011
23012            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
23013                if (dumpState.onTitlePrinted()) pw.println();
23014
23015                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23016                ipw.println();
23017                ipw.println("Loaded volumes:");
23018                ipw.increaseIndent();
23019                if (mLoadedVolumes.size() == 0) {
23020                    ipw.println("(none)");
23021                } else {
23022                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
23023                        ipw.println(mLoadedVolumes.valueAt(i));
23024                    }
23025                }
23026                ipw.decreaseIndent();
23027            }
23028
23029            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
23030                if (dumpState.onTitlePrinted()) pw.println();
23031                dumpDexoptStateLPr(pw, packageName);
23032            }
23033
23034            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
23035                if (dumpState.onTitlePrinted()) pw.println();
23036                dumpCompilerStatsLPr(pw, packageName);
23037            }
23038
23039            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
23040                if (dumpState.onTitlePrinted()) pw.println();
23041                mSettings.dumpReadMessagesLPr(pw, dumpState);
23042
23043                pw.println();
23044                pw.println("Package warning messages:");
23045                BufferedReader in = null;
23046                String line = null;
23047                try {
23048                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23049                    while ((line = in.readLine()) != null) {
23050                        if (line.contains("ignored: updated version")) continue;
23051                        pw.println(line);
23052                    }
23053                } catch (IOException ignored) {
23054                } finally {
23055                    IoUtils.closeQuietly(in);
23056                }
23057            }
23058
23059            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
23060                BufferedReader in = null;
23061                String line = null;
23062                try {
23063                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23064                    while ((line = in.readLine()) != null) {
23065                        if (line.contains("ignored: updated version")) continue;
23066                        pw.print("msg,");
23067                        pw.println(line);
23068                    }
23069                } catch (IOException ignored) {
23070                } finally {
23071                    IoUtils.closeQuietly(in);
23072                }
23073            }
23074        }
23075
23076        // PackageInstaller should be called outside of mPackages lock
23077        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
23078            // XXX should handle packageName != null by dumping only install data that
23079            // the given package is involved with.
23080            if (dumpState.onTitlePrinted()) pw.println();
23081            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
23082        }
23083    }
23084
23085    private void dumpProto(FileDescriptor fd) {
23086        final ProtoOutputStream proto = new ProtoOutputStream(fd);
23087
23088        synchronized (mPackages) {
23089            final long requiredVerifierPackageToken =
23090                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
23091            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
23092            proto.write(
23093                    PackageServiceDumpProto.PackageShortProto.UID,
23094                    getPackageUid(
23095                            mRequiredVerifierPackage,
23096                            MATCH_DEBUG_TRIAGED_MISSING,
23097                            UserHandle.USER_SYSTEM));
23098            proto.end(requiredVerifierPackageToken);
23099
23100            if (mIntentFilterVerifierComponent != null) {
23101                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
23102                final long verifierPackageToken =
23103                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
23104                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
23105                proto.write(
23106                        PackageServiceDumpProto.PackageShortProto.UID,
23107                        getPackageUid(
23108                                verifierPackageName,
23109                                MATCH_DEBUG_TRIAGED_MISSING,
23110                                UserHandle.USER_SYSTEM));
23111                proto.end(verifierPackageToken);
23112            }
23113
23114            dumpSharedLibrariesProto(proto);
23115            dumpFeaturesProto(proto);
23116            mSettings.dumpPackagesProto(proto);
23117            mSettings.dumpSharedUsersProto(proto);
23118            dumpMessagesProto(proto);
23119        }
23120        proto.flush();
23121    }
23122
23123    private void dumpMessagesProto(ProtoOutputStream proto) {
23124        BufferedReader in = null;
23125        String line = null;
23126        try {
23127            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
23128            while ((line = in.readLine()) != null) {
23129                if (line.contains("ignored: updated version")) continue;
23130                proto.write(PackageServiceDumpProto.MESSAGES, line);
23131            }
23132        } catch (IOException ignored) {
23133        } finally {
23134            IoUtils.closeQuietly(in);
23135        }
23136    }
23137
23138    private void dumpFeaturesProto(ProtoOutputStream proto) {
23139        synchronized (mAvailableFeatures) {
23140            final int count = mAvailableFeatures.size();
23141            for (int i = 0; i < count; i++) {
23142                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
23143                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
23144                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
23145                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
23146                proto.end(featureToken);
23147            }
23148        }
23149    }
23150
23151    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
23152        final int count = mSharedLibraries.size();
23153        for (int i = 0; i < count; i++) {
23154            final String libName = mSharedLibraries.keyAt(i);
23155            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
23156            if (versionedLib == null) {
23157                continue;
23158            }
23159            final int versionCount = versionedLib.size();
23160            for (int j = 0; j < versionCount; j++) {
23161                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
23162                final long sharedLibraryToken =
23163                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
23164                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
23165                final boolean isJar = (libEntry.path != null);
23166                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
23167                if (isJar) {
23168                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
23169                } else {
23170                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
23171                }
23172                proto.end(sharedLibraryToken);
23173            }
23174        }
23175    }
23176
23177    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
23178        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23179        ipw.println();
23180        ipw.println("Dexopt state:");
23181        ipw.increaseIndent();
23182        Collection<PackageParser.Package> packages = null;
23183        if (packageName != null) {
23184            PackageParser.Package targetPackage = mPackages.get(packageName);
23185            if (targetPackage != null) {
23186                packages = Collections.singletonList(targetPackage);
23187            } else {
23188                ipw.println("Unable to find package: " + packageName);
23189                return;
23190            }
23191        } else {
23192            packages = mPackages.values();
23193        }
23194
23195        for (PackageParser.Package pkg : packages) {
23196            ipw.println("[" + pkg.packageName + "]");
23197            ipw.increaseIndent();
23198            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
23199                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
23200            ipw.decreaseIndent();
23201        }
23202    }
23203
23204    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
23205        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
23206        ipw.println();
23207        ipw.println("Compiler stats:");
23208        ipw.increaseIndent();
23209        Collection<PackageParser.Package> packages = null;
23210        if (packageName != null) {
23211            PackageParser.Package targetPackage = mPackages.get(packageName);
23212            if (targetPackage != null) {
23213                packages = Collections.singletonList(targetPackage);
23214            } else {
23215                ipw.println("Unable to find package: " + packageName);
23216                return;
23217            }
23218        } else {
23219            packages = mPackages.values();
23220        }
23221
23222        for (PackageParser.Package pkg : packages) {
23223            ipw.println("[" + pkg.packageName + "]");
23224            ipw.increaseIndent();
23225
23226            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
23227            if (stats == null) {
23228                ipw.println("(No recorded stats)");
23229            } else {
23230                stats.dump(ipw);
23231            }
23232            ipw.decreaseIndent();
23233        }
23234    }
23235
23236    private String dumpDomainString(String packageName) {
23237        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
23238                .getList();
23239        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
23240
23241        ArraySet<String> result = new ArraySet<>();
23242        if (iviList.size() > 0) {
23243            for (IntentFilterVerificationInfo ivi : iviList) {
23244                for (String host : ivi.getDomains()) {
23245                    result.add(host);
23246                }
23247            }
23248        }
23249        if (filters != null && filters.size() > 0) {
23250            for (IntentFilter filter : filters) {
23251                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
23252                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
23253                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
23254                    result.addAll(filter.getHostsList());
23255                }
23256            }
23257        }
23258
23259        StringBuilder sb = new StringBuilder(result.size() * 16);
23260        for (String domain : result) {
23261            if (sb.length() > 0) sb.append(" ");
23262            sb.append(domain);
23263        }
23264        return sb.toString();
23265    }
23266
23267    // ------- apps on sdcard specific code -------
23268    static final boolean DEBUG_SD_INSTALL = false;
23269
23270    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23271
23272    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23273
23274    private boolean mMediaMounted = false;
23275
23276    static String getEncryptKey() {
23277        try {
23278            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23279                    SD_ENCRYPTION_KEYSTORE_NAME);
23280            if (sdEncKey == null) {
23281                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23282                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23283                if (sdEncKey == null) {
23284                    Slog.e(TAG, "Failed to create encryption keys");
23285                    return null;
23286                }
23287            }
23288            return sdEncKey;
23289        } catch (NoSuchAlgorithmException nsae) {
23290            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23291            return null;
23292        } catch (IOException ioe) {
23293            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23294            return null;
23295        }
23296    }
23297
23298    /*
23299     * Update media status on PackageManager.
23300     */
23301    @Override
23302    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23303        enforceSystemOrRoot("Media status can only be updated by the system");
23304        // reader; this apparently protects mMediaMounted, but should probably
23305        // be a different lock in that case.
23306        synchronized (mPackages) {
23307            Log.i(TAG, "Updating external media status from "
23308                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23309                    + (mediaStatus ? "mounted" : "unmounted"));
23310            if (DEBUG_SD_INSTALL)
23311                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23312                        + ", mMediaMounted=" + mMediaMounted);
23313            if (mediaStatus == mMediaMounted) {
23314                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23315                        : 0, -1);
23316                mHandler.sendMessage(msg);
23317                return;
23318            }
23319            mMediaMounted = mediaStatus;
23320        }
23321        // Queue up an async operation since the package installation may take a
23322        // little while.
23323        mHandler.post(new Runnable() {
23324            public void run() {
23325                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23326            }
23327        });
23328    }
23329
23330    /**
23331     * Called by StorageManagerService when the initial ASECs to scan are available.
23332     * Should block until all the ASEC containers are finished being scanned.
23333     */
23334    public void scanAvailableAsecs() {
23335        updateExternalMediaStatusInner(true, false, false);
23336    }
23337
23338    /*
23339     * Collect information of applications on external media, map them against
23340     * existing containers and update information based on current mount status.
23341     * Please note that we always have to report status if reportStatus has been
23342     * set to true especially when unloading packages.
23343     */
23344    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23345            boolean externalStorage) {
23346        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23347        int[] uidArr = EmptyArray.INT;
23348
23349        final String[] list = PackageHelper.getSecureContainerList();
23350        if (ArrayUtils.isEmpty(list)) {
23351            Log.i(TAG, "No secure containers found");
23352        } else {
23353            // Process list of secure containers and categorize them
23354            // as active or stale based on their package internal state.
23355
23356            // reader
23357            synchronized (mPackages) {
23358                for (String cid : list) {
23359                    // Leave stages untouched for now; installer service owns them
23360                    if (PackageInstallerService.isStageName(cid)) continue;
23361
23362                    if (DEBUG_SD_INSTALL)
23363                        Log.i(TAG, "Processing container " + cid);
23364                    String pkgName = getAsecPackageName(cid);
23365                    if (pkgName == null) {
23366                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23367                        continue;
23368                    }
23369                    if (DEBUG_SD_INSTALL)
23370                        Log.i(TAG, "Looking for pkg : " + pkgName);
23371
23372                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23373                    if (ps == null) {
23374                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23375                        continue;
23376                    }
23377
23378                    /*
23379                     * Skip packages that are not external if we're unmounting
23380                     * external storage.
23381                     */
23382                    if (externalStorage && !isMounted && !isExternal(ps)) {
23383                        continue;
23384                    }
23385
23386                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23387                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23388                    // The package status is changed only if the code path
23389                    // matches between settings and the container id.
23390                    if (ps.codePathString != null
23391                            && ps.codePathString.startsWith(args.getCodePath())) {
23392                        if (DEBUG_SD_INSTALL) {
23393                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23394                                    + " at code path: " + ps.codePathString);
23395                        }
23396
23397                        // We do have a valid package installed on sdcard
23398                        processCids.put(args, ps.codePathString);
23399                        final int uid = ps.appId;
23400                        if (uid != -1) {
23401                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23402                        }
23403                    } else {
23404                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23405                                + ps.codePathString);
23406                    }
23407                }
23408            }
23409
23410            Arrays.sort(uidArr);
23411        }
23412
23413        // Process packages with valid entries.
23414        if (isMounted) {
23415            if (DEBUG_SD_INSTALL)
23416                Log.i(TAG, "Loading packages");
23417            loadMediaPackages(processCids, uidArr, externalStorage);
23418            startCleaningPackages();
23419            mInstallerService.onSecureContainersAvailable();
23420        } else {
23421            if (DEBUG_SD_INSTALL)
23422                Log.i(TAG, "Unloading packages");
23423            unloadMediaPackages(processCids, uidArr, reportStatus);
23424        }
23425    }
23426
23427    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23428            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23429        final int size = infos.size();
23430        final String[] packageNames = new String[size];
23431        final int[] packageUids = new int[size];
23432        for (int i = 0; i < size; i++) {
23433            final ApplicationInfo info = infos.get(i);
23434            packageNames[i] = info.packageName;
23435            packageUids[i] = info.uid;
23436        }
23437        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23438                finishedReceiver);
23439    }
23440
23441    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23442            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23443        sendResourcesChangedBroadcast(mediaStatus, replacing,
23444                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23445    }
23446
23447    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23448            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23449        int size = pkgList.length;
23450        if (size > 0) {
23451            // Send broadcasts here
23452            Bundle extras = new Bundle();
23453            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23454            if (uidArr != null) {
23455                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23456            }
23457            if (replacing) {
23458                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23459            }
23460            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23461                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23462            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23463        }
23464    }
23465
23466   /*
23467     * Look at potentially valid container ids from processCids If package
23468     * information doesn't match the one on record or package scanning fails,
23469     * the cid is added to list of removeCids. We currently don't delete stale
23470     * containers.
23471     */
23472    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23473            boolean externalStorage) {
23474        ArrayList<String> pkgList = new ArrayList<String>();
23475        Set<AsecInstallArgs> keys = processCids.keySet();
23476
23477        for (AsecInstallArgs args : keys) {
23478            String codePath = processCids.get(args);
23479            if (DEBUG_SD_INSTALL)
23480                Log.i(TAG, "Loading container : " + args.cid);
23481            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23482            try {
23483                // Make sure there are no container errors first.
23484                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23485                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23486                            + " when installing from sdcard");
23487                    continue;
23488                }
23489                // Check code path here.
23490                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23491                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23492                            + " does not match one in settings " + codePath);
23493                    continue;
23494                }
23495                // Parse package
23496                int parseFlags = mDefParseFlags;
23497                if (args.isExternalAsec()) {
23498                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23499                }
23500                if (args.isFwdLocked()) {
23501                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23502                }
23503
23504                synchronized (mInstallLock) {
23505                    PackageParser.Package pkg = null;
23506                    try {
23507                        // Sadly we don't know the package name yet to freeze it
23508                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23509                                SCAN_IGNORE_FROZEN, 0, null);
23510                    } catch (PackageManagerException e) {
23511                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23512                    }
23513                    // Scan the package
23514                    if (pkg != null) {
23515                        /*
23516                         * TODO why is the lock being held? doPostInstall is
23517                         * called in other places without the lock. This needs
23518                         * to be straightened out.
23519                         */
23520                        // writer
23521                        synchronized (mPackages) {
23522                            retCode = PackageManager.INSTALL_SUCCEEDED;
23523                            pkgList.add(pkg.packageName);
23524                            // Post process args
23525                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23526                                    pkg.applicationInfo.uid);
23527                        }
23528                    } else {
23529                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23530                    }
23531                }
23532
23533            } finally {
23534                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23535                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23536                }
23537            }
23538        }
23539        // writer
23540        synchronized (mPackages) {
23541            // If the platform SDK has changed since the last time we booted,
23542            // we need to re-grant app permission to catch any new ones that
23543            // appear. This is really a hack, and means that apps can in some
23544            // cases get permissions that the user didn't initially explicitly
23545            // allow... it would be nice to have some better way to handle
23546            // this situation.
23547            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23548                    : mSettings.getInternalVersion();
23549            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23550                    : StorageManager.UUID_PRIVATE_INTERNAL;
23551
23552            int updateFlags = UPDATE_PERMISSIONS_ALL;
23553            if (ver.sdkVersion != mSdkVersion) {
23554                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23555                        + mSdkVersion + "; regranting permissions for external");
23556                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23557            }
23558            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23559
23560            // Yay, everything is now upgraded
23561            ver.forceCurrent();
23562
23563            // can downgrade to reader
23564            // Persist settings
23565            mSettings.writeLPr();
23566        }
23567        // Send a broadcast to let everyone know we are done processing
23568        if (pkgList.size() > 0) {
23569            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23570        }
23571    }
23572
23573   /*
23574     * Utility method to unload a list of specified containers
23575     */
23576    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23577        // Just unmount all valid containers.
23578        for (AsecInstallArgs arg : cidArgs) {
23579            synchronized (mInstallLock) {
23580                arg.doPostDeleteLI(false);
23581           }
23582       }
23583   }
23584
23585    /*
23586     * Unload packages mounted on external media. This involves deleting package
23587     * data from internal structures, sending broadcasts about disabled packages,
23588     * gc'ing to free up references, unmounting all secure containers
23589     * corresponding to packages on external media, and posting a
23590     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23591     * that we always have to post this message if status has been requested no
23592     * matter what.
23593     */
23594    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23595            final boolean reportStatus) {
23596        if (DEBUG_SD_INSTALL)
23597            Log.i(TAG, "unloading media packages");
23598        ArrayList<String> pkgList = new ArrayList<String>();
23599        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23600        final Set<AsecInstallArgs> keys = processCids.keySet();
23601        for (AsecInstallArgs args : keys) {
23602            String pkgName = args.getPackageName();
23603            if (DEBUG_SD_INSTALL)
23604                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23605            // Delete package internally
23606            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23607            synchronized (mInstallLock) {
23608                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23609                final boolean res;
23610                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23611                        "unloadMediaPackages")) {
23612                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23613                            null);
23614                }
23615                if (res) {
23616                    pkgList.add(pkgName);
23617                } else {
23618                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23619                    failedList.add(args);
23620                }
23621            }
23622        }
23623
23624        // reader
23625        synchronized (mPackages) {
23626            // We didn't update the settings after removing each package;
23627            // write them now for all packages.
23628            mSettings.writeLPr();
23629        }
23630
23631        // We have to absolutely send UPDATED_MEDIA_STATUS only
23632        // after confirming that all the receivers processed the ordered
23633        // broadcast when packages get disabled, force a gc to clean things up.
23634        // and unload all the containers.
23635        if (pkgList.size() > 0) {
23636            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23637                    new IIntentReceiver.Stub() {
23638                public void performReceive(Intent intent, int resultCode, String data,
23639                        Bundle extras, boolean ordered, boolean sticky,
23640                        int sendingUser) throws RemoteException {
23641                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23642                            reportStatus ? 1 : 0, 1, keys);
23643                    mHandler.sendMessage(msg);
23644                }
23645            });
23646        } else {
23647            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23648                    keys);
23649            mHandler.sendMessage(msg);
23650        }
23651    }
23652
23653    private void loadPrivatePackages(final VolumeInfo vol) {
23654        mHandler.post(new Runnable() {
23655            @Override
23656            public void run() {
23657                loadPrivatePackagesInner(vol);
23658            }
23659        });
23660    }
23661
23662    private void loadPrivatePackagesInner(VolumeInfo vol) {
23663        final String volumeUuid = vol.fsUuid;
23664        if (TextUtils.isEmpty(volumeUuid)) {
23665            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23666            return;
23667        }
23668
23669        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23670        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23671        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23672
23673        final VersionInfo ver;
23674        final List<PackageSetting> packages;
23675        synchronized (mPackages) {
23676            ver = mSettings.findOrCreateVersion(volumeUuid);
23677            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23678        }
23679
23680        for (PackageSetting ps : packages) {
23681            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23682            synchronized (mInstallLock) {
23683                final PackageParser.Package pkg;
23684                try {
23685                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23686                    loaded.add(pkg.applicationInfo);
23687
23688                } catch (PackageManagerException e) {
23689                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23690                }
23691
23692                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23693                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23694                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23695                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23696                }
23697            }
23698        }
23699
23700        // Reconcile app data for all started/unlocked users
23701        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23702        final UserManager um = mContext.getSystemService(UserManager.class);
23703        UserManagerInternal umInternal = getUserManagerInternal();
23704        for (UserInfo user : um.getUsers()) {
23705            final int flags;
23706            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23707                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23708            } else if (umInternal.isUserRunning(user.id)) {
23709                flags = StorageManager.FLAG_STORAGE_DE;
23710            } else {
23711                continue;
23712            }
23713
23714            try {
23715                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23716                synchronized (mInstallLock) {
23717                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23718                }
23719            } catch (IllegalStateException e) {
23720                // Device was probably ejected, and we'll process that event momentarily
23721                Slog.w(TAG, "Failed to prepare storage: " + e);
23722            }
23723        }
23724
23725        synchronized (mPackages) {
23726            int updateFlags = UPDATE_PERMISSIONS_ALL;
23727            if (ver.sdkVersion != mSdkVersion) {
23728                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23729                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23730                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23731            }
23732            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23733
23734            // Yay, everything is now upgraded
23735            ver.forceCurrent();
23736
23737            mSettings.writeLPr();
23738        }
23739
23740        for (PackageFreezer freezer : freezers) {
23741            freezer.close();
23742        }
23743
23744        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23745        sendResourcesChangedBroadcast(true, false, loaded, null);
23746        mLoadedVolumes.add(vol.getId());
23747    }
23748
23749    private void unloadPrivatePackages(final VolumeInfo vol) {
23750        mHandler.post(new Runnable() {
23751            @Override
23752            public void run() {
23753                unloadPrivatePackagesInner(vol);
23754            }
23755        });
23756    }
23757
23758    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23759        final String volumeUuid = vol.fsUuid;
23760        if (TextUtils.isEmpty(volumeUuid)) {
23761            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23762            return;
23763        }
23764
23765        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23766        synchronized (mInstallLock) {
23767        synchronized (mPackages) {
23768            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23769            for (PackageSetting ps : packages) {
23770                if (ps.pkg == null) continue;
23771
23772                final ApplicationInfo info = ps.pkg.applicationInfo;
23773                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23774                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23775
23776                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23777                        "unloadPrivatePackagesInner")) {
23778                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23779                            false, null)) {
23780                        unloaded.add(info);
23781                    } else {
23782                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23783                    }
23784                }
23785
23786                // Try very hard to release any references to this package
23787                // so we don't risk the system server being killed due to
23788                // open FDs
23789                AttributeCache.instance().removePackage(ps.name);
23790            }
23791
23792            mSettings.writeLPr();
23793        }
23794        }
23795
23796        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23797        sendResourcesChangedBroadcast(false, false, unloaded, null);
23798        mLoadedVolumes.remove(vol.getId());
23799
23800        // Try very hard to release any references to this path so we don't risk
23801        // the system server being killed due to open FDs
23802        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23803
23804        for (int i = 0; i < 3; i++) {
23805            System.gc();
23806            System.runFinalization();
23807        }
23808    }
23809
23810    private void assertPackageKnown(String volumeUuid, String packageName)
23811            throws PackageManagerException {
23812        synchronized (mPackages) {
23813            // Normalize package name to handle renamed packages
23814            packageName = normalizePackageNameLPr(packageName);
23815
23816            final PackageSetting ps = mSettings.mPackages.get(packageName);
23817            if (ps == null) {
23818                throw new PackageManagerException("Package " + packageName + " is unknown");
23819            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23820                throw new PackageManagerException(
23821                        "Package " + packageName + " found on unknown volume " + volumeUuid
23822                                + "; expected volume " + ps.volumeUuid);
23823            }
23824        }
23825    }
23826
23827    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23828            throws PackageManagerException {
23829        synchronized (mPackages) {
23830            // Normalize package name to handle renamed packages
23831            packageName = normalizePackageNameLPr(packageName);
23832
23833            final PackageSetting ps = mSettings.mPackages.get(packageName);
23834            if (ps == null) {
23835                throw new PackageManagerException("Package " + packageName + " is unknown");
23836            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23837                throw new PackageManagerException(
23838                        "Package " + packageName + " found on unknown volume " + volumeUuid
23839                                + "; expected volume " + ps.volumeUuid);
23840            } else if (!ps.getInstalled(userId)) {
23841                throw new PackageManagerException(
23842                        "Package " + packageName + " not installed for user " + userId);
23843            }
23844        }
23845    }
23846
23847    private List<String> collectAbsoluteCodePaths() {
23848        synchronized (mPackages) {
23849            List<String> codePaths = new ArrayList<>();
23850            final int packageCount = mSettings.mPackages.size();
23851            for (int i = 0; i < packageCount; i++) {
23852                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23853                codePaths.add(ps.codePath.getAbsolutePath());
23854            }
23855            return codePaths;
23856        }
23857    }
23858
23859    /**
23860     * Examine all apps present on given mounted volume, and destroy apps that
23861     * aren't expected, either due to uninstallation or reinstallation on
23862     * another volume.
23863     */
23864    private void reconcileApps(String volumeUuid) {
23865        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23866        List<File> filesToDelete = null;
23867
23868        final File[] files = FileUtils.listFilesOrEmpty(
23869                Environment.getDataAppDirectory(volumeUuid));
23870        for (File file : files) {
23871            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23872                    && !PackageInstallerService.isStageName(file.getName());
23873            if (!isPackage) {
23874                // Ignore entries which are not packages
23875                continue;
23876            }
23877
23878            String absolutePath = file.getAbsolutePath();
23879
23880            boolean pathValid = false;
23881            final int absoluteCodePathCount = absoluteCodePaths.size();
23882            for (int i = 0; i < absoluteCodePathCount; i++) {
23883                String absoluteCodePath = absoluteCodePaths.get(i);
23884                if (absolutePath.startsWith(absoluteCodePath)) {
23885                    pathValid = true;
23886                    break;
23887                }
23888            }
23889
23890            if (!pathValid) {
23891                if (filesToDelete == null) {
23892                    filesToDelete = new ArrayList<>();
23893                }
23894                filesToDelete.add(file);
23895            }
23896        }
23897
23898        if (filesToDelete != null) {
23899            final int fileToDeleteCount = filesToDelete.size();
23900            for (int i = 0; i < fileToDeleteCount; i++) {
23901                File fileToDelete = filesToDelete.get(i);
23902                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23903                synchronized (mInstallLock) {
23904                    removeCodePathLI(fileToDelete);
23905                }
23906            }
23907        }
23908    }
23909
23910    /**
23911     * Reconcile all app data for the given user.
23912     * <p>
23913     * Verifies that directories exist and that ownership and labeling is
23914     * correct for all installed apps on all mounted volumes.
23915     */
23916    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23917        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23918        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23919            final String volumeUuid = vol.getFsUuid();
23920            synchronized (mInstallLock) {
23921                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23922            }
23923        }
23924    }
23925
23926    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23927            boolean migrateAppData) {
23928        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23929    }
23930
23931    /**
23932     * Reconcile all app data on given mounted volume.
23933     * <p>
23934     * Destroys app data that isn't expected, either due to uninstallation or
23935     * reinstallation on another volume.
23936     * <p>
23937     * Verifies that directories exist and that ownership and labeling is
23938     * correct for all installed apps.
23939     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23940     */
23941    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23942            boolean migrateAppData, boolean onlyCoreApps) {
23943        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23944                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23945        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23946
23947        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23948        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23949
23950        // First look for stale data that doesn't belong, and check if things
23951        // have changed since we did our last restorecon
23952        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23953            if (StorageManager.isFileEncryptedNativeOrEmulated()
23954                    && !StorageManager.isUserKeyUnlocked(userId)) {
23955                throw new RuntimeException(
23956                        "Yikes, someone asked us to reconcile CE storage while " + userId
23957                                + " was still locked; this would have caused massive data loss!");
23958            }
23959
23960            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23961            for (File file : files) {
23962                final String packageName = file.getName();
23963                try {
23964                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23965                } catch (PackageManagerException e) {
23966                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23967                    try {
23968                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23969                                StorageManager.FLAG_STORAGE_CE, 0);
23970                    } catch (InstallerException e2) {
23971                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23972                    }
23973                }
23974            }
23975        }
23976        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23977            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23978            for (File file : files) {
23979                final String packageName = file.getName();
23980                try {
23981                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23982                } catch (PackageManagerException e) {
23983                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23984                    try {
23985                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23986                                StorageManager.FLAG_STORAGE_DE, 0);
23987                    } catch (InstallerException e2) {
23988                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23989                    }
23990                }
23991            }
23992        }
23993
23994        // Ensure that data directories are ready to roll for all packages
23995        // installed for this volume and user
23996        final List<PackageSetting> packages;
23997        synchronized (mPackages) {
23998            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23999        }
24000        int preparedCount = 0;
24001        for (PackageSetting ps : packages) {
24002            final String packageName = ps.name;
24003            if (ps.pkg == null) {
24004                Slog.w(TAG, "Odd, missing scanned package " + packageName);
24005                // TODO: might be due to legacy ASEC apps; we should circle back
24006                // and reconcile again once they're scanned
24007                continue;
24008            }
24009            // Skip non-core apps if requested
24010            if (onlyCoreApps && !ps.pkg.coreApp) {
24011                result.add(packageName);
24012                continue;
24013            }
24014
24015            if (ps.getInstalled(userId)) {
24016                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
24017                preparedCount++;
24018            }
24019        }
24020
24021        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
24022        return result;
24023    }
24024
24025    /**
24026     * Prepare app data for the given app just after it was installed or
24027     * upgraded. This method carefully only touches users that it's installed
24028     * for, and it forces a restorecon to handle any seinfo changes.
24029     * <p>
24030     * Verifies that directories exist and that ownership and labeling is
24031     * correct for all installed apps. If there is an ownership mismatch, it
24032     * will try recovering system apps by wiping data; third-party app data is
24033     * left intact.
24034     * <p>
24035     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
24036     */
24037    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
24038        final PackageSetting ps;
24039        synchronized (mPackages) {
24040            ps = mSettings.mPackages.get(pkg.packageName);
24041            mSettings.writeKernelMappingLPr(ps);
24042        }
24043
24044        final UserManager um = mContext.getSystemService(UserManager.class);
24045        UserManagerInternal umInternal = getUserManagerInternal();
24046        for (UserInfo user : um.getUsers()) {
24047            final int flags;
24048            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
24049                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
24050            } else if (umInternal.isUserRunning(user.id)) {
24051                flags = StorageManager.FLAG_STORAGE_DE;
24052            } else {
24053                continue;
24054            }
24055
24056            if (ps.getInstalled(user.id)) {
24057                // TODO: when user data is locked, mark that we're still dirty
24058                prepareAppDataLIF(pkg, user.id, flags);
24059            }
24060        }
24061    }
24062
24063    /**
24064     * Prepare app data for the given app.
24065     * <p>
24066     * Verifies that directories exist and that ownership and labeling is
24067     * correct for all installed apps. If there is an ownership mismatch, this
24068     * will try recovering system apps by wiping data; third-party app data is
24069     * left intact.
24070     */
24071    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
24072        if (pkg == null) {
24073            Slog.wtf(TAG, "Package was null!", new Throwable());
24074            return;
24075        }
24076        prepareAppDataLeafLIF(pkg, userId, flags);
24077        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24078        for (int i = 0; i < childCount; i++) {
24079            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
24080        }
24081    }
24082
24083    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
24084            boolean maybeMigrateAppData) {
24085        prepareAppDataLIF(pkg, userId, flags);
24086
24087        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
24088            // We may have just shuffled around app data directories, so
24089            // prepare them one more time
24090            prepareAppDataLIF(pkg, userId, flags);
24091        }
24092    }
24093
24094    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24095        if (DEBUG_APP_DATA) {
24096            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
24097                    + Integer.toHexString(flags));
24098        }
24099
24100        final String volumeUuid = pkg.volumeUuid;
24101        final String packageName = pkg.packageName;
24102        final ApplicationInfo app = pkg.applicationInfo;
24103        final int appId = UserHandle.getAppId(app.uid);
24104
24105        Preconditions.checkNotNull(app.seInfo);
24106
24107        long ceDataInode = -1;
24108        try {
24109            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24110                    appId, app.seInfo, app.targetSdkVersion);
24111        } catch (InstallerException e) {
24112            if (app.isSystemApp()) {
24113                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
24114                        + ", but trying to recover: " + e);
24115                destroyAppDataLeafLIF(pkg, userId, flags);
24116                try {
24117                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
24118                            appId, app.seInfo, app.targetSdkVersion);
24119                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
24120                } catch (InstallerException e2) {
24121                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
24122                }
24123            } else {
24124                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
24125            }
24126        }
24127
24128        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
24129            // TODO: mark this structure as dirty so we persist it!
24130            synchronized (mPackages) {
24131                final PackageSetting ps = mSettings.mPackages.get(packageName);
24132                if (ps != null) {
24133                    ps.setCeDataInode(ceDataInode, userId);
24134                }
24135            }
24136        }
24137
24138        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24139    }
24140
24141    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
24142        if (pkg == null) {
24143            Slog.wtf(TAG, "Package was null!", new Throwable());
24144            return;
24145        }
24146        prepareAppDataContentsLeafLIF(pkg, userId, flags);
24147        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
24148        for (int i = 0; i < childCount; i++) {
24149            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
24150        }
24151    }
24152
24153    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
24154        final String volumeUuid = pkg.volumeUuid;
24155        final String packageName = pkg.packageName;
24156        final ApplicationInfo app = pkg.applicationInfo;
24157
24158        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
24159            // Create a native library symlink only if we have native libraries
24160            // and if the native libraries are 32 bit libraries. We do not provide
24161            // this symlink for 64 bit libraries.
24162            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
24163                final String nativeLibPath = app.nativeLibraryDir;
24164                try {
24165                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
24166                            nativeLibPath, userId);
24167                } catch (InstallerException e) {
24168                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
24169                }
24170            }
24171        }
24172    }
24173
24174    /**
24175     * For system apps on non-FBE devices, this method migrates any existing
24176     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
24177     * requested by the app.
24178     */
24179    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
24180        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
24181                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
24182            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
24183                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
24184            try {
24185                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
24186                        storageTarget);
24187            } catch (InstallerException e) {
24188                logCriticalInfo(Log.WARN,
24189                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
24190            }
24191            return true;
24192        } else {
24193            return false;
24194        }
24195    }
24196
24197    public PackageFreezer freezePackage(String packageName, String killReason) {
24198        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
24199    }
24200
24201    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
24202        return new PackageFreezer(packageName, userId, killReason);
24203    }
24204
24205    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
24206            String killReason) {
24207        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
24208    }
24209
24210    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
24211            String killReason) {
24212        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
24213            return new PackageFreezer();
24214        } else {
24215            return freezePackage(packageName, userId, killReason);
24216        }
24217    }
24218
24219    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
24220            String killReason) {
24221        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
24222    }
24223
24224    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
24225            String killReason) {
24226        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
24227            return new PackageFreezer();
24228        } else {
24229            return freezePackage(packageName, userId, killReason);
24230        }
24231    }
24232
24233    /**
24234     * Class that freezes and kills the given package upon creation, and
24235     * unfreezes it upon closing. This is typically used when doing surgery on
24236     * app code/data to prevent the app from running while you're working.
24237     */
24238    private class PackageFreezer implements AutoCloseable {
24239        private final String mPackageName;
24240        private final PackageFreezer[] mChildren;
24241
24242        private final boolean mWeFroze;
24243
24244        private final AtomicBoolean mClosed = new AtomicBoolean();
24245        private final CloseGuard mCloseGuard = CloseGuard.get();
24246
24247        /**
24248         * Create and return a stub freezer that doesn't actually do anything,
24249         * typically used when someone requested
24250         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
24251         * {@link PackageManager#DELETE_DONT_KILL_APP}.
24252         */
24253        public PackageFreezer() {
24254            mPackageName = null;
24255            mChildren = null;
24256            mWeFroze = false;
24257            mCloseGuard.open("close");
24258        }
24259
24260        public PackageFreezer(String packageName, int userId, String killReason) {
24261            synchronized (mPackages) {
24262                mPackageName = packageName;
24263                mWeFroze = mFrozenPackages.add(mPackageName);
24264
24265                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24266                if (ps != null) {
24267                    killApplication(ps.name, ps.appId, userId, killReason);
24268                }
24269
24270                final PackageParser.Package p = mPackages.get(packageName);
24271                if (p != null && p.childPackages != null) {
24272                    final int N = p.childPackages.size();
24273                    mChildren = new PackageFreezer[N];
24274                    for (int i = 0; i < N; i++) {
24275                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24276                                userId, killReason);
24277                    }
24278                } else {
24279                    mChildren = null;
24280                }
24281            }
24282            mCloseGuard.open("close");
24283        }
24284
24285        @Override
24286        protected void finalize() throws Throwable {
24287            try {
24288                if (mCloseGuard != null) {
24289                    mCloseGuard.warnIfOpen();
24290                }
24291
24292                close();
24293            } finally {
24294                super.finalize();
24295            }
24296        }
24297
24298        @Override
24299        public void close() {
24300            mCloseGuard.close();
24301            if (mClosed.compareAndSet(false, true)) {
24302                synchronized (mPackages) {
24303                    if (mWeFroze) {
24304                        mFrozenPackages.remove(mPackageName);
24305                    }
24306
24307                    if (mChildren != null) {
24308                        for (PackageFreezer freezer : mChildren) {
24309                            freezer.close();
24310                        }
24311                    }
24312                }
24313            }
24314        }
24315    }
24316
24317    /**
24318     * Verify that given package is currently frozen.
24319     */
24320    private void checkPackageFrozen(String packageName) {
24321        synchronized (mPackages) {
24322            if (!mFrozenPackages.contains(packageName)) {
24323                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24324            }
24325        }
24326    }
24327
24328    @Override
24329    public int movePackage(final String packageName, final String volumeUuid) {
24330        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24331
24332        final int callingUid = Binder.getCallingUid();
24333        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24334        final int moveId = mNextMoveId.getAndIncrement();
24335        mHandler.post(new Runnable() {
24336            @Override
24337            public void run() {
24338                try {
24339                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24340                } catch (PackageManagerException e) {
24341                    Slog.w(TAG, "Failed to move " + packageName, e);
24342                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24343                }
24344            }
24345        });
24346        return moveId;
24347    }
24348
24349    private void movePackageInternal(final String packageName, final String volumeUuid,
24350            final int moveId, final int callingUid, UserHandle user)
24351                    throws PackageManagerException {
24352        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24353        final PackageManager pm = mContext.getPackageManager();
24354
24355        final boolean currentAsec;
24356        final String currentVolumeUuid;
24357        final File codeFile;
24358        final String installerPackageName;
24359        final String packageAbiOverride;
24360        final int appId;
24361        final String seinfo;
24362        final String label;
24363        final int targetSdkVersion;
24364        final PackageFreezer freezer;
24365        final int[] installedUserIds;
24366
24367        // reader
24368        synchronized (mPackages) {
24369            final PackageParser.Package pkg = mPackages.get(packageName);
24370            final PackageSetting ps = mSettings.mPackages.get(packageName);
24371            if (pkg == null
24372                    || ps == null
24373                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24374                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24375            }
24376            if (pkg.applicationInfo.isSystemApp()) {
24377                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24378                        "Cannot move system application");
24379            }
24380
24381            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24382            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24383                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24384            if (isInternalStorage && !allow3rdPartyOnInternal) {
24385                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24386                        "3rd party apps are not allowed on internal storage");
24387            }
24388
24389            if (pkg.applicationInfo.isExternalAsec()) {
24390                currentAsec = true;
24391                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24392            } else if (pkg.applicationInfo.isForwardLocked()) {
24393                currentAsec = true;
24394                currentVolumeUuid = "forward_locked";
24395            } else {
24396                currentAsec = false;
24397                currentVolumeUuid = ps.volumeUuid;
24398
24399                final File probe = new File(pkg.codePath);
24400                final File probeOat = new File(probe, "oat");
24401                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24402                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24403                            "Move only supported for modern cluster style installs");
24404                }
24405            }
24406
24407            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24408                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24409                        "Package already moved to " + volumeUuid);
24410            }
24411            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24412                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24413                        "Device admin cannot be moved");
24414            }
24415
24416            if (mFrozenPackages.contains(packageName)) {
24417                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24418                        "Failed to move already frozen package");
24419            }
24420
24421            codeFile = new File(pkg.codePath);
24422            installerPackageName = ps.installerPackageName;
24423            packageAbiOverride = ps.cpuAbiOverrideString;
24424            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24425            seinfo = pkg.applicationInfo.seInfo;
24426            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24427            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24428            freezer = freezePackage(packageName, "movePackageInternal");
24429            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24430        }
24431
24432        final Bundle extras = new Bundle();
24433        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24434        extras.putString(Intent.EXTRA_TITLE, label);
24435        mMoveCallbacks.notifyCreated(moveId, extras);
24436
24437        int installFlags;
24438        final boolean moveCompleteApp;
24439        final File measurePath;
24440
24441        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24442            installFlags = INSTALL_INTERNAL;
24443            moveCompleteApp = !currentAsec;
24444            measurePath = Environment.getDataAppDirectory(volumeUuid);
24445        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24446            installFlags = INSTALL_EXTERNAL;
24447            moveCompleteApp = false;
24448            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24449        } else {
24450            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24451            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24452                    || !volume.isMountedWritable()) {
24453                freezer.close();
24454                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24455                        "Move location not mounted private volume");
24456            }
24457
24458            Preconditions.checkState(!currentAsec);
24459
24460            installFlags = INSTALL_INTERNAL;
24461            moveCompleteApp = true;
24462            measurePath = Environment.getDataAppDirectory(volumeUuid);
24463        }
24464
24465        // If we're moving app data around, we need all the users unlocked
24466        if (moveCompleteApp) {
24467            for (int userId : installedUserIds) {
24468                if (StorageManager.isFileEncryptedNativeOrEmulated()
24469                        && !StorageManager.isUserKeyUnlocked(userId)) {
24470                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24471                            "User " + userId + " must be unlocked");
24472                }
24473            }
24474        }
24475
24476        final PackageStats stats = new PackageStats(null, -1);
24477        synchronized (mInstaller) {
24478            for (int userId : installedUserIds) {
24479                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24480                    freezer.close();
24481                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24482                            "Failed to measure package size");
24483                }
24484            }
24485        }
24486
24487        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24488                + stats.dataSize);
24489
24490        final long startFreeBytes = measurePath.getUsableSpace();
24491        final long sizeBytes;
24492        if (moveCompleteApp) {
24493            sizeBytes = stats.codeSize + stats.dataSize;
24494        } else {
24495            sizeBytes = stats.codeSize;
24496        }
24497
24498        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24499            freezer.close();
24500            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24501                    "Not enough free space to move");
24502        }
24503
24504        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24505
24506        final CountDownLatch installedLatch = new CountDownLatch(1);
24507        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24508            @Override
24509            public void onUserActionRequired(Intent intent) throws RemoteException {
24510                throw new IllegalStateException();
24511            }
24512
24513            @Override
24514            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24515                    Bundle extras) throws RemoteException {
24516                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24517                        + PackageManager.installStatusToString(returnCode, msg));
24518
24519                installedLatch.countDown();
24520                freezer.close();
24521
24522                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24523                switch (status) {
24524                    case PackageInstaller.STATUS_SUCCESS:
24525                        mMoveCallbacks.notifyStatusChanged(moveId,
24526                                PackageManager.MOVE_SUCCEEDED);
24527                        break;
24528                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24529                        mMoveCallbacks.notifyStatusChanged(moveId,
24530                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24531                        break;
24532                    default:
24533                        mMoveCallbacks.notifyStatusChanged(moveId,
24534                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24535                        break;
24536                }
24537            }
24538        };
24539
24540        final MoveInfo move;
24541        if (moveCompleteApp) {
24542            // Kick off a thread to report progress estimates
24543            new Thread() {
24544                @Override
24545                public void run() {
24546                    while (true) {
24547                        try {
24548                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24549                                break;
24550                            }
24551                        } catch (InterruptedException ignored) {
24552                        }
24553
24554                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24555                        final int progress = 10 + (int) MathUtils.constrain(
24556                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24557                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24558                    }
24559                }
24560            }.start();
24561
24562            final String dataAppName = codeFile.getName();
24563            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24564                    dataAppName, appId, seinfo, targetSdkVersion);
24565        } else {
24566            move = null;
24567        }
24568
24569        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24570
24571        final Message msg = mHandler.obtainMessage(INIT_COPY);
24572        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24573        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24574                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24575                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24576                PackageManager.INSTALL_REASON_UNKNOWN);
24577        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24578        msg.obj = params;
24579
24580        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24581                System.identityHashCode(msg.obj));
24582        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24583                System.identityHashCode(msg.obj));
24584
24585        mHandler.sendMessage(msg);
24586    }
24587
24588    @Override
24589    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24590        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24591
24592        final int realMoveId = mNextMoveId.getAndIncrement();
24593        final Bundle extras = new Bundle();
24594        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24595        mMoveCallbacks.notifyCreated(realMoveId, extras);
24596
24597        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24598            @Override
24599            public void onCreated(int moveId, Bundle extras) {
24600                // Ignored
24601            }
24602
24603            @Override
24604            public void onStatusChanged(int moveId, int status, long estMillis) {
24605                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24606            }
24607        };
24608
24609        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24610        storage.setPrimaryStorageUuid(volumeUuid, callback);
24611        return realMoveId;
24612    }
24613
24614    @Override
24615    public int getMoveStatus(int moveId) {
24616        mContext.enforceCallingOrSelfPermission(
24617                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24618        return mMoveCallbacks.mLastStatus.get(moveId);
24619    }
24620
24621    @Override
24622    public void registerMoveCallback(IPackageMoveObserver callback) {
24623        mContext.enforceCallingOrSelfPermission(
24624                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24625        mMoveCallbacks.register(callback);
24626    }
24627
24628    @Override
24629    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24630        mContext.enforceCallingOrSelfPermission(
24631                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24632        mMoveCallbacks.unregister(callback);
24633    }
24634
24635    @Override
24636    public boolean setInstallLocation(int loc) {
24637        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24638                null);
24639        if (getInstallLocation() == loc) {
24640            return true;
24641        }
24642        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24643                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24644            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24645                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24646            return true;
24647        }
24648        return false;
24649   }
24650
24651    @Override
24652    public int getInstallLocation() {
24653        // allow instant app access
24654        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24655                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24656                PackageHelper.APP_INSTALL_AUTO);
24657    }
24658
24659    /** Called by UserManagerService */
24660    void cleanUpUser(UserManagerService userManager, int userHandle) {
24661        synchronized (mPackages) {
24662            mDirtyUsers.remove(userHandle);
24663            mUserNeedsBadging.delete(userHandle);
24664            mSettings.removeUserLPw(userHandle);
24665            mPendingBroadcasts.remove(userHandle);
24666            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24667            removeUnusedPackagesLPw(userManager, userHandle);
24668        }
24669    }
24670
24671    /**
24672     * We're removing userHandle and would like to remove any downloaded packages
24673     * that are no longer in use by any other user.
24674     * @param userHandle the user being removed
24675     */
24676    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24677        final boolean DEBUG_CLEAN_APKS = false;
24678        int [] users = userManager.getUserIds();
24679        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24680        while (psit.hasNext()) {
24681            PackageSetting ps = psit.next();
24682            if (ps.pkg == null) {
24683                continue;
24684            }
24685            final String packageName = ps.pkg.packageName;
24686            // Skip over if system app
24687            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24688                continue;
24689            }
24690            if (DEBUG_CLEAN_APKS) {
24691                Slog.i(TAG, "Checking package " + packageName);
24692            }
24693            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24694            if (keep) {
24695                if (DEBUG_CLEAN_APKS) {
24696                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24697                }
24698            } else {
24699                for (int i = 0; i < users.length; i++) {
24700                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24701                        keep = true;
24702                        if (DEBUG_CLEAN_APKS) {
24703                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24704                                    + users[i]);
24705                        }
24706                        break;
24707                    }
24708                }
24709            }
24710            if (!keep) {
24711                if (DEBUG_CLEAN_APKS) {
24712                    Slog.i(TAG, "  Removing package " + packageName);
24713                }
24714                mHandler.post(new Runnable() {
24715                    public void run() {
24716                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24717                                userHandle, 0);
24718                    } //end run
24719                });
24720            }
24721        }
24722    }
24723
24724    /** Called by UserManagerService */
24725    void createNewUser(int userId, String[] disallowedPackages) {
24726        synchronized (mInstallLock) {
24727            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24728        }
24729        synchronized (mPackages) {
24730            scheduleWritePackageRestrictionsLocked(userId);
24731            scheduleWritePackageListLocked(userId);
24732            applyFactoryDefaultBrowserLPw(userId);
24733            primeDomainVerificationsLPw(userId);
24734        }
24735    }
24736
24737    void onNewUserCreated(final int userId) {
24738        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24739        // If permission review for legacy apps is required, we represent
24740        // dagerous permissions for such apps as always granted runtime
24741        // permissions to keep per user flag state whether review is needed.
24742        // Hence, if a new user is added we have to propagate dangerous
24743        // permission grants for these legacy apps.
24744        if (mPermissionReviewRequired) {
24745            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24746                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24747        }
24748    }
24749
24750    @Override
24751    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24752        mContext.enforceCallingOrSelfPermission(
24753                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24754                "Only package verification agents can read the verifier device identity");
24755
24756        synchronized (mPackages) {
24757            return mSettings.getVerifierDeviceIdentityLPw();
24758        }
24759    }
24760
24761    @Override
24762    public void setPermissionEnforced(String permission, boolean enforced) {
24763        // TODO: Now that we no longer change GID for storage, this should to away.
24764        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24765                "setPermissionEnforced");
24766        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24767            synchronized (mPackages) {
24768                if (mSettings.mReadExternalStorageEnforced == null
24769                        || mSettings.mReadExternalStorageEnforced != enforced) {
24770                    mSettings.mReadExternalStorageEnforced = enforced;
24771                    mSettings.writeLPr();
24772                }
24773            }
24774            // kill any non-foreground processes so we restart them and
24775            // grant/revoke the GID.
24776            final IActivityManager am = ActivityManager.getService();
24777            if (am != null) {
24778                final long token = Binder.clearCallingIdentity();
24779                try {
24780                    am.killProcessesBelowForeground("setPermissionEnforcement");
24781                } catch (RemoteException e) {
24782                } finally {
24783                    Binder.restoreCallingIdentity(token);
24784                }
24785            }
24786        } else {
24787            throw new IllegalArgumentException("No selective enforcement for " + permission);
24788        }
24789    }
24790
24791    @Override
24792    @Deprecated
24793    public boolean isPermissionEnforced(String permission) {
24794        // allow instant applications
24795        return true;
24796    }
24797
24798    @Override
24799    public boolean isStorageLow() {
24800        // allow instant applications
24801        final long token = Binder.clearCallingIdentity();
24802        try {
24803            final DeviceStorageMonitorInternal
24804                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24805            if (dsm != null) {
24806                return dsm.isMemoryLow();
24807            } else {
24808                return false;
24809            }
24810        } finally {
24811            Binder.restoreCallingIdentity(token);
24812        }
24813    }
24814
24815    @Override
24816    public IPackageInstaller getPackageInstaller() {
24817        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24818            return null;
24819        }
24820        return mInstallerService;
24821    }
24822
24823    private boolean userNeedsBadging(int userId) {
24824        int index = mUserNeedsBadging.indexOfKey(userId);
24825        if (index < 0) {
24826            final UserInfo userInfo;
24827            final long token = Binder.clearCallingIdentity();
24828            try {
24829                userInfo = sUserManager.getUserInfo(userId);
24830            } finally {
24831                Binder.restoreCallingIdentity(token);
24832            }
24833            final boolean b;
24834            if (userInfo != null && userInfo.isManagedProfile()) {
24835                b = true;
24836            } else {
24837                b = false;
24838            }
24839            mUserNeedsBadging.put(userId, b);
24840            return b;
24841        }
24842        return mUserNeedsBadging.valueAt(index);
24843    }
24844
24845    @Override
24846    public KeySet getKeySetByAlias(String packageName, String alias) {
24847        if (packageName == null || alias == null) {
24848            return null;
24849        }
24850        synchronized(mPackages) {
24851            final PackageParser.Package pkg = mPackages.get(packageName);
24852            if (pkg == null) {
24853                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24854                throw new IllegalArgumentException("Unknown package: " + packageName);
24855            }
24856            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24857            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24858                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24859                throw new IllegalArgumentException("Unknown package: " + packageName);
24860            }
24861            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24862            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24863        }
24864    }
24865
24866    @Override
24867    public KeySet getSigningKeySet(String packageName) {
24868        if (packageName == null) {
24869            return null;
24870        }
24871        synchronized(mPackages) {
24872            final int callingUid = Binder.getCallingUid();
24873            final int callingUserId = UserHandle.getUserId(callingUid);
24874            final PackageParser.Package pkg = mPackages.get(packageName);
24875            if (pkg == null) {
24876                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24877                throw new IllegalArgumentException("Unknown package: " + packageName);
24878            }
24879            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24880            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24881                // filter and pretend the package doesn't exist
24882                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24883                        + ", uid:" + callingUid);
24884                throw new IllegalArgumentException("Unknown package: " + packageName);
24885            }
24886            if (pkg.applicationInfo.uid != callingUid
24887                    && Process.SYSTEM_UID != callingUid) {
24888                throw new SecurityException("May not access signing KeySet of other apps.");
24889            }
24890            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24891            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24892        }
24893    }
24894
24895    @Override
24896    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24897        final int callingUid = Binder.getCallingUid();
24898        if (getInstantAppPackageName(callingUid) != null) {
24899            return false;
24900        }
24901        if (packageName == null || ks == null) {
24902            return false;
24903        }
24904        synchronized(mPackages) {
24905            final PackageParser.Package pkg = mPackages.get(packageName);
24906            if (pkg == null
24907                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24908                            UserHandle.getUserId(callingUid))) {
24909                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24910                throw new IllegalArgumentException("Unknown package: " + packageName);
24911            }
24912            IBinder ksh = ks.getToken();
24913            if (ksh instanceof KeySetHandle) {
24914                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24915                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24916            }
24917            return false;
24918        }
24919    }
24920
24921    @Override
24922    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24923        final int callingUid = Binder.getCallingUid();
24924        if (getInstantAppPackageName(callingUid) != null) {
24925            return false;
24926        }
24927        if (packageName == null || ks == null) {
24928            return false;
24929        }
24930        synchronized(mPackages) {
24931            final PackageParser.Package pkg = mPackages.get(packageName);
24932            if (pkg == null
24933                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24934                            UserHandle.getUserId(callingUid))) {
24935                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24936                throw new IllegalArgumentException("Unknown package: " + packageName);
24937            }
24938            IBinder ksh = ks.getToken();
24939            if (ksh instanceof KeySetHandle) {
24940                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24941                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24942            }
24943            return false;
24944        }
24945    }
24946
24947    private void deletePackageIfUnusedLPr(final String packageName) {
24948        PackageSetting ps = mSettings.mPackages.get(packageName);
24949        if (ps == null) {
24950            return;
24951        }
24952        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24953            // TODO Implement atomic delete if package is unused
24954            // It is currently possible that the package will be deleted even if it is installed
24955            // after this method returns.
24956            mHandler.post(new Runnable() {
24957                public void run() {
24958                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24959                            0, PackageManager.DELETE_ALL_USERS);
24960                }
24961            });
24962        }
24963    }
24964
24965    /**
24966     * Check and throw if the given before/after packages would be considered a
24967     * downgrade.
24968     */
24969    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24970            throws PackageManagerException {
24971        if (after.versionCode < before.mVersionCode) {
24972            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24973                    "Update version code " + after.versionCode + " is older than current "
24974                    + before.mVersionCode);
24975        } else if (after.versionCode == before.mVersionCode) {
24976            if (after.baseRevisionCode < before.baseRevisionCode) {
24977                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24978                        "Update base revision code " + after.baseRevisionCode
24979                        + " is older than current " + before.baseRevisionCode);
24980            }
24981
24982            if (!ArrayUtils.isEmpty(after.splitNames)) {
24983                for (int i = 0; i < after.splitNames.length; i++) {
24984                    final String splitName = after.splitNames[i];
24985                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24986                    if (j != -1) {
24987                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24988                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24989                                    "Update split " + splitName + " revision code "
24990                                    + after.splitRevisionCodes[i] + " is older than current "
24991                                    + before.splitRevisionCodes[j]);
24992                        }
24993                    }
24994                }
24995            }
24996        }
24997    }
24998
24999    private static class MoveCallbacks extends Handler {
25000        private static final int MSG_CREATED = 1;
25001        private static final int MSG_STATUS_CHANGED = 2;
25002
25003        private final RemoteCallbackList<IPackageMoveObserver>
25004                mCallbacks = new RemoteCallbackList<>();
25005
25006        private final SparseIntArray mLastStatus = new SparseIntArray();
25007
25008        public MoveCallbacks(Looper looper) {
25009            super(looper);
25010        }
25011
25012        public void register(IPackageMoveObserver callback) {
25013            mCallbacks.register(callback);
25014        }
25015
25016        public void unregister(IPackageMoveObserver callback) {
25017            mCallbacks.unregister(callback);
25018        }
25019
25020        @Override
25021        public void handleMessage(Message msg) {
25022            final SomeArgs args = (SomeArgs) msg.obj;
25023            final int n = mCallbacks.beginBroadcast();
25024            for (int i = 0; i < n; i++) {
25025                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
25026                try {
25027                    invokeCallback(callback, msg.what, args);
25028                } catch (RemoteException ignored) {
25029                }
25030            }
25031            mCallbacks.finishBroadcast();
25032            args.recycle();
25033        }
25034
25035        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
25036                throws RemoteException {
25037            switch (what) {
25038                case MSG_CREATED: {
25039                    callback.onCreated(args.argi1, (Bundle) args.arg2);
25040                    break;
25041                }
25042                case MSG_STATUS_CHANGED: {
25043                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
25044                    break;
25045                }
25046            }
25047        }
25048
25049        private void notifyCreated(int moveId, Bundle extras) {
25050            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
25051
25052            final SomeArgs args = SomeArgs.obtain();
25053            args.argi1 = moveId;
25054            args.arg2 = extras;
25055            obtainMessage(MSG_CREATED, args).sendToTarget();
25056        }
25057
25058        private void notifyStatusChanged(int moveId, int status) {
25059            notifyStatusChanged(moveId, status, -1);
25060        }
25061
25062        private void notifyStatusChanged(int moveId, int status, long estMillis) {
25063            Slog.v(TAG, "Move " + moveId + " status " + status);
25064
25065            final SomeArgs args = SomeArgs.obtain();
25066            args.argi1 = moveId;
25067            args.argi2 = status;
25068            args.arg3 = estMillis;
25069            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
25070
25071            synchronized (mLastStatus) {
25072                mLastStatus.put(moveId, status);
25073            }
25074        }
25075    }
25076
25077    private final static class OnPermissionChangeListeners extends Handler {
25078        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
25079
25080        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
25081                new RemoteCallbackList<>();
25082
25083        public OnPermissionChangeListeners(Looper looper) {
25084            super(looper);
25085        }
25086
25087        @Override
25088        public void handleMessage(Message msg) {
25089            switch (msg.what) {
25090                case MSG_ON_PERMISSIONS_CHANGED: {
25091                    final int uid = msg.arg1;
25092                    handleOnPermissionsChanged(uid);
25093                } break;
25094            }
25095        }
25096
25097        public void addListenerLocked(IOnPermissionsChangeListener listener) {
25098            mPermissionListeners.register(listener);
25099
25100        }
25101
25102        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
25103            mPermissionListeners.unregister(listener);
25104        }
25105
25106        public void onPermissionsChanged(int uid) {
25107            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
25108                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
25109            }
25110        }
25111
25112        private void handleOnPermissionsChanged(int uid) {
25113            final int count = mPermissionListeners.beginBroadcast();
25114            try {
25115                for (int i = 0; i < count; i++) {
25116                    IOnPermissionsChangeListener callback = mPermissionListeners
25117                            .getBroadcastItem(i);
25118                    try {
25119                        callback.onPermissionsChanged(uid);
25120                    } catch (RemoteException e) {
25121                        Log.e(TAG, "Permission listener is dead", e);
25122                    }
25123                }
25124            } finally {
25125                mPermissionListeners.finishBroadcast();
25126            }
25127        }
25128    }
25129
25130    private class PackageManagerNative extends IPackageManagerNative.Stub {
25131        @Override
25132        public String[] getNamesForUids(int[] uids) throws RemoteException {
25133            final String[] results = PackageManagerService.this.getNamesForUids(uids);
25134            // massage results so they can be parsed by the native binder
25135            for (int i = results.length - 1; i >= 0; --i) {
25136                if (results[i] == null) {
25137                    results[i] = "";
25138                }
25139            }
25140            return results;
25141        }
25142    }
25143
25144    private class PackageManagerInternalImpl extends PackageManagerInternal {
25145        @Override
25146        public void setLocationPackagesProvider(PackagesProvider provider) {
25147            synchronized (mPackages) {
25148                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
25149            }
25150        }
25151
25152        @Override
25153        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
25154            synchronized (mPackages) {
25155                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
25156            }
25157        }
25158
25159        @Override
25160        public void setSmsAppPackagesProvider(PackagesProvider provider) {
25161            synchronized (mPackages) {
25162                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
25163            }
25164        }
25165
25166        @Override
25167        public void setDialerAppPackagesProvider(PackagesProvider provider) {
25168            synchronized (mPackages) {
25169                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
25170            }
25171        }
25172
25173        @Override
25174        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
25175            synchronized (mPackages) {
25176                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
25177            }
25178        }
25179
25180        @Override
25181        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
25182            synchronized (mPackages) {
25183                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
25184            }
25185        }
25186
25187        @Override
25188        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
25189            synchronized (mPackages) {
25190                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
25191                        packageName, userId);
25192            }
25193        }
25194
25195        @Override
25196        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
25197            synchronized (mPackages) {
25198                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
25199                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
25200                        packageName, userId);
25201            }
25202        }
25203
25204        @Override
25205        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
25206            synchronized (mPackages) {
25207                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
25208                        packageName, userId);
25209            }
25210        }
25211
25212        @Override
25213        public void setKeepUninstalledPackages(final List<String> packageList) {
25214            Preconditions.checkNotNull(packageList);
25215            List<String> removedFromList = null;
25216            synchronized (mPackages) {
25217                if (mKeepUninstalledPackages != null) {
25218                    final int packagesCount = mKeepUninstalledPackages.size();
25219                    for (int i = 0; i < packagesCount; i++) {
25220                        String oldPackage = mKeepUninstalledPackages.get(i);
25221                        if (packageList != null && packageList.contains(oldPackage)) {
25222                            continue;
25223                        }
25224                        if (removedFromList == null) {
25225                            removedFromList = new ArrayList<>();
25226                        }
25227                        removedFromList.add(oldPackage);
25228                    }
25229                }
25230                mKeepUninstalledPackages = new ArrayList<>(packageList);
25231                if (removedFromList != null) {
25232                    final int removedCount = removedFromList.size();
25233                    for (int i = 0; i < removedCount; i++) {
25234                        deletePackageIfUnusedLPr(removedFromList.get(i));
25235                    }
25236                }
25237            }
25238        }
25239
25240        @Override
25241        public boolean isPermissionsReviewRequired(String packageName, int userId) {
25242            synchronized (mPackages) {
25243                // If we do not support permission review, done.
25244                if (!mPermissionReviewRequired) {
25245                    return false;
25246                }
25247
25248                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
25249                if (packageSetting == null) {
25250                    return false;
25251                }
25252
25253                // Permission review applies only to apps not supporting the new permission model.
25254                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
25255                    return false;
25256                }
25257
25258                // Legacy apps have the permission and get user consent on launch.
25259                PermissionsState permissionsState = packageSetting.getPermissionsState();
25260                return permissionsState.isPermissionReviewRequired(userId);
25261            }
25262        }
25263
25264        @Override
25265        public PackageInfo getPackageInfo(
25266                String packageName, int flags, int filterCallingUid, int userId) {
25267            return PackageManagerService.this
25268                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25269                            flags, filterCallingUid, userId);
25270        }
25271
25272        @Override
25273        public ApplicationInfo getApplicationInfo(
25274                String packageName, int flags, int filterCallingUid, int userId) {
25275            return PackageManagerService.this
25276                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25277        }
25278
25279        @Override
25280        public ActivityInfo getActivityInfo(
25281                ComponentName component, int flags, int filterCallingUid, int userId) {
25282            return PackageManagerService.this
25283                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25284        }
25285
25286        @Override
25287        public List<ResolveInfo> queryIntentActivities(
25288                Intent intent, int flags, int filterCallingUid, int userId) {
25289            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25290            return PackageManagerService.this
25291                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25292                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25293        }
25294
25295        @Override
25296        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25297                int userId) {
25298            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25299        }
25300
25301        @Override
25302        public void setDeviceAndProfileOwnerPackages(
25303                int deviceOwnerUserId, String deviceOwnerPackage,
25304                SparseArray<String> profileOwnerPackages) {
25305            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25306                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25307        }
25308
25309        @Override
25310        public boolean isPackageDataProtected(int userId, String packageName) {
25311            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25312        }
25313
25314        @Override
25315        public boolean isPackageEphemeral(int userId, String packageName) {
25316            synchronized (mPackages) {
25317                final PackageSetting ps = mSettings.mPackages.get(packageName);
25318                return ps != null ? ps.getInstantApp(userId) : false;
25319            }
25320        }
25321
25322        @Override
25323        public boolean wasPackageEverLaunched(String packageName, int userId) {
25324            synchronized (mPackages) {
25325                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25326            }
25327        }
25328
25329        @Override
25330        public void grantRuntimePermission(String packageName, String name, int userId,
25331                boolean overridePolicy) {
25332            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25333                    overridePolicy);
25334        }
25335
25336        @Override
25337        public void revokeRuntimePermission(String packageName, String name, int userId,
25338                boolean overridePolicy) {
25339            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25340                    overridePolicy);
25341        }
25342
25343        @Override
25344        public String getNameForUid(int uid) {
25345            return PackageManagerService.this.getNameForUid(uid);
25346        }
25347
25348        @Override
25349        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25350                Intent origIntent, String resolvedType, String callingPackage,
25351                Bundle verificationBundle, int userId) {
25352            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25353                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25354                    userId);
25355        }
25356
25357        @Override
25358        public void grantEphemeralAccess(int userId, Intent intent,
25359                int targetAppId, int ephemeralAppId) {
25360            synchronized (mPackages) {
25361                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25362                        targetAppId, ephemeralAppId);
25363            }
25364        }
25365
25366        @Override
25367        public boolean isInstantAppInstallerComponent(ComponentName component) {
25368            synchronized (mPackages) {
25369                return mInstantAppInstallerActivity != null
25370                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25371            }
25372        }
25373
25374        @Override
25375        public void pruneInstantApps() {
25376            mInstantAppRegistry.pruneInstantApps();
25377        }
25378
25379        @Override
25380        public String getSetupWizardPackageName() {
25381            return mSetupWizardPackage;
25382        }
25383
25384        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25385            if (policy != null) {
25386                mExternalSourcesPolicy = policy;
25387            }
25388        }
25389
25390        @Override
25391        public boolean isPackagePersistent(String packageName) {
25392            synchronized (mPackages) {
25393                PackageParser.Package pkg = mPackages.get(packageName);
25394                return pkg != null
25395                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25396                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25397                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25398                        : false;
25399            }
25400        }
25401
25402        @Override
25403        public List<PackageInfo> getOverlayPackages(int userId) {
25404            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25405            synchronized (mPackages) {
25406                for (PackageParser.Package p : mPackages.values()) {
25407                    if (p.mOverlayTarget != null) {
25408                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25409                        if (pkg != null) {
25410                            overlayPackages.add(pkg);
25411                        }
25412                    }
25413                }
25414            }
25415            return overlayPackages;
25416        }
25417
25418        @Override
25419        public List<String> getTargetPackageNames(int userId) {
25420            List<String> targetPackages = new ArrayList<>();
25421            synchronized (mPackages) {
25422                for (PackageParser.Package p : mPackages.values()) {
25423                    if (p.mOverlayTarget == null) {
25424                        targetPackages.add(p.packageName);
25425                    }
25426                }
25427            }
25428            return targetPackages;
25429        }
25430
25431        @Override
25432        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25433                @Nullable List<String> overlayPackageNames) {
25434            synchronized (mPackages) {
25435                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25436                    Slog.e(TAG, "failed to find package " + targetPackageName);
25437                    return false;
25438                }
25439                ArrayList<String> overlayPaths = null;
25440                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25441                    final int N = overlayPackageNames.size();
25442                    overlayPaths = new ArrayList<>(N);
25443                    for (int i = 0; i < N; i++) {
25444                        final String packageName = overlayPackageNames.get(i);
25445                        final PackageParser.Package pkg = mPackages.get(packageName);
25446                        if (pkg == null) {
25447                            Slog.e(TAG, "failed to find package " + packageName);
25448                            return false;
25449                        }
25450                        overlayPaths.add(pkg.baseCodePath);
25451                    }
25452                }
25453
25454                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25455                ps.setOverlayPaths(overlayPaths, userId);
25456                return true;
25457            }
25458        }
25459
25460        @Override
25461        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25462                int flags, int userId) {
25463            return resolveIntentInternal(
25464                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25465        }
25466
25467        @Override
25468        public ResolveInfo resolveService(Intent intent, String resolvedType,
25469                int flags, int userId, int callingUid) {
25470            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25471        }
25472
25473        @Override
25474        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25475            synchronized (mPackages) {
25476                mIsolatedOwners.put(isolatedUid, ownerUid);
25477            }
25478        }
25479
25480        @Override
25481        public void removeIsolatedUid(int isolatedUid) {
25482            synchronized (mPackages) {
25483                mIsolatedOwners.delete(isolatedUid);
25484            }
25485        }
25486
25487        @Override
25488        public int getUidTargetSdkVersion(int uid) {
25489            synchronized (mPackages) {
25490                return getUidTargetSdkVersionLockedLPr(uid);
25491            }
25492        }
25493
25494        @Override
25495        public boolean canAccessInstantApps(int callingUid, int userId) {
25496            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25497        }
25498
25499        @Override
25500        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
25501            synchronized (mPackages) {
25502                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
25503            }
25504        }
25505    }
25506
25507    @Override
25508    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25509        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25510        synchronized (mPackages) {
25511            final long identity = Binder.clearCallingIdentity();
25512            try {
25513                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25514                        packageNames, userId);
25515            } finally {
25516                Binder.restoreCallingIdentity(identity);
25517            }
25518        }
25519    }
25520
25521    @Override
25522    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25523        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25524        synchronized (mPackages) {
25525            final long identity = Binder.clearCallingIdentity();
25526            try {
25527                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25528                        packageNames, userId);
25529            } finally {
25530                Binder.restoreCallingIdentity(identity);
25531            }
25532        }
25533    }
25534
25535    private static void enforceSystemOrPhoneCaller(String tag) {
25536        int callingUid = Binder.getCallingUid();
25537        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25538            throw new SecurityException(
25539                    "Cannot call " + tag + " from UID " + callingUid);
25540        }
25541    }
25542
25543    boolean isHistoricalPackageUsageAvailable() {
25544        return mPackageUsage.isHistoricalPackageUsageAvailable();
25545    }
25546
25547    /**
25548     * Return a <b>copy</b> of the collection of packages known to the package manager.
25549     * @return A copy of the values of mPackages.
25550     */
25551    Collection<PackageParser.Package> getPackages() {
25552        synchronized (mPackages) {
25553            return new ArrayList<>(mPackages.values());
25554        }
25555    }
25556
25557    /**
25558     * Logs process start information (including base APK hash) to the security log.
25559     * @hide
25560     */
25561    @Override
25562    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25563            String apkFile, int pid) {
25564        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25565            return;
25566        }
25567        if (!SecurityLog.isLoggingEnabled()) {
25568            return;
25569        }
25570        Bundle data = new Bundle();
25571        data.putLong("startTimestamp", System.currentTimeMillis());
25572        data.putString("processName", processName);
25573        data.putInt("uid", uid);
25574        data.putString("seinfo", seinfo);
25575        data.putString("apkFile", apkFile);
25576        data.putInt("pid", pid);
25577        Message msg = mProcessLoggingHandler.obtainMessage(
25578                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25579        msg.setData(data);
25580        mProcessLoggingHandler.sendMessage(msg);
25581    }
25582
25583    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25584        return mCompilerStats.getPackageStats(pkgName);
25585    }
25586
25587    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25588        return getOrCreateCompilerPackageStats(pkg.packageName);
25589    }
25590
25591    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25592        return mCompilerStats.getOrCreatePackageStats(pkgName);
25593    }
25594
25595    public void deleteCompilerPackageStats(String pkgName) {
25596        mCompilerStats.deletePackageStats(pkgName);
25597    }
25598
25599    @Override
25600    public int getInstallReason(String packageName, int userId) {
25601        final int callingUid = Binder.getCallingUid();
25602        enforceCrossUserPermission(callingUid, userId,
25603                true /* requireFullPermission */, false /* checkShell */,
25604                "get install reason");
25605        synchronized (mPackages) {
25606            final PackageSetting ps = mSettings.mPackages.get(packageName);
25607            if (filterAppAccessLPr(ps, callingUid, userId)) {
25608                return PackageManager.INSTALL_REASON_UNKNOWN;
25609            }
25610            if (ps != null) {
25611                return ps.getInstallReason(userId);
25612            }
25613        }
25614        return PackageManager.INSTALL_REASON_UNKNOWN;
25615    }
25616
25617    @Override
25618    public boolean canRequestPackageInstalls(String packageName, int userId) {
25619        return canRequestPackageInstallsInternal(packageName, 0, userId,
25620                true /* throwIfPermNotDeclared*/);
25621    }
25622
25623    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25624            boolean throwIfPermNotDeclared) {
25625        int callingUid = Binder.getCallingUid();
25626        int uid = getPackageUid(packageName, 0, userId);
25627        if (callingUid != uid && callingUid != Process.ROOT_UID
25628                && callingUid != Process.SYSTEM_UID) {
25629            throw new SecurityException(
25630                    "Caller uid " + callingUid + " does not own package " + packageName);
25631        }
25632        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25633        if (info == null) {
25634            return false;
25635        }
25636        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25637            return false;
25638        }
25639        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25640        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25641        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25642            if (throwIfPermNotDeclared) {
25643                throw new SecurityException("Need to declare " + appOpPermission
25644                        + " to call this api");
25645            } else {
25646                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25647                return false;
25648            }
25649        }
25650        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25651            return false;
25652        }
25653        if (mExternalSourcesPolicy != null) {
25654            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25655            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25656                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25657            }
25658        }
25659        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25660    }
25661
25662    @Override
25663    public ComponentName getInstantAppResolverSettingsComponent() {
25664        return mInstantAppResolverSettingsComponent;
25665    }
25666
25667    @Override
25668    public ComponentName getInstantAppInstallerComponent() {
25669        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25670            return null;
25671        }
25672        return mInstantAppInstallerActivity == null
25673                ? null : mInstantAppInstallerActivity.getComponentName();
25674    }
25675
25676    @Override
25677    public String getInstantAppAndroidId(String packageName, int userId) {
25678        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25679                "getInstantAppAndroidId");
25680        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25681                true /* requireFullPermission */, false /* checkShell */,
25682                "getInstantAppAndroidId");
25683        // Make sure the target is an Instant App.
25684        if (!isInstantApp(packageName, userId)) {
25685            return null;
25686        }
25687        synchronized (mPackages) {
25688            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25689        }
25690    }
25691
25692    boolean canHaveOatDir(String packageName) {
25693        synchronized (mPackages) {
25694            PackageParser.Package p = mPackages.get(packageName);
25695            if (p == null) {
25696                return false;
25697            }
25698            return p.canHaveOatDir();
25699        }
25700    }
25701
25702    private String getOatDir(PackageParser.Package pkg) {
25703        if (!pkg.canHaveOatDir()) {
25704            return null;
25705        }
25706        File codePath = new File(pkg.codePath);
25707        if (codePath.isDirectory()) {
25708            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25709        }
25710        return null;
25711    }
25712
25713    void deleteOatArtifactsOfPackage(String packageName) {
25714        final String[] instructionSets;
25715        final List<String> codePaths;
25716        final String oatDir;
25717        final PackageParser.Package pkg;
25718        synchronized (mPackages) {
25719            pkg = mPackages.get(packageName);
25720        }
25721        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25722        codePaths = pkg.getAllCodePaths();
25723        oatDir = getOatDir(pkg);
25724
25725        for (String codePath : codePaths) {
25726            for (String isa : instructionSets) {
25727                try {
25728                    mInstaller.deleteOdex(codePath, isa, oatDir);
25729                } catch (InstallerException e) {
25730                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25731                }
25732            }
25733        }
25734    }
25735
25736    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25737        Set<String> unusedPackages = new HashSet<>();
25738        long currentTimeInMillis = System.currentTimeMillis();
25739        synchronized (mPackages) {
25740            for (PackageParser.Package pkg : mPackages.values()) {
25741                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25742                if (ps == null) {
25743                    continue;
25744                }
25745                PackageDexUsage.PackageUseInfo packageUseInfo =
25746                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25747                if (PackageManagerServiceUtils
25748                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25749                                downgradeTimeThresholdMillis, packageUseInfo,
25750                                pkg.getLatestPackageUseTimeInMills(),
25751                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25752                    unusedPackages.add(pkg.packageName);
25753                }
25754            }
25755        }
25756        return unusedPackages;
25757    }
25758}
25759
25760interface PackageSender {
25761    void sendPackageBroadcast(final String action, final String pkg,
25762        final Bundle extras, final int flags, final String targetPkg,
25763        final IIntentReceiver finishedReceiver, final int[] userIds);
25764    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25765        boolean includeStopped, int appId, int... userIds);
25766}
25767